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
RJPercival/certificate-transparency
python/ct/crypto/asn1/tag.py
35
4183
"""ASN.1 tagging.""" from ct.crypto import error UNIVERSAL = 0x00 APPLICATION = 0x40 CONTEXT_SPECIFIC = 0x80 PRIVATE = 0xc0 PRIMITIVE = 0x00 CONSTRUCTED = 0x20 # Constants for better readability. IMPLICIT, EXPLICIT = range(2) class Tag(object): """An ASN.1 tag.""" _CLASS_MASK = 0xc0 _ENCODING_MASK = 0x20 _NUMBER_MASK = 0x1f _HIGH = 0x1f _FULL_SUB_OCTET = 0x7f _LAST_OCTET = 0x80 def __init__(self, number, tag_class, encoding): """ASN.1 tag. Initialize a tag from its number, class and encoding. Args: number: the numeric value of the tag. tag_class: must be one of UNIVERSAL, APPLICATION, CONTEXT_SPECIFIC or PRIVATE. encoding: must be one of PRIMITIVE or CONSTRUCTED. Raises: ValueError: invalid initializers. """ if tag_class not in (UNIVERSAL, APPLICATION, CONTEXT_SPECIFIC, PRIVATE): raise ValueError("Invalid tag class %s" % tag_class) if encoding not in (PRIMITIVE, CONSTRUCTED): raise ValueError("Invalid encoding %s" % encoding) # Public just for lightweight access. Do not modify directly. self.number = number self.tag_class = tag_class self.encoding = encoding if number <= 30: self.value = chr(tag_class | encoding | number) else: res = [tag_class | encoding | self._HIGH] tmp = [] while number > 0: tmp.append((number & self._FULL_SUB_OCTET) | self._LAST_OCTET) number >>= 7 tmp[0] -= self._LAST_OCTET tmp.reverse() res += tmp self.value = ''.join([chr(byte) for byte in res]) def __repr__(self): return ("%s(%r, %r, %r)" % (self.__class__.__name__, self.number, self.tag_class, self.encoding)) def __str__(self): return "[%s %d]" % (self.class_name(), self.number) def __len__(self): return len(self.value) def class_name(self): if self.tag_class == UNIVERSAL: return "UNIVERSAL" elif self.tag_class == APPLICATION: return "APPLICATION" elif self.tag_class == CONTEXT_SPECIFIC: return "CONTEXT-SPECIFIC" elif self.tag_class == PRIVATE: return "PRIVATE" else: raise ValueError("Invalid tag class %x" % self.tag_class) def __hash__(self): return hash(self.value) def __eq__(self, other): if not isinstance(other, Tag): return NotImplemented return self.value == other.value def __ne__(self, other): if not isinstance(other, Tag): return NotImplemented return self.value != other.value @classmethod def read(cls, buf): """Read from the beginning of a string or buffer. Args: buf: a binary string or string buffer containing an ASN.1 object. Returns: an tuple consisting of an instance of the class and the remaining buffer/string. """ if not buf: raise error.ASN1TagError("Ran out of bytes while decoding") tag_bytes = 0 id_byte = ord(buf[tag_bytes]) tag_class = id_byte & cls._CLASS_MASK encoding = id_byte & cls._ENCODING_MASK number = id_byte & cls._NUMBER_MASK if number == cls._HIGH: number = 0 tag_bytes += 1 success = False for i in range(1, len(buf)): number <<= 7 id_byte = ord(buf[i]) number |= (id_byte & cls._FULL_SUB_OCTET) tag_bytes += 1 if id_byte & cls._LAST_OCTET == 0: success = True break if not success: raise error.ASN1TagError("Ran out of bytes while decoding") if tag_bytes - 1 > 5: raise error.ASN1TagError("Base 128 integer too large") tag_bytes -= 1 tag = cls(number, tag_class, encoding) return tag, buf[tag_bytes + 1:]
apache-2.0
cms-externals/openloops
scons-local/scons-local-2.3.0/SCons/Util.py
11
49066
"""SCons.Util Various utility functions go here. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. __revision__ = "src/engine/SCons/Util.py 2013/03/03 09:48:35 garyo" import os import sys import copy import re import types from collections import UserDict, UserList, UserString # Don't "from types import ..." these because we need to get at the # types module later to look for UnicodeType. InstanceType = types.InstanceType MethodType = types.MethodType FunctionType = types.FunctionType try: unicode except NameError: UnicodeType = None else: UnicodeType = unicode def dictify(keys, values, result={}): for k, v in zip(keys, values): result[k] = v return result _altsep = os.altsep if _altsep is None and sys.platform == 'win32': # My ActivePython 2.0.1 doesn't set os.altsep! What gives? _altsep = '/' if _altsep: def rightmost_separator(path, sep): return max(path.rfind(sep), path.rfind(_altsep)) else: def rightmost_separator(path, sep): return path.rfind(sep) # First two from the Python Cookbook, just for completeness. # (Yeah, yeah, YAGNI...) def containsAny(str, set): """Check whether sequence str contains ANY of the items in set.""" for c in set: if c in str: return 1 return 0 def containsAll(str, set): """Check whether sequence str contains ALL of the items in set.""" for c in set: if c not in str: return 0 return 1 def containsOnly(str, set): """Check whether sequence str contains ONLY items in set.""" for c in str: if c not in set: return 0 return 1 def splitext(path): "Same as os.path.splitext() but faster." sep = rightmost_separator(path, os.sep) dot = path.rfind('.') # An ext is only real if it has at least one non-digit char if dot > sep and not containsOnly(path[dot:], "0123456789."): return path[:dot],path[dot:] else: return path,"" def updrive(path): """ Make the drive letter (if any) upper case. This is useful because Windows is inconsitent on the case of the drive letter, which can cause inconsistencies when calculating command signatures. """ drive, rest = os.path.splitdrive(path) if drive: path = drive.upper() + rest return path class NodeList(UserList): """This class is almost exactly like a regular list of Nodes (actually it can hold any object), with one important difference. If you try to get an attribute from this list, it will return that attribute from every item in the list. For example: >>> someList = NodeList([ ' foo ', ' bar ' ]) >>> someList.strip() [ 'foo', 'bar' ] """ def __nonzero__(self): return len(self.data) != 0 def __str__(self): return ' '.join(map(str, self.data)) def __iter__(self): return iter(self.data) def __call__(self, *args, **kwargs): result = [x(*args, **kwargs) for x in self.data] return self.__class__(result) def __getattr__(self, name): result = [getattr(x, name) for x in self.data] return self.__class__(result) _get_env_var = re.compile(r'^\$([_a-zA-Z]\w*|{[_a-zA-Z]\w*})$') def get_environment_var(varstr): """Given a string, first determine if it looks like a reference to a single environment variable, like "$FOO" or "${FOO}". If so, return that variable with no decorations ("FOO"). If not, return None.""" mo=_get_env_var.match(to_String(varstr)) if mo: var = mo.group(1) if var[0] == '{': return var[1:-1] else: return var else: return None class DisplayEngine(object): print_it = True def __call__(self, text, append_newline=1): if not self.print_it: return if append_newline: text = text + '\n' try: sys.stdout.write(unicode(text)) except IOError: # Stdout might be connected to a pipe that has been closed # by now. The most likely reason for the pipe being closed # is that the user has press ctrl-c. It this is the case, # then SCons is currently shutdown. We therefore ignore # IOError's here so that SCons can continue and shutdown # properly so that the .sconsign is correctly written # before SCons exits. pass def set_mode(self, mode): self.print_it = mode def render_tree(root, child_func, prune=0, margin=[0], visited={}): """ Render a tree of nodes into an ASCII tree view. root - the root node of the tree child_func - the function called to get the children of a node prune - don't visit the same node twice margin - the format of the left margin to use for children of root. 1 results in a pipe, and 0 results in no pipe. visited - a dictionary of visited nodes in the current branch if not prune, or in the whole tree if prune. """ rname = str(root) children = child_func(root) retval = "" for pipe in margin[:-1]: if pipe: retval = retval + "| " else: retval = retval + " " if rname in visited: return retval + "+-[" + rname + "]\n" retval = retval + "+-" + rname + "\n" if not prune: visited = copy.copy(visited) visited[rname] = 1 for i in range(len(children)): margin.append(i<len(children)-1) retval = retval + render_tree(children[i], child_func, prune, margin, visited ) margin.pop() return retval IDX = lambda N: N and 1 or 0 def print_tree(root, child_func, prune=0, showtags=0, margin=[0], visited={}): """ Print a tree of nodes. This is like render_tree, except it prints lines directly instead of creating a string representation in memory, so that huge trees can be printed. root - the root node of the tree child_func - the function called to get the children of a node prune - don't visit the same node twice showtags - print status information to the left of each node line margin - the format of the left margin to use for children of root. 1 results in a pipe, and 0 results in no pipe. visited - a dictionary of visited nodes in the current branch if not prune, or in the whole tree if prune. """ rname = str(root) if showtags: if showtags == 2: legend = (' E = exists\n' + ' R = exists in repository only\n' + ' b = implicit builder\n' + ' B = explicit builder\n' + ' S = side effect\n' + ' P = precious\n' + ' A = always build\n' + ' C = current\n' + ' N = no clean\n' + ' H = no cache\n' + '\n') sys.stdout.write(unicode(legend)) tags = ['['] tags.append(' E'[IDX(root.exists())]) tags.append(' R'[IDX(root.rexists() and not root.exists())]) tags.append(' BbB'[[0,1][IDX(root.has_explicit_builder())] + [0,2][IDX(root.has_builder())]]) tags.append(' S'[IDX(root.side_effect)]) tags.append(' P'[IDX(root.precious)]) tags.append(' A'[IDX(root.always_build)]) tags.append(' C'[IDX(root.is_up_to_date())]) tags.append(' N'[IDX(root.noclean)]) tags.append(' H'[IDX(root.nocache)]) tags.append(']') else: tags = [] def MMM(m): return [" ","| "][m] margins = list(map(MMM, margin[:-1])) children = child_func(root) if prune and rname in visited and children: sys.stdout.write(''.join(tags + margins + ['+-[', rname, ']']) + u'\n') return sys.stdout.write(''.join(tags + margins + ['+-', rname]) + u'\n') visited[rname] = 1 if children: margin.append(1) idx = IDX(showtags) for C in children[:-1]: print_tree(C, child_func, prune, idx, margin, visited) margin[-1] = 0 print_tree(children[-1], child_func, prune, idx, margin, visited) margin.pop() # Functions for deciding if things are like various types, mainly to # handle UserDict, UserList and UserString like their underlying types. # # Yes, all of this manual testing breaks polymorphism, and the real # Pythonic way to do all of this would be to just try it and handle the # exception, but handling the exception when it's not the right type is # often too slow. # We are using the following trick to speed up these # functions. Default arguments are used to take a snapshot of the # the global functions and constants used by these functions. This # transforms accesses to global variable into local variables # accesses (i.e. LOAD_FAST instead of LOAD_GLOBAL). DictTypes = (dict, UserDict) ListTypes = (list, UserList) SequenceTypes = (list, tuple, UserList) # Note that profiling data shows a speed-up when comparing # explicitely with str and unicode instead of simply comparing # with basestring. (at least on Python 2.5.1) StringTypes = (str, unicode, UserString) # Empirically, it is faster to check explicitely for str and # unicode than for basestring. BaseStringTypes = (str, unicode) def is_Dict(obj, isinstance=isinstance, DictTypes=DictTypes): return isinstance(obj, DictTypes) def is_List(obj, isinstance=isinstance, ListTypes=ListTypes): return isinstance(obj, ListTypes) def is_Sequence(obj, isinstance=isinstance, SequenceTypes=SequenceTypes): return isinstance(obj, SequenceTypes) def is_Tuple(obj, isinstance=isinstance, tuple=tuple): return isinstance(obj, tuple) def is_String(obj, isinstance=isinstance, StringTypes=StringTypes): return isinstance(obj, StringTypes) def is_Scalar(obj, isinstance=isinstance, StringTypes=StringTypes, SequenceTypes=SequenceTypes): # Profiling shows that there is an impressive speed-up of 2x # when explicitely checking for strings instead of just not # sequence when the argument (i.e. obj) is already a string. # But, if obj is a not string then it is twice as fast to # check only for 'not sequence'. The following code therefore # assumes that the obj argument is a string must of the time. return isinstance(obj, StringTypes) or not isinstance(obj, SequenceTypes) def do_flatten(sequence, result, isinstance=isinstance, StringTypes=StringTypes, SequenceTypes=SequenceTypes): for item in sequence: if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes): result.append(item) else: do_flatten(item, result) def flatten(obj, isinstance=isinstance, StringTypes=StringTypes, SequenceTypes=SequenceTypes, do_flatten=do_flatten): """Flatten a sequence to a non-nested list. Flatten() converts either a single scalar or a nested sequence to a non-nested list. Note that flatten() considers strings to be scalars instead of sequences like Python would. """ if isinstance(obj, StringTypes) or not isinstance(obj, SequenceTypes): return [obj] result = [] for item in obj: if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes): result.append(item) else: do_flatten(item, result) return result def flatten_sequence(sequence, isinstance=isinstance, StringTypes=StringTypes, SequenceTypes=SequenceTypes, do_flatten=do_flatten): """Flatten a sequence to a non-nested list. Same as flatten(), but it does not handle the single scalar case. This is slightly more efficient when one knows that the sequence to flatten can not be a scalar. """ result = [] for item in sequence: if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes): result.append(item) else: do_flatten(item, result) return result # Generic convert-to-string functions that abstract away whether or # not the Python we're executing has Unicode support. The wrapper # to_String_for_signature() will use a for_signature() method if the # specified object has one. # def to_String(s, isinstance=isinstance, str=str, UserString=UserString, BaseStringTypes=BaseStringTypes): if isinstance(s,BaseStringTypes): # Early out when already a string! return s elif isinstance(s, UserString): # s.data can only be either a unicode or a regular # string. Please see the UserString initializer. return s.data else: return str(s) def to_String_for_subst(s, isinstance=isinstance, str=str, to_String=to_String, BaseStringTypes=BaseStringTypes, SequenceTypes=SequenceTypes, UserString=UserString): # Note that the test cases are sorted by order of probability. if isinstance(s, BaseStringTypes): return s elif isinstance(s, SequenceTypes): l = [] for e in s: l.append(to_String_for_subst(e)) return ' '.join( s ) elif isinstance(s, UserString): # s.data can only be either a unicode or a regular # string. Please see the UserString initializer. return s.data else: return str(s) def to_String_for_signature(obj, to_String_for_subst=to_String_for_subst, AttributeError=AttributeError): try: f = obj.for_signature except AttributeError: return to_String_for_subst(obj) else: return f() # The SCons "semi-deep" copy. # # This makes separate copies of lists (including UserList objects) # dictionaries (including UserDict objects) and tuples, but just copies # references to anything else it finds. # # A special case is any object that has a __semi_deepcopy__() method, # which we invoke to create the copy. Currently only used by # BuilderDict to actually prevent the copy operation (as invalid on that object) # # The dispatch table approach used here is a direct rip-off from the # normal Python copy module. _semi_deepcopy_dispatch = d = {} def semi_deepcopy_dict(x, exclude = [] ): copy = {} for key, val in x.items(): # The regular Python copy.deepcopy() also deepcopies the key, # as follows: # # copy[semi_deepcopy(key)] = semi_deepcopy(val) # # Doesn't seem like we need to, but we'll comment it just in case. if key not in exclude: copy[key] = semi_deepcopy(val) return copy d[dict] = semi_deepcopy_dict def _semi_deepcopy_list(x): return list(map(semi_deepcopy, x)) d[list] = _semi_deepcopy_list def _semi_deepcopy_tuple(x): return tuple(map(semi_deepcopy, x)) d[tuple] = _semi_deepcopy_tuple def semi_deepcopy(x): copier = _semi_deepcopy_dispatch.get(type(x)) if copier: return copier(x) else: if hasattr(x, '__semi_deepcopy__') and callable(x.__semi_deepcopy__): return x.__semi_deepcopy__() elif isinstance(x, UserDict): return x.__class__(semi_deepcopy_dict(x)) elif isinstance(x, UserList): return x.__class__(_semi_deepcopy_list(x)) return x class Proxy(object): """A simple generic Proxy class, forwarding all calls to subject. So, for the benefit of the python newbie, what does this really mean? Well, it means that you can take an object, let's call it 'objA', and wrap it in this Proxy class, with a statement like this proxyObj = Proxy(objA), Then, if in the future, you do something like this x = proxyObj.var1, since Proxy does not have a 'var1' attribute (but presumably objA does), the request actually is equivalent to saying x = objA.var1 Inherit from this class to create a Proxy. Note that, with new-style classes, this does *not* work transparently for Proxy subclasses that use special .__*__() method names, because those names are now bound to the class, not the individual instances. You now need to know in advance which .__*__() method names you want to pass on to the underlying Proxy object, and specifically delegate their calls like this: class Foo(Proxy): __str__ = Delegate('__str__') """ def __init__(self, subject): """Wrap an object as a Proxy object""" self._subject = subject def __getattr__(self, name): """Retrieve an attribute from the wrapped object. If the named attribute doesn't exist, AttributeError is raised""" return getattr(self._subject, name) def get(self): """Retrieve the entire wrapped object""" return self._subject def __cmp__(self, other): if issubclass(other.__class__, self._subject.__class__): return cmp(self._subject, other) return cmp(self.__dict__, other.__dict__) class Delegate(object): """A Python Descriptor class that delegates attribute fetches to an underlying wrapped subject of a Proxy. Typical use: class Foo(Proxy): __str__ = Delegate('__str__') """ def __init__(self, attribute): self.attribute = attribute def __get__(self, obj, cls): if isinstance(obj, cls): return getattr(obj._subject, self.attribute) else: return self # attempt to load the windows registry module: can_read_reg = 0 try: import winreg can_read_reg = 1 hkey_mod = winreg RegOpenKeyEx = winreg.OpenKeyEx RegEnumKey = winreg.EnumKey RegEnumValue = winreg.EnumValue RegQueryValueEx = winreg.QueryValueEx RegError = winreg.error except ImportError: try: import win32api import win32con can_read_reg = 1 hkey_mod = win32con RegOpenKeyEx = win32api.RegOpenKeyEx RegEnumKey = win32api.RegEnumKey RegEnumValue = win32api.RegEnumValue RegQueryValueEx = win32api.RegQueryValueEx RegError = win32api.error except ImportError: class _NoError(Exception): pass RegError = _NoError if can_read_reg: HKEY_CLASSES_ROOT = hkey_mod.HKEY_CLASSES_ROOT HKEY_LOCAL_MACHINE = hkey_mod.HKEY_LOCAL_MACHINE HKEY_CURRENT_USER = hkey_mod.HKEY_CURRENT_USER HKEY_USERS = hkey_mod.HKEY_USERS def RegGetValue(root, key): """This utility function returns a value in the registry without having to open the key first. Only available on Windows platforms with a version of Python that can read the registry. Returns the same thing as SCons.Util.RegQueryValueEx, except you just specify the entire path to the value, and don't have to bother opening the key first. So: Instead of: k = SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\Windows\CurrentVersion') out = SCons.Util.RegQueryValueEx(k, 'ProgramFilesDir') You can write: out = SCons.Util.RegGetValue(SCons.Util.HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir') """ # I would use os.path.split here, but it's not a filesystem # path... p = key.rfind('\\') + 1 keyp = key[:p-1] # -1 to omit trailing slash val = key[p:] k = RegOpenKeyEx(root, keyp) return RegQueryValueEx(k,val) else: try: e = WindowsError except NameError: # Make sure we have a definition of WindowsError so we can # run platform-independent tests of Windows functionality on # platforms other than Windows. (WindowsError is, in fact, an # OSError subclass on Windows.) class WindowsError(OSError): pass import builtins builtins.WindowsError = WindowsError else: del e HKEY_CLASSES_ROOT = None HKEY_LOCAL_MACHINE = None HKEY_CURRENT_USER = None HKEY_USERS = None def RegGetValue(root, key): raise WindowsError def RegOpenKeyEx(root, key): raise WindowsError if sys.platform == 'win32': def WhereIs(file, path=None, pathext=None, reject=[]): if path is None: try: path = os.environ['PATH'] except KeyError: return None if is_String(path): path = path.split(os.pathsep) if pathext is None: try: pathext = os.environ['PATHEXT'] except KeyError: pathext = '.COM;.EXE;.BAT;.CMD' if is_String(pathext): pathext = pathext.split(os.pathsep) for ext in pathext: if ext.lower() == file[-len(ext):].lower(): pathext = [''] break if not is_List(reject) and not is_Tuple(reject): reject = [reject] for dir in path: f = os.path.join(dir, file) for ext in pathext: fext = f + ext if os.path.isfile(fext): try: reject.index(fext) except ValueError: return os.path.normpath(fext) continue return None elif os.name == 'os2': def WhereIs(file, path=None, pathext=None, reject=[]): if path is None: try: path = os.environ['PATH'] except KeyError: return None if is_String(path): path = path.split(os.pathsep) if pathext is None: pathext = ['.exe', '.cmd'] for ext in pathext: if ext.lower() == file[-len(ext):].lower(): pathext = [''] break if not is_List(reject) and not is_Tuple(reject): reject = [reject] for dir in path: f = os.path.join(dir, file) for ext in pathext: fext = f + ext if os.path.isfile(fext): try: reject.index(fext) except ValueError: return os.path.normpath(fext) continue return None else: def WhereIs(file, path=None, pathext=None, reject=[]): import stat if path is None: try: path = os.environ['PATH'] except KeyError: return None if is_String(path): path = path.split(os.pathsep) if not is_List(reject) and not is_Tuple(reject): reject = [reject] for d in path: f = os.path.join(d, file) if os.path.isfile(f): try: st = os.stat(f) except OSError: # os.stat() raises OSError, not IOError if the file # doesn't exist, so in this case we let IOError get # raised so as to not mask possibly serious disk or # network issues. continue if stat.S_IMODE(st[stat.ST_MODE]) & 0111: try: reject.index(f) except ValueError: return os.path.normpath(f) continue return None def PrependPath(oldpath, newpath, sep = os.pathsep, delete_existing=1, canonicalize=None): """This prepends newpath elements to the given oldpath. Will only add any particular path once (leaving the first one it encounters and ignoring the rest, to preserve path order), and will os.path.normpath and os.path.normcase all paths to help assure this. This can also handle the case where the given old path variable is a list instead of a string, in which case a list will be returned instead of a string. Example: Old Path: "/foo/bar:/foo" New Path: "/biz/boom:/foo" Result: "/biz/boom:/foo:/foo/bar" If delete_existing is 0, then adding a path that exists will not move it to the beginning; it will stay where it is in the list. If canonicalize is not None, it is applied to each element of newpath before use. """ orig = oldpath is_list = 1 paths = orig if not is_List(orig) and not is_Tuple(orig): paths = paths.split(sep) is_list = 0 if is_String(newpath): newpaths = newpath.split(sep) elif not is_List(newpath) and not is_Tuple(newpath): newpaths = [ newpath ] # might be a Dir else: newpaths = newpath if canonicalize: newpaths=list(map(canonicalize, newpaths)) if not delete_existing: # First uniquify the old paths, making sure to # preserve the first instance (in Unix/Linux, # the first one wins), and remembering them in normpaths. # Then insert the new paths at the head of the list # if they're not already in the normpaths list. result = [] normpaths = [] for path in paths: if not path: continue normpath = os.path.normpath(os.path.normcase(path)) if normpath not in normpaths: result.append(path) normpaths.append(normpath) newpaths.reverse() # since we're inserting at the head for path in newpaths: if not path: continue normpath = os.path.normpath(os.path.normcase(path)) if normpath not in normpaths: result.insert(0, path) normpaths.append(normpath) paths = result else: newpaths = newpaths + paths # prepend new paths normpaths = [] paths = [] # now we add them only if they are unique for path in newpaths: normpath = os.path.normpath(os.path.normcase(path)) if path and not normpath in normpaths: paths.append(path) normpaths.append(normpath) if is_list: return paths else: return sep.join(paths) def AppendPath(oldpath, newpath, sep = os.pathsep, delete_existing=1, canonicalize=None): """This appends new path elements to the given old path. Will only add any particular path once (leaving the last one it encounters and ignoring the rest, to preserve path order), and will os.path.normpath and os.path.normcase all paths to help assure this. This can also handle the case where the given old path variable is a list instead of a string, in which case a list will be returned instead of a string. Example: Old Path: "/foo/bar:/foo" New Path: "/biz/boom:/foo" Result: "/foo/bar:/biz/boom:/foo" If delete_existing is 0, then adding a path that exists will not move it to the end; it will stay where it is in the list. If canonicalize is not None, it is applied to each element of newpath before use. """ orig = oldpath is_list = 1 paths = orig if not is_List(orig) and not is_Tuple(orig): paths = paths.split(sep) is_list = 0 if is_String(newpath): newpaths = newpath.split(sep) elif not is_List(newpath) and not is_Tuple(newpath): newpaths = [ newpath ] # might be a Dir else: newpaths = newpath if canonicalize: newpaths=list(map(canonicalize, newpaths)) if not delete_existing: # add old paths to result, then # add new paths if not already present # (I thought about using a dict for normpaths for speed, # but it's not clear hashing the strings would be faster # than linear searching these typically short lists.) result = [] normpaths = [] for path in paths: if not path: continue result.append(path) normpaths.append(os.path.normpath(os.path.normcase(path))) for path in newpaths: if not path: continue normpath = os.path.normpath(os.path.normcase(path)) if normpath not in normpaths: result.append(path) normpaths.append(normpath) paths = result else: # start w/ new paths, add old ones if not present, # then reverse. newpaths = paths + newpaths # append new paths newpaths.reverse() normpaths = [] paths = [] # now we add them only if they are unique for path in newpaths: normpath = os.path.normpath(os.path.normcase(path)) if path and not normpath in normpaths: paths.append(path) normpaths.append(normpath) paths.reverse() if is_list: return paths else: return sep.join(paths) if sys.platform == 'cygwin': def get_native_path(path): """Transforms an absolute path into a native path for the system. In Cygwin, this converts from a Cygwin path to a Windows one.""" return os.popen('cygpath -w ' + path).read().replace('\n', '') else: def get_native_path(path): """Transforms an absolute path into a native path for the system. Non-Cygwin version, just leave the path alone.""" return path display = DisplayEngine() def Split(arg): if is_List(arg) or is_Tuple(arg): return arg elif is_String(arg): return arg.split() else: return [arg] class CLVar(UserList): """A class for command-line construction variables. This is a list that uses Split() to split an initial string along white-space arguments, and similarly to split any strings that get added. This allows us to Do the Right Thing with Append() and Prepend() (as well as straight Python foo = env['VAR'] + 'arg1 arg2') regardless of whether a user adds a list or a string to a command-line construction variable. """ def __init__(self, seq = []): UserList.__init__(self, Split(seq)) def __add__(self, other): return UserList.__add__(self, CLVar(other)) def __radd__(self, other): return UserList.__radd__(self, CLVar(other)) def __coerce__(self, other): return (self, CLVar(other)) def __str__(self): return ' '.join(self.data) # A dictionary that preserves the order in which items are added. # Submitted by David Benjamin to ActiveState's Python Cookbook web site: # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747 # Including fixes/enhancements from the follow-on discussions. class OrderedDict(UserDict): def __init__(self, dict = None): self._keys = [] UserDict.__init__(self, dict) def __delitem__(self, key): UserDict.__delitem__(self, key) self._keys.remove(key) def __setitem__(self, key, item): UserDict.__setitem__(self, key, item) if key not in self._keys: self._keys.append(key) def clear(self): UserDict.clear(self) self._keys = [] def copy(self): dict = OrderedDict() dict.update(self) return dict def items(self): return list(zip(self._keys, list(self.values()))) def keys(self): return self._keys[:] def popitem(self): try: key = self._keys[-1] except IndexError: raise KeyError('dictionary is empty') val = self[key] del self[key] return (key, val) def setdefault(self, key, failobj = None): UserDict.setdefault(self, key, failobj) if key not in self._keys: self._keys.append(key) def update(self, dict): for (key, val) in dict.items(): self.__setitem__(key, val) def values(self): return list(map(self.get, self._keys)) class Selector(OrderedDict): """A callable ordered dictionary that maps file suffixes to dictionary values. We preserve the order in which items are added so that get_suffix() calls always return the first suffix added.""" def __call__(self, env, source, ext=None): if ext is None: try: ext = source[0].suffix except IndexError: ext = "" try: return self[ext] except KeyError: # Try to perform Environment substitution on the keys of # the dictionary before giving up. s_dict = {} for (k,v) in self.items(): if k is not None: s_k = env.subst(k) if s_k in s_dict: # We only raise an error when variables point # to the same suffix. If one suffix is literal # and a variable suffix contains this literal, # the literal wins and we don't raise an error. raise KeyError(s_dict[s_k][0], k, s_k) s_dict[s_k] = (k,v) try: return s_dict[ext][1] except KeyError: try: return self[None] except KeyError: return None if sys.platform == 'cygwin': # On Cygwin, os.path.normcase() lies, so just report back the # fact that the underlying Windows OS is case-insensitive. def case_sensitive_suffixes(s1, s2): return 0 else: def case_sensitive_suffixes(s1, s2): return (os.path.normcase(s1) != os.path.normcase(s2)) def adjustixes(fname, pre, suf, ensure_suffix=False): if pre: path, fn = os.path.split(os.path.normpath(fname)) if fn[:len(pre)] != pre: fname = os.path.join(path, pre + fn) # Only append a suffix if the suffix we're going to add isn't already # there, and if either we've been asked to ensure the specific suffix # is present or there's no suffix on it at all. if suf and fname[-len(suf):] != suf and \ (ensure_suffix or not splitext(fname)[1]): fname = fname + suf return fname # From Tim Peters, # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560 # ASPN: Python Cookbook: Remove duplicates from a sequence # (Also in the printed Python Cookbook.) def unique(s): """Return a list of the elements in s, but without duplicates. For example, unique([1,2,3,1,2,3]) is some permutation of [1,2,3], unique("abcabc") some permutation of ["a", "b", "c"], and unique(([1, 2], [2, 3], [1, 2])) some permutation of [[2, 3], [1, 2]]. For best speed, all sequence elements should be hashable. Then unique() will usually work in linear time. If not possible, the sequence elements should enjoy a total ordering, and if list(s).sort() doesn't raise TypeError it's assumed that they do enjoy a total ordering. Then unique() will usually work in O(N*log2(N)) time. If that's not possible either, the sequence elements must support equality-testing. Then unique() will usually work in quadratic time. """ n = len(s) if n == 0: return [] # Try using a dict first, as that's the fastest and will usually # work. If it doesn't work, it will usually fail quickly, so it # usually doesn't cost much to *try* it. It requires that all the # sequence elements be hashable, and support equality comparison. u = {} try: for x in s: u[x] = 1 except TypeError: pass # move on to the next method else: return list(u.keys()) del u # We can't hash all the elements. Second fastest is to sort, # which brings the equal elements together; then duplicates are # easy to weed out in a single pass. # NOTE: Python's list.sort() was designed to be efficient in the # presence of many duplicate elements. This isn't true of all # sort functions in all languages or libraries, so this approach # is more effective in Python than it may be elsewhere. try: t = sorted(s) except TypeError: pass # move on to the next method else: assert n > 0 last = t[0] lasti = i = 1 while i < n: if t[i] != last: t[lasti] = last = t[i] lasti = lasti + 1 i = i + 1 return t[:lasti] del t # Brute force is all that's left. u = [] for x in s: if x not in u: u.append(x) return u # From Alex Martelli, # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560 # ASPN: Python Cookbook: Remove duplicates from a sequence # First comment, dated 2001/10/13. # (Also in the printed Python Cookbook.) def uniquer(seq, idfun=None): if idfun is None: def idfun(x): return x seen = {} result = [] for item in seq: marker = idfun(item) # in old Python versions: # if seen.has_key(marker) # but in new ones: if marker in seen: continue seen[marker] = 1 result.append(item) return result # A more efficient implementation of Alex's uniquer(), this avoids the # idfun() argument and function-call overhead by assuming that all # items in the sequence are hashable. def uniquer_hashables(seq): seen = {} result = [] for item in seq: #if not item in seen: if item not in seen: seen[item] = 1 result.append(item) return result # Much of the logic here was originally based on recipe 4.9 from the # Python CookBook, but we had to dumb it way down for Python 1.5.2. class LogicalLines(object): def __init__(self, fileobj): self.fileobj = fileobj def readline(self): result = [] while True: line = self.fileobj.readline() if not line: break if line[-2:] == '\\\n': result.append(line[:-2]) else: result.append(line) break return ''.join(result) def readlines(self): result = [] while True: line = self.readline() if not line: break result.append(line) return result class UniqueList(UserList): def __init__(self, seq = []): UserList.__init__(self, seq) self.unique = True def __make_unique(self): if not self.unique: self.data = uniquer_hashables(self.data) self.unique = True def __lt__(self, other): self.__make_unique() return UserList.__lt__(self, other) def __le__(self, other): self.__make_unique() return UserList.__le__(self, other) def __eq__(self, other): self.__make_unique() return UserList.__eq__(self, other) def __ne__(self, other): self.__make_unique() return UserList.__ne__(self, other) def __gt__(self, other): self.__make_unique() return UserList.__gt__(self, other) def __ge__(self, other): self.__make_unique() return UserList.__ge__(self, other) def __cmp__(self, other): self.__make_unique() return UserList.__cmp__(self, other) def __len__(self): self.__make_unique() return UserList.__len__(self) def __getitem__(self, i): self.__make_unique() return UserList.__getitem__(self, i) def __setitem__(self, i, item): UserList.__setitem__(self, i, item) self.unique = False def __getslice__(self, i, j): self.__make_unique() return UserList.__getslice__(self, i, j) def __setslice__(self, i, j, other): UserList.__setslice__(self, i, j, other) self.unique = False def __add__(self, other): result = UserList.__add__(self, other) result.unique = False return result def __radd__(self, other): result = UserList.__radd__(self, other) result.unique = False return result def __iadd__(self, other): result = UserList.__iadd__(self, other) result.unique = False return result def __mul__(self, other): result = UserList.__mul__(self, other) result.unique = False return result def __rmul__(self, other): result = UserList.__rmul__(self, other) result.unique = False return result def __imul__(self, other): result = UserList.__imul__(self, other) result.unique = False return result def append(self, item): UserList.append(self, item) self.unique = False def insert(self, i): UserList.insert(self, i) self.unique = False def count(self, item): self.__make_unique() return UserList.count(self, item) def index(self, item): self.__make_unique() return UserList.index(self, item) def reverse(self): self.__make_unique() UserList.reverse(self) def sort(self, *args, **kwds): self.__make_unique() return UserList.sort(self, *args, **kwds) def extend(self, other): UserList.extend(self, other) self.unique = False class Unbuffered(object): """ A proxy class that wraps a file object, flushing after every write, and delegating everything else to the wrapped object. """ def __init__(self, file): self.file = file self.softspace = 0 ## backward compatibility; not supported in Py3k def write(self, arg): try: self.file.write(arg) self.file.flush() except IOError: # Stdout might be connected to a pipe that has been closed # by now. The most likely reason for the pipe being closed # is that the user has press ctrl-c. It this is the case, # then SCons is currently shutdown. We therefore ignore # IOError's here so that SCons can continue and shutdown # properly so that the .sconsign is correctly written # before SCons exits. pass def __getattr__(self, attr): return getattr(self.file, attr) def make_path_relative(path): """ makes an absolute path name to a relative pathname. """ if os.path.isabs(path): drive_s,path = os.path.splitdrive(path) import re if not drive_s: path=re.compile("/*(.*)").findall(path)[0] else: path=path[1:] assert( not os.path.isabs( path ) ), path return path # The original idea for AddMethod() and RenameFunction() come from the # following post to the ActiveState Python Cookbook: # # ASPN: Python Cookbook : Install bound methods in an instance # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/223613 # # That code was a little fragile, though, so the following changes # have been wrung on it: # # * Switched the installmethod() "object" and "function" arguments, # so the order reflects that the left-hand side is the thing being # "assigned to" and the right-hand side is the value being assigned. # # * Changed explicit type-checking to the "try: klass = object.__class__" # block in installmethod() below so that it still works with the # old-style classes that SCons uses. # # * Replaced the by-hand creation of methods and functions with use of # the "new" module, as alluded to in Alex Martelli's response to the # following Cookbook post: # # ASPN: Python Cookbook : Dynamically added methods to a class # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81732 def AddMethod(obj, function, name=None): """ Adds either a bound method to an instance or an unbound method to a class. If name is ommited the name of the specified function is used by default. Example: a = A() def f(self, x, y): self.z = x + y AddMethod(f, A, "add") a.add(2, 4) print a.z AddMethod(lambda self, i: self.l[i], a, "listIndex") print a.listIndex(5) """ if name is None: name = function.func_name else: function = RenameFunction(function, name) if hasattr(obj, '__class__') and obj.__class__ is not type: # "obj" is an instance, so it gets a bound method. setattr(obj, name, MethodType(function, obj, obj.__class__)) else: # "obj" is a class, so it gets an unbound method. setattr(obj, name, MethodType(function, None, obj)) def RenameFunction(function, name): """ Returns a function identical to the specified function, but with the specified name. """ return FunctionType(function.func_code, function.func_globals, name, function.func_defaults) md5 = False def MD5signature(s): return str(s) def MD5filesignature(fname, chunksize=65536): f = open(fname, "rb") result = f.read() f.close() return result try: import hashlib except ImportError: pass else: if hasattr(hashlib, 'md5'): md5 = True def MD5signature(s): m = hashlib.md5() m.update(str(s)) return m.hexdigest() def MD5filesignature(fname, chunksize=65536): m = hashlib.md5() f = open(fname, "rb") while True: blck = f.read(chunksize) if not blck: break m.update(str(blck)) f.close() return m.hexdigest() def MD5collect(signatures): """ Collects a list of signatures into an aggregate signature. signatures - a list of signatures returns - the aggregate signature """ if len(signatures) == 1: return signatures[0] else: return MD5signature(', '.join(signatures)) def silent_intern(x): """ Perform sys.intern() on the passed argument and return the result. If the input is ineligible (e.g. a unicode string) the original argument is returned and no exception is thrown. """ try: return sys.intern(x) except TypeError: return x # From Dinu C. Gherman, # Python Cookbook, second edition, recipe 6.17, p. 277. # Also: # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68205 # ASPN: Python Cookbook: Null Object Design Pattern #TODO??? class Null(object): class Null(object): """ Null objects always and reliably "do nothing." """ def __new__(cls, *args, **kwargs): if not '_instance' in vars(cls): cls._instance = super(Null, cls).__new__(cls, *args, **kwargs) return cls._instance def __init__(self, *args, **kwargs): pass def __call__(self, *args, **kwargs): return self def __repr__(self): return "Null(0x%08X)" % id(self) def __nonzero__(self): return False def __getattr__(self, name): return self def __setattr__(self, name, value): return self def __delattr__(self, name): return self class NullSeq(Null): def __len__(self): return 0 def __iter__(self): return iter(()) def __getitem__(self, i): return self def __delitem__(self, i): return self def __setitem__(self, i, v): return self del __revision__ # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
gpl-3.0
kenshay/ImageScripter
Script_Runner/PYTHON/Lib/distutils/command/build_clib.py
204
8022
"""distutils.command.build_clib Implements the Distutils 'build_clib' command, to build a C/C++ library that is included in the module distribution and needed by an extension module.""" # XXX this module has *lots* of code ripped-off quite transparently from # build_ext.py -- not surprisingly really, as the work required to build # a static library from a collection of C source files is not really all # that different from what's required to build a shared object file from # a collection of C source files. Nevertheless, I haven't done the # necessary refactoring to account for the overlap in code between the # two modules, mainly because a number of subtle details changed in the # cut 'n paste. Sigh. import os from distutils.core import Command from distutils.errors import * from distutils.sysconfig import customize_compiler from distutils import log def show_compilers(): from distutils.ccompiler import show_compilers show_compilers() class build_clib(Command): description = "build C/C++ libraries used by Python extensions" user_options = [ ('build-clib=', 'b', "directory to build C/C++ libraries to"), ('build-temp=', 't', "directory to put temporary build by-products"), ('debug', 'g', "compile with debugging information"), ('force', 'f', "forcibly build everything (ignore file timestamps)"), ('compiler=', 'c', "specify the compiler type"), ] boolean_options = ['debug', 'force'] help_options = [ ('help-compiler', None, "list available compilers", show_compilers), ] def initialize_options(self): self.build_clib = None self.build_temp = None # List of libraries to build self.libraries = None # Compilation options for all libraries self.include_dirs = None self.define = None self.undef = None self.debug = None self.force = 0 self.compiler = None def finalize_options(self): # This might be confusing: both build-clib and build-temp default # to build-temp as defined by the "build" command. This is because # I think that C libraries are really just temporary build # by-products, at least from the point of view of building Python # extensions -- but I want to keep my options open. self.set_undefined_options('build', ('build_temp', 'build_clib'), ('build_temp', 'build_temp'), ('compiler', 'compiler'), ('debug', 'debug'), ('force', 'force')) self.libraries = self.distribution.libraries if self.libraries: self.check_library_list(self.libraries) if self.include_dirs is None: self.include_dirs = self.distribution.include_dirs or [] if isinstance(self.include_dirs, str): self.include_dirs = self.include_dirs.split(os.pathsep) # XXX same as for build_ext -- what about 'self.define' and # 'self.undef' ? def run(self): if not self.libraries: return # Yech -- this is cut 'n pasted from build_ext.py! from distutils.ccompiler import new_compiler self.compiler = new_compiler(compiler=self.compiler, dry_run=self.dry_run, force=self.force) customize_compiler(self.compiler) if self.include_dirs is not None: self.compiler.set_include_dirs(self.include_dirs) if self.define is not None: # 'define' option is a list of (name,value) tuples for (name,value) in self.define: self.compiler.define_macro(name, value) if self.undef is not None: for macro in self.undef: self.compiler.undefine_macro(macro) self.build_libraries(self.libraries) def check_library_list(self, libraries): """Ensure that the list of libraries is valid. `library` is presumably provided as a command option 'libraries'. This method checks that it is a list of 2-tuples, where the tuples are (library_name, build_info_dict). Raise DistutilsSetupError if the structure is invalid anywhere; just returns otherwise. """ if not isinstance(libraries, list): raise DistutilsSetupError( "'libraries' option must be a list of tuples") for lib in libraries: if not isinstance(lib, tuple) and len(lib) != 2: raise DistutilsSetupError( "each element of 'libraries' must a 2-tuple") name, build_info = lib if not isinstance(name, str): raise DistutilsSetupError( "first element of each tuple in 'libraries' " "must be a string (the library name)") if '/' in name or (os.sep != '/' and os.sep in name): raise DistutilsSetupError("bad library name '%s': " "may not contain directory separators" % lib[0]) if not isinstance(build_info, dict): raise DistutilsSetupError( "second element of each tuple in 'libraries' " "must be a dictionary (build info)") def get_library_names(self): # Assume the library list is valid -- 'check_library_list()' is # called from 'finalize_options()', so it should be! if not self.libraries: return None lib_names = [] for (lib_name, build_info) in self.libraries: lib_names.append(lib_name) return lib_names def get_source_files(self): self.check_library_list(self.libraries) filenames = [] for (lib_name, build_info) in self.libraries: sources = build_info.get('sources') if sources is None or not isinstance(sources, (list, tuple)): raise DistutilsSetupError( "in 'libraries' option (library '%s'), " "'sources' must be present and must be " "a list of source filenames" % lib_name) filenames.extend(sources) return filenames def build_libraries(self, libraries): for (lib_name, build_info) in libraries: sources = build_info.get('sources') if sources is None or not isinstance(sources, (list, tuple)): raise DistutilsSetupError( "in 'libraries' option (library '%s'), " "'sources' must be present and must be " "a list of source filenames" % lib_name) sources = list(sources) log.info("building '%s' library", lib_name) # First, compile the source code to object files in the library # directory. (This should probably change to putting object # files in a temporary build directory.) macros = build_info.get('macros') include_dirs = build_info.get('include_dirs') objects = self.compiler.compile(sources, output_dir=self.build_temp, macros=macros, include_dirs=include_dirs, debug=self.debug) # Now "link" the object files together into a static library. # (On Unix at least, this isn't really linking -- it just # builds an archive. Whatever.) self.compiler.create_static_lib(objects, lib_name, output_dir=self.build_clib, debug=self.debug)
gpl-3.0
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-3.1/Lib/distutils/tests/test_util.py
1
8506
"""Tests for distutils.util.""" # not covered yet: # - byte_compile # import os import sys import unittest from copy import copy from distutils.errors import DistutilsPlatformError from distutils.util import (get_platform, convert_path, change_root, check_environ, split_quoted, strtobool, rfc822_escape) from distutils import util # used to patch _environ_checked from distutils.sysconfig import get_config_vars from distutils import sysconfig from distutils.tests import support class UtilTestCase(support.EnvironGuard, unittest.TestCase): def setUp(self): super(UtilTestCase, self).setUp() # saving the environment self.name = os.name self.platform = sys.platform self.version = sys.version self.sep = os.sep self.join = os.path.join self.isabs = os.path.isabs self.splitdrive = os.path.splitdrive self._config_vars = copy(sysconfig._config_vars) # patching os.uname if hasattr(os, 'uname'): self.uname = os.uname self._uname = os.uname() else: self.uname = None self._uname = None os.uname = self._get_uname def tearDown(self): # getting back the environment os.name = self.name sys.platform = self.platform sys.version = self.version os.sep = self.sep os.path.join = self.join os.path.isabs = self.isabs os.path.splitdrive = self.splitdrive if self.uname is not None: os.uname = self.uname else: del os.uname sysconfig._config_vars = copy(self._config_vars) super(UtilTestCase, self).tearDown() def _set_uname(self, uname): self._uname = uname def _get_uname(self): return self._uname def test_get_platform(self): # windows XP, 32bits os.name = 'nt' sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) ' '[MSC v.1310 32 bit (Intel)]') sys.platform = 'win32' self.assertEquals(get_platform(), 'win32') # windows XP, amd64 os.name = 'nt' sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) ' '[MSC v.1310 32 bit (Amd64)]') sys.platform = 'win32' self.assertEquals(get_platform(), 'win-amd64') # windows XP, itanium os.name = 'nt' sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) ' '[MSC v.1310 32 bit (Itanium)]') sys.platform = 'win32' self.assertEquals(get_platform(), 'win-ia64') # macbook os.name = 'posix' sys.version = ('2.5 (r25:51918, Sep 19 2006, 08:49:13) ' '\n[GCC 4.0.1 (Apple Computer, Inc. build 5341)]') sys.platform = 'darwin' self._set_uname(('Darwin', 'macziade', '8.11.1', ('Darwin Kernel Version 8.11.1: ' 'Wed Oct 10 18:23:28 PDT 2007; ' 'root:xnu-792.25.20~1/RELEASE_I386'), 'i386')) self.environ['MACOSX_DEPLOYMENT_TARGET'] = '10.3' get_config_vars()['CFLAGS'] = ('-fno-strict-aliasing -DNDEBUG -g ' '-fwrapv -O3 -Wall -Wstrict-prototypes') self.assertEquals(get_platform(), 'macosx-10.3-i386') # macbook with fat binaries (fat, universal or fat64) self.environ['MACOSX_DEPLOYMENT_TARGET'] = '10.4' get_config_vars()['CFLAGS'] = ('-arch ppc -arch i386 -isysroot ' '/Developer/SDKs/MacOSX10.4u.sdk ' '-fno-strict-aliasing -fno-common ' '-dynamic -DNDEBUG -g -O3') self.assertEquals(get_platform(), 'macosx-10.4-fat') get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch i386 -isysroot ' '/Developer/SDKs/MacOSX10.4u.sdk ' '-fno-strict-aliasing -fno-common ' '-dynamic -DNDEBUG -g -O3') self.assertEquals(get_platform(), 'macosx-10.4-universal') get_config_vars()['CFLAGS'] = ('-arch x86_64 -isysroot ' '/Developer/SDKs/MacOSX10.4u.sdk ' '-fno-strict-aliasing -fno-common ' '-dynamic -DNDEBUG -g -O3') self.assertEquals(get_platform(), 'macosx-10.4-fat64') # linux debian sarge os.name = 'posix' sys.version = ('2.3.5 (#1, Jul 4 2007, 17:28:59) ' '\n[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)]') sys.platform = 'linux2' self._set_uname(('Linux', 'aglae', '2.6.21.1dedibox-r7', '#1 Mon Apr 30 17:25:38 CEST 2007', 'i686')) self.assertEquals(get_platform(), 'linux-i686') # XXX more platforms to tests here def test_convert_path(self): # linux/mac os.sep = '/' def _join(path): return '/'.join(path) os.path.join = _join self.assertEquals(convert_path('/home/to/my/stuff'), '/home/to/my/stuff') # win os.sep = '\\' def _join(*path): return '\\'.join(path) os.path.join = _join self.assertRaises(ValueError, convert_path, '/home/to/my/stuff') self.assertRaises(ValueError, convert_path, 'home/to/my/stuff/') self.assertEquals(convert_path('home/to/my/stuff'), 'home\\to\\my\\stuff') self.assertEquals(convert_path('.'), os.curdir) def test_change_root(self): # linux/mac os.name = 'posix' def _isabs(path): return path[0] == '/' os.path.isabs = _isabs def _join(*path): return '/'.join(path) os.path.join = _join self.assertEquals(change_root('/root', '/old/its/here'), '/root/old/its/here') self.assertEquals(change_root('/root', 'its/here'), '/root/its/here') # windows os.name = 'nt' def _isabs(path): return path.startswith('c:\\') os.path.isabs = _isabs def _splitdrive(path): if path.startswith('c:'): return ('', path.replace('c:', '')) return ('', path) os.path.splitdrive = _splitdrive def _join(*path): return '\\'.join(path) os.path.join = _join self.assertEquals(change_root('c:\\root', 'c:\\old\\its\\here'), 'c:\\root\\old\\its\\here') self.assertEquals(change_root('c:\\root', 'its\\here'), 'c:\\root\\its\\here') # BugsBunny os (it's a great os) os.name = 'BugsBunny' self.assertRaises(DistutilsPlatformError, change_root, 'c:\\root', 'its\\here') # XXX platforms to be covered: os2, mac def test_check_environ(self): util._environ_checked = 0 # posix without HOME if os.name == 'posix': # this test won't run on windows check_environ() import pwd self.assertEquals(self.environ['HOME'], pwd.getpwuid(os.getuid())[5]) else: check_environ() self.assertEquals(self.environ['PLAT'], get_platform()) self.assertEquals(util._environ_checked, 1) def test_split_quoted(self): self.assertEquals(split_quoted('""one"" "two" \'three\' \\four'), ['one', 'two', 'three', 'four']) def test_strtobool(self): yes = ('y', 'Y', 'yes', 'True', 't', 'true', 'True', 'On', 'on', '1') no = ('n', 'no', 'f', 'false', 'off', '0', 'Off', 'No', 'N') for y in yes: self.assert_(strtobool(y)) for n in no: self.assert_(not strtobool(n)) def test_rfc822_escape(self): header = 'I am a\npoor\nlonesome\nheader\n' res = rfc822_escape(header) wanted = ('I am a%(8s)spoor%(8s)slonesome%(8s)s' 'header%(8s)s') % {'8s': '\n'+8*' '} self.assertEquals(res, wanted) def test_suite(): return unittest.makeSuite(UtilTestCase) if __name__ == "__main__": unittest.main(defaultTest="test_suite")
mit
nhenezi/kuma
vendor/packages/translate-toolkit/translate/storage/placeables/__init__.py
10
2030
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2008-2009 Zuza Software Foundation # # This file is part of the Translate Toolkit. # # 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, see <http://www.gnu.org/licenses/>. """ This module implements basic functionality to support placeables. A placeable is used to represent things like: 1. Substitutions For example, in ODF, footnotes appear in the ODF XML where they are defined; so if we extract a paragraph with some footnotes, the translator will have a lot of additional XML to with; so we separate the footnotes out into separate translation units and mark their positions in the original text with placeables. 2. Hiding of inline formatting data The translator doesn't want to have to deal with all the weird formatting conventions of wherever the text came from. 3. Marking variables This is an old issue - translators translate variable names which should remain untranslated. We can wrap placeables around variable names to avoid this. The placeables model follows the XLIFF standard's list of placeables. Please refer to the XLIFF specification to get a better understanding. """ import base import interfaces import general import xliff from base import * from base import __all__ as all_your_base from strelem import StringElem from parse import parse __all__ = ['base', 'interfaces', 'general', 'parse', 'StringElem', 'xliff'] + all_your_base
mpl-2.0
mancoast/CPythonPyc_test
fail/323_test_cmd_line.py
1
14080
# Tests invocation of the interpreter with various command line arguments # Most tests are executed with environment variables ignored # See test_cmd_line_script.py for testing of script execution import test.support, unittest import os import sys import subprocess import tempfile from test.script_helper import spawn_python, kill_python, assert_python_ok, assert_python_failure # XXX (ncoghlan): Move to script_helper and make consistent with run_python def _kill_python_and_exit_code(p): data = kill_python(p) returncode = p.wait() return data, returncode class CmdLineTest(unittest.TestCase): def test_directories(self): assert_python_failure('.') assert_python_failure('< .') def verify_valid_flag(self, cmd_line): rc, out, err = assert_python_ok(*cmd_line) self.assertTrue(out == b'' or out.endswith(b'\n')) self.assertNotIn(b'Traceback', out) self.assertNotIn(b'Traceback', err) def test_optimize(self): self.verify_valid_flag('-O') self.verify_valid_flag('-OO') def test_q(self): self.verify_valid_flag('-Qold') self.verify_valid_flag('-Qnew') self.verify_valid_flag('-Qwarn') self.verify_valid_flag('-Qwarnall') def test_site_flag(self): self.verify_valid_flag('-S') def test_usage(self): rc, out, err = assert_python_ok('-h') self.assertIn(b'usage', out) def test_version(self): version = ('Python %d.%d' % sys.version_info[:2]).encode("ascii") rc, out, err = assert_python_ok('-V') self.assertTrue(err.startswith(version)) def test_verbose(self): # -v causes imports to write to stderr. If the write to # stderr itself causes an import to happen (for the output # codec), a recursion loop can occur. rc, out, err = assert_python_ok('-v') self.assertNotIn(b'stack overflow', err) rc, out, err = assert_python_ok('-vv') self.assertNotIn(b'stack overflow', err) def test_xoptions(self): rc, out, err = assert_python_ok('-c', 'import sys; print(sys._xoptions)') opts = eval(out.splitlines()[0]) self.assertEqual(opts, {}) rc, out, err = assert_python_ok( '-Xa', '-Xb=c,d=e', '-c', 'import sys; print(sys._xoptions)') opts = eval(out.splitlines()[0]) self.assertEqual(opts, {'a': True, 'b': 'c,d=e'}) def test_run_module(self): # Test expected operation of the '-m' switch # Switch needs an argument assert_python_failure('-m') # Check we get an error for a nonexistent module assert_python_failure('-m', 'fnord43520xyz') # Check the runpy module also gives an error for # a nonexistent module assert_python_failure('-m', 'runpy', 'fnord43520xyz'), # All good if module is located and run successfully assert_python_ok('-m', 'timeit', '-n', '1'), def test_run_module_bug1764407(self): # -m and -i need to play well together # Runs the timeit module and checks the __main__ # namespace has been populated appropriately p = spawn_python('-i', '-m', 'timeit', '-n', '1') p.stdin.write(b'Timer\n') p.stdin.write(b'exit()\n') data = kill_python(p) self.assertTrue(data.find(b'1 loop') != -1) self.assertTrue(data.find(b'__main__.Timer') != -1) def test_run_code(self): # Test expected operation of the '-c' switch # Switch needs an argument assert_python_failure('-c') # Check we get an error for an uncaught exception assert_python_failure('-c', 'raise Exception') # All good if execution is successful assert_python_ok('-c', 'pass') @unittest.skipIf(sys.getfilesystemencoding() == 'ascii', 'need a filesystem encoding different than ASCII') def test_non_ascii(self): # Test handling of non-ascii data if test.support.verbose: import locale print('locale encoding = %s, filesystem encoding = %s' % (locale.getpreferredencoding(), sys.getfilesystemencoding())) command = "assert(ord('\xe9') == 0xe9)" assert_python_ok('-c', command) # On Windows, pass bytes to subprocess doesn't test how Python decodes the # command line, but how subprocess does decode bytes to unicode. Python # doesn't decode the command line because Windows provides directly the # arguments as unicode (using wmain() instead of main()). @unittest.skipIf(sys.platform == 'win32', 'Windows has a native unicode API') def test_undecodable_code(self): undecodable = b"\xff" env = os.environ.copy() # Use C locale to get ascii for the locale encoding env['LC_ALL'] = 'C' code = ( b'import locale; ' b'print(ascii("' + undecodable + b'"), ' b'locale.getpreferredencoding())') p = subprocess.Popen( [sys.executable, "-c", code], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env) stdout, stderr = p.communicate() if p.returncode == 1: # _Py_char2wchar() decoded b'\xff' as '\udcff' (b'\xff' is not # decodable from ASCII) and run_command() failed on # PyUnicode_AsUTF8String(). This is the expected behaviour on # Linux. pattern = b"Unable to decode the command from the command line:" elif p.returncode == 0: # _Py_char2wchar() decoded b'\xff' as '\xff' even if the locale is # C and the locale encoding is ASCII. It occurs on FreeBSD, Solaris # and Mac OS X. pattern = b"'\\xff' " # The output is followed by the encoding name, an alias to ASCII. # Examples: "US-ASCII" or "646" (ISO 646, on Solaris). else: raise AssertionError("Unknown exit code: %s, output=%a" % (p.returncode, stdout)) if not stdout.startswith(pattern): raise AssertionError("%a doesn't start with %a" % (stdout, pattern)) @unittest.skipUnless(sys.platform == 'darwin', 'test specific to Mac OS X') def test_osx_utf8(self): def check_output(text): decoded = text.decode('utf8', 'surrogateescape') expected = ascii(decoded).encode('ascii') + b'\n' env = os.environ.copy() # C locale gives ASCII locale encoding, but Python uses UTF-8 # to parse the command line arguments on Mac OS X env['LC_ALL'] = 'C' p = subprocess.Popen( (sys.executable, "-c", "import sys; print(ascii(sys.argv[1]))", text), stdout=subprocess.PIPE, env=env) stdout, stderr = p.communicate() self.assertEqual(stdout, expected) self.assertEqual(p.returncode, 0) # test valid utf-8 text = 'e:\xe9, euro:\u20ac, non-bmp:\U0010ffff'.encode('utf-8') check_output(text) # test invalid utf-8 text = ( b'\xff' # invalid byte b'\xc3\xa9' # valid utf-8 character b'\xc3\xff' # invalid byte sequence b'\xed\xa0\x80' # lone surrogate character (invalid) ) check_output(text) def test_unbuffered_output(self): # Test expected operation of the '-u' switch for stream in ('stdout', 'stderr'): # Binary is unbuffered code = ("import os, sys; sys.%s.buffer.write(b'x'); os._exit(0)" % stream) rc, out, err = assert_python_ok('-u', '-c', code) data = err if stream == 'stderr' else out self.assertEqual(data, b'x', "binary %s not unbuffered" % stream) # Text is line-buffered code = ("import os, sys; sys.%s.write('x\\n'); os._exit(0)" % stream) rc, out, err = assert_python_ok('-u', '-c', code) data = err if stream == 'stderr' else out self.assertEqual(data.strip(), b'x', "text %s not line-buffered" % stream) def test_unbuffered_input(self): # sys.stdin still works with '-u' code = ("import sys; sys.stdout.write(sys.stdin.read(1))") p = spawn_python('-u', '-c', code) p.stdin.write(b'x') p.stdin.flush() data, rc = _kill_python_and_exit_code(p) self.assertEqual(rc, 0) self.assertTrue(data.startswith(b'x'), data) def test_large_PYTHONPATH(self): path1 = "ABCDE" * 100 path2 = "FGHIJ" * 100 path = path1 + os.pathsep + path2 code = """if 1: import sys path = ":".join(sys.path) path = path.encode("ascii", "backslashreplace") sys.stdout.buffer.write(path)""" rc, out, err = assert_python_ok('-S', '-c', code, PYTHONPATH=path) self.assertIn(path1.encode('ascii'), out) self.assertIn(path2.encode('ascii'), out) def test_displayhook_unencodable(self): for encoding in ('ascii', 'latin1', 'utf8'): env = os.environ.copy() env['PYTHONIOENCODING'] = encoding p = subprocess.Popen( [sys.executable, '-i'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env) # non-ascii, surrogate, non-BMP printable, non-BMP unprintable text = "a=\xe9 b=\uDC80 c=\U00010000 d=\U0010FFFF" p.stdin.write(ascii(text).encode('ascii') + b"\n") p.stdin.write(b'exit()\n') data = kill_python(p) escaped = repr(text).encode(encoding, 'backslashreplace') self.assertIn(escaped, data) def check_input(self, code, expected): with tempfile.NamedTemporaryFile("wb+") as stdin: sep = os.linesep.encode('ASCII') stdin.write(sep.join((b'abc', b'def'))) stdin.flush() stdin.seek(0) with subprocess.Popen( (sys.executable, "-c", code), stdin=stdin, stdout=subprocess.PIPE) as proc: stdout, stderr = proc.communicate() self.assertEqual(stdout.rstrip(), expected) def test_stdin_readline(self): # Issue #11272: check that sys.stdin.readline() replaces '\r\n' by '\n' # on Windows (sys.stdin is opened in binary mode) self.check_input( "import sys; print(repr(sys.stdin.readline()))", b"'abc\\n'") def test_builtin_input(self): # Issue #11272: check that input() strips newlines ('\n' or '\r\n') self.check_input( "print(repr(input()))", b"'abc'") def test_unmached_quote(self): # Issue #10206: python program starting with unmatched quote # spewed spaces to stdout rc, out, err = assert_python_failure('-c', "'") self.assertRegex(err.decode('ascii', 'ignore'), 'SyntaxError') self.assertEqual(b'', out) def test_stdout_flush_at_shutdown(self): # Issue #5319: if stdout.flush() fails at shutdown, an error should # be printed out. code = """if 1: import os, sys sys.stdout.write('x') os.close(sys.stdout.fileno())""" rc, out, err = assert_python_ok('-c', code) self.assertEqual(b'', out) self.assertRegex(err.decode('ascii', 'ignore'), 'Exception IOError: .* ignored') def test_closed_stdout(self): # Issue #13444: if stdout has been explicitly closed, we should # not attempt to flush it at shutdown. code = "import sys; sys.stdout.close()" rc, out, err = assert_python_ok('-c', code) self.assertEqual(b'', err) # Issue #7111: Python should work without standard streams @unittest.skipIf(os.name != 'posix', "test needs POSIX semantics") def _test_no_stdio(self, streams): code = """if 1: import os, sys for i, s in enumerate({streams}): if getattr(sys, s) is not None: os._exit(i + 1) os._exit(42)""".format(streams=streams) def preexec(): if 'stdin' in streams: os.close(0) if 'stdout' in streams: os.close(1) if 'stderr' in streams: os.close(2) p = subprocess.Popen( [sys.executable, "-E", "-c", code], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=preexec) out, err = p.communicate() self.assertEqual(test.support.strip_python_stderr(err), b'') self.assertEqual(p.returncode, 42) def test_no_stdin(self): self._test_no_stdio(['stdin']) def test_no_stdout(self): self._test_no_stdio(['stdout']) def test_no_stderr(self): self._test_no_stdio(['stderr']) def test_no_std_streams(self): self._test_no_stdio(['stdin', 'stdout', 'stderr']) def test_hash_randomization(self): # Verify that -R enables hash randomization: self.verify_valid_flag('-R') hashes = [] for i in range(2): code = 'print(hash("spam"))' rc, out, err = assert_python_ok('-R', '-c', code) self.assertEqual(rc, 0) hashes.append(out) self.assertNotEqual(hashes[0], hashes[1]) # Verify that sys.flags contains hash_randomization code = 'import sys; print("random is", sys.flags.hash_randomization)' rc, out, err = assert_python_ok('-R', '-c', code) self.assertEqual(rc, 0) self.assertIn(b'random is 1', out) def test_main(): test.support.run_unittest(CmdLineTest) test.support.reap_children() if __name__ == "__main__": test_main()
gpl-3.0
hyperized/ansible
lib/ansible/modules/storage/purestorage/purefb_snap.py
38
6777
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Simon Dodsley (simon@purestorage.com) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: purefb_snap version_added: '2.6' short_description: Manage filesystem snapshots on Pure Storage FlashBlades description: - Create or delete volumes and filesystem snapshots on Pure Storage FlashBlades. author: - Pure Storage Ansible Team (@sdodsley) <pure-ansible-team@purestorage.com> options: name: description: - The name of the source filesystem. required: true type: str suffix: description: - Suffix of snapshot name. type: str state: description: - Define whether the filesystem snapshot should exist or not. choices: [ absent, present ] default: present type: str eradicate: description: - Define whether to eradicate the snapshot on delete or leave in trash. type: bool default: 'no' extends_documentation_fragment: - purestorage.fb ''' EXAMPLES = r''' - name: Create snapshot foo.ansible purefb_snap: name: foo suffix: ansible fb_url: 10.10.10.2 fb_api_token: e31060a7-21fc-e277-6240-25983c6c4592 state: present - name: Delete snapshot named foo.snap purefb_snap: name: foo suffix: snap fb_url: 10.10.10.2 fb_api_token: e31060a7-21fc-e277-6240-25983c6c4592 state: absent - name: Recover deleted snapshot foo.ansible purefb_snap: name: foo suffix: ansible fb_url: 10.10.10.2 fb_api_token: e31060a7-21fc-e277-6240-25983c6c4592 state: present - name: Eradicate snapshot named foo.snap purefb_snap: name: foo suffix: snap eradicate: true fb_url: 10.10.10.2 fb_api_token: e31060a7-21fc-e277-6240-25983c6c4592 state: absent ''' RETURN = r''' ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.pure import get_blade, purefb_argument_spec from datetime import datetime HAS_PURITY_FB = True try: from purity_fb import FileSystemSnapshot, SnapshotSuffix except ImportError: HAS_PURITY_FB = False def get_fs(module, blade): """Return Filesystem or None""" fs = [] fs.append(module.params['name']) try: res = blade.file_systems.list_file_systems(names=fs) return res.items[0] except Exception: return None def get_fssnapshot(module, blade): """Return Snapshot or None""" try: filt = 'source=\'' + module.params['name'] + '\' and suffix=\'' + module.params['suffix'] + '\'' res = blade.file_system_snapshots.list_file_system_snapshots(filter=filt) return res.items[0] except Exception: return None def create_snapshot(module, blade): """Create Snapshot""" if not module.check_mode: source = [] source.append(module.params['name']) try: blade.file_system_snapshots.create_file_system_snapshots(sources=source, suffix=SnapshotSuffix(module.params['suffix'])) changed = True except Exception: changed = False module.exit_json(changed=changed) def recover_snapshot(module, blade): """Recover deleted Snapshot""" if not module.check_mode: snapname = module.params['name'] + "." + module.params['suffix'] new_attr = FileSystemSnapshot(destroyed=False) try: blade.file_system_snapshots.update_file_system_snapshots(name=snapname, attributes=new_attr) changed = True except Exception: changed = False module.exit_json(changed=changed) def update_snapshot(module, blade): """Update Snapshot""" changed = False module.exit_json(changed=changed) def delete_snapshot(module, blade): """ Delete Snapshot""" if not module.check_mode: snapname = module.params['name'] + "." + module.params['suffix'] new_attr = FileSystemSnapshot(destroyed=True) try: blade.file_system_snapshots.update_file_system_snapshots(name=snapname, attributes=new_attr) changed = True if module.params['eradicate']: try: blade.file_system_snapshots.delete_file_system_snapshots(name=snapname) changed = True except Exception: changed = False except Exception: changed = False module.exit_json(changed=changed) def eradicate_snapshot(module, blade): """ Eradicate Snapshot""" if not module.check_mode: snapname = module.params['name'] + "." + module.params['suffix'] try: blade.file_system_snapshots.delete_file_system_snapshots(name=snapname) changed = True except Exception: changed = False module.exit_json(changed=changed) def main(): argument_spec = purefb_argument_spec() argument_spec.update( dict( name=dict(required=True), suffix=dict(type='str'), eradicate=dict(default='false', type='bool'), state=dict(default='present', choices=['present', 'absent']) ) ) module = AnsibleModule(argument_spec, supports_check_mode=True) if not HAS_PURITY_FB: module.fail_json(msg='purity_fb sdk is required for this module') if module.params['suffix'] is None: suffix = "snap-" + str((datetime.utcnow() - datetime(1970, 1, 1, 0, 0, 0, 0)).total_seconds()) module.params['suffix'] = suffix.replace(".", "") state = module.params['state'] blade = get_blade(module) fs = get_fs(module, blade) snap = get_fssnapshot(module, blade) if state == 'present' and fs and not fs.destroyed and not snap: create_snapshot(module, blade) elif state == 'present' and fs and not fs.destroyed and snap and not snap.destroyed: update_snapshot(module, blade) elif state == 'present' and fs and not fs.destroyed and snap and snap.destroyed: recover_snapshot(module, blade) elif state == 'present' and fs and fs.destroyed: update_snapshot(module, blade) elif state == 'present' and not fs: update_snapshot(module, blade) elif state == 'absent' and snap and not snap.destroyed: delete_snapshot(module, blade) elif state == 'absent' and snap and snap.destroyed: eradicate_snapshot(module, blade) elif state == 'absent' and not snap: module.exit_json(changed=False) if __name__ == '__main__': main()
gpl-3.0
BeDjango/intef-openedx
lms/djangoapps/verify_student/management/commands/set_software_secure_status.py
63
2223
""" Manually set Software Secure verification status. """ import sys from django.core.management.base import BaseCommand from lms.djangoapps.verify_student.models import ( SoftwareSecurePhotoVerification, VerificationCheckpoint, VerificationStatus ) class Command(BaseCommand): """ Command to trigger the actions that would normally follow Software Secure returning with the results of a photo verification. """ args = "<{approved, denied}, SoftwareSecurePhotoVerification id, [reason_for_denial]>" def handle(self, *args, **kwargs): # pylint: disable=unused-argument from lms.djangoapps.verify_student.views import _set_user_requirement_status status_to_set = args[0] receipt_id = args[1] try: attempt = SoftwareSecurePhotoVerification.objects.get(receipt_id=receipt_id) except SoftwareSecurePhotoVerification.DoesNotExist: self.stderr.write( 'SoftwareSecurePhotoVerification with id {id} could not be found.\n'.format(id=receipt_id) ) sys.exit(1) if status_to_set == 'approved': self.stdout.write('Approving verification for {id}.\n'.format(id=receipt_id)) attempt.approve() _set_user_requirement_status(attempt, 'reverification', 'satisfied') elif status_to_set == 'denied': self.stdout.write('Denying verification for {id}.\n'.format(id=receipt_id)) if len(args) >= 3: reason_for_denial = args[2] else: reason_for_denial = 'Denied via management command.' attempt.deny(reason_for_denial) _set_user_requirement_status(attempt, 'reverification', 'failed', reason_for_denial) else: self.stdout.write('Cannot set id {id} to unrecognized status {status}'.format( id=receipt_id, status=status_to_set )) sys.exit(1) checkpoints = VerificationCheckpoint.objects.filter(photo_verification=attempt).all() VerificationStatus.add_status_from_checkpoints( checkpoints=checkpoints, user=attempt.user, status=status_to_set )
agpl-3.0
google-code-export/django-hotclub
apps/core_apps/tag_app/views.py
2
1919
from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from blog.models import Post from tagging.models import Tag, TaggedItem from photos.models import Photos from bookmarks.models import BookmarkInstance from projects.models import Project, Task from projects.models import Topic as ProjectTopic from tribes.models import Tribe from tribes.models import Topic as TribeTopic from wiki.models import Article as WikiArticle def tags(request, tag, template_name='tags/index.html'): tag = get_object_or_404(Tag, name=tag) alltags = TaggedItem.objects.get_by_model(Post, tag).filter(status=2) phototags = TaggedItem.objects.get_by_model(Photos, tag) bookmarktags = TaggedItem.objects.get_by_model(BookmarkInstance, tag) project_tags = TaggedItem.objects.get_by_model(Project, tag).filter(deleted=False) project_topic_tags = TaggedItem.objects.get_by_model(ProjectTopic, tag).filter(project__deleted=False) project_task_tags = TaggedItem.objects.get_by_model(Task, tag).filter(project__deleted=False) tribe_tags = TaggedItem.objects.get_by_model(Tribe, tag).filter(deleted=False) tribe_topic_tags = TaggedItem.objects.get_by_model(TribeTopic, tag).filter(tribe__deleted=False) # @@@ TODO: tribe_wiki_article_tags and project_wiki_article_tags wiki_article_tags = TaggedItem.objects.get_by_model(WikiArticle, tag) return render_to_response(template_name, { 'tag': tag, 'alltags': alltags, 'phototags': phototags, 'bookmarktags': bookmarktags, 'project_tags': project_tags, 'project_topic_tags': project_topic_tags, 'project_task_tags': project_task_tags, 'tribe_tags': tribe_tags, 'tribe_topic_tags': tribe_topic_tags, 'wiki_article_tags': wiki_article_tags, }, context_instance=RequestContext(request))
mit
Dineshs91/youtube-dl
youtube_dl/extractor/ndr.py
74
4573
# encoding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( ExtractorError, int_or_none, qualities, parse_duration, ) class NDRBaseIE(InfoExtractor): def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group('id') page = self._download_webpage(url, video_id, 'Downloading page') title = self._og_search_title(page).strip() description = self._og_search_description(page) if description: description = description.strip() duration = int_or_none(self._html_search_regex(r'duration: (\d+),\n', page, 'duration', default=None)) if not duration: duration = parse_duration(self._html_search_regex( r'(<span class="min">\d+</span>:<span class="sec">\d+</span>)', page, 'duration', default=None)) formats = [] mp3_url = re.search(r'''\{src:'(?P<audio>[^']+)', type:"audio/mp3"},''', page) if mp3_url: formats.append({ 'url': mp3_url.group('audio'), 'format_id': 'mp3', }) thumbnail = None video_url = re.search(r'''3: \{src:'(?P<video>.+?)\.(lo|hi|hq)\.mp4', type:"video/mp4"},''', page) if video_url: thumbnails = re.findall(r'''\d+: \{src: "([^"]+)"(?: \|\| '[^']+')?, quality: '([^']+)'}''', page) if thumbnails: quality_key = qualities(['xs', 's', 'm', 'l', 'xl']) largest = max(thumbnails, key=lambda thumb: quality_key(thumb[1])) thumbnail = 'http://www.ndr.de' + largest[0] for format_id in 'lo', 'hi', 'hq': formats.append({ 'url': '%s.%s.mp4' % (video_url.group('video'), format_id), 'format_id': format_id, }) if not formats: raise ExtractorError('No media links available for %s' % video_id) return { 'id': video_id, 'title': title, 'description': description, 'thumbnail': thumbnail, 'duration': duration, 'formats': formats, } class NDRIE(NDRBaseIE): IE_NAME = 'ndr' IE_DESC = 'NDR.de - Mediathek' _VALID_URL = r'https?://www\.ndr\.de/.+?(?P<id>\d+)\.html' _TESTS = [ { 'url': 'http://www.ndr.de/fernsehen/sendungen/nordmagazin/Kartoffeltage-in-der-Lewitz,nordmagazin25866.html', 'md5': '5bc5f5b92c82c0f8b26cddca34f8bb2c', 'note': 'Video file', 'info_dict': { 'id': '25866', 'ext': 'mp4', 'title': 'Kartoffeltage in der Lewitz', 'description': 'md5:48c4c04dde604c8a9971b3d4e3b9eaa8', 'duration': 166, }, 'skip': '404 Not found', }, { 'url': 'http://www.ndr.de/fernsehen/Party-Poette-und-Parade,hafengeburtstag988.html', 'md5': 'dadc003c55ae12a5d2f6bd436cd73f59', 'info_dict': { 'id': '988', 'ext': 'mp4', 'title': 'Party, Pötte und Parade', 'description': 'Hunderttausende feiern zwischen Speicherstadt und St. Pauli den 826. Hafengeburtstag. Die NDR Sondersendung zeigt die schönsten und spektakulärsten Bilder vom Auftakt.', 'duration': 3498, }, }, { 'url': 'http://www.ndr.de/info/audio51535.html', 'md5': 'bb3cd38e24fbcc866d13b50ca59307b8', 'note': 'Audio file', 'info_dict': { 'id': '51535', 'ext': 'mp3', 'title': 'La Valette entgeht der Hinrichtung', 'description': 'md5:22f9541913a40fe50091d5cdd7c9f536', 'duration': 884, } } ] class NJoyIE(NDRBaseIE): IE_NAME = 'N-JOY' _VALID_URL = r'https?://www\.n-joy\.de/.+?(?P<id>\d+)\.html' _TEST = { 'url': 'http://www.n-joy.de/entertainment/comedy/comedy_contest/Benaissa-beim-NDR-Comedy-Contest,comedycontest2480.html', 'md5': 'cb63be60cd6f9dd75218803146d8dc67', 'info_dict': { 'id': '2480', 'ext': 'mp4', 'title': 'Benaissa beim NDR Comedy Contest', 'description': 'Von seinem sehr "behaarten" Leben lässt sich Benaissa trotz aller Schwierigkeiten nicht unterkriegen.', 'duration': 654, } }
unlicense
hexlism/css_platform
sleepypuppy/__init__.py
15
6243
from logging import Formatter from logging.handlers import RotatingFileHandler from flask import Flask, redirect, request, abort, send_from_directory from flask.ext import login from flask.ext.bcrypt import Bcrypt from flask.ext.restful import Api from flask.ext.admin import Admin from flask.ext.mail import Mail from functools import wraps from flask.ext.sqlalchemy import SQLAlchemy import flask_wtf import os # Config and App setups app = Flask(__name__, static_folder='static') app.config.from_object('config-default') app.config.update(dict( PREFERRED_URL_SCHEME='https' )) app.debug = app.config.get('DEBUG') # Log handler functionality handler = RotatingFileHandler(app.config.get('LOG_FILE'), maxBytes=10000000, backupCount=100) handler.setFormatter( Formatter( '%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]' ) ) handler.setLevel(app.config.get('LOG_LEVEL')) app.logger.addHandler(handler) def ssl_required(fn): """ SSL decorator """ @wraps(fn) def decorated_view(*args, **kwargs): if app.config.get("SSL"): if request.is_secure: return fn(*args, **kwargs) else: return redirect(request.url.replace("http://", "https://")) return fn(*args, **kwargs) return decorated_view # CSRF Protection csrf_protect = flask_wtf.CsrfProtect(app) # Initalize DB object db = SQLAlchemy(app) # Initalize Bcrypt object for password hashing bcrypt = Bcrypt(app) # Initalize flask mail object for email notifications flask_mail = Mail(app) # Decorator for Token Auth on API Requests from sleepypuppy.admin.admin.models import Administrator def require_appkey(view_function): """ Decorator for api using token based authetication """ @wraps(view_function) def decorated_function(*args, **kwargs): # If the user is attempting to get list of puppyscripts # return the puppyscripts without token auth if request.method == "GET" and request.path.split('/')[2] == 'puppyscript_loader': return view_function(*args, **kwargs) if request.headers.get('Token'): for keys in Administrator.query.all(): if request.headers.get('Token') == keys.api_key: return view_function(*args, **kwargs) abort(401) else: abort(401) return decorated_function # Initalize the Flask API flask_api = Api(app, decorators=[csrf_protect.exempt, require_appkey]) def init_login(): """ Initalize the Flask Login manager """ login_manager = login.LoginManager() login_manager.init_app(app) login_manager.session_protection = "strong" # Create user loader function @login_manager.user_loader def load_user(user_id): return db.session.query(Administrator).get(user_id) # Create the Flask Admin object from admin.admin.views import MyAdminIndexView, AdministratorView flask_admin = Admin(app, 'Sleepy Puppy', index_view=MyAdminIndexView(url='/'), base_template='admin/base.html', template_mode='bootstrap3') # Intalize the login manager for sleepy puppy init_login() # Import the collector which is used to collect capture information from collector import views # Import the screenshot upload handler from upload import upload # noqa # Initalize all Flask API views from api.views import PuppyscriptAssociations, CaptureView, CaptureViewList, PuppyscriptView, PuppyscriptViewList, PayloadView, PayloadViewList, AccessLogView, AccessLogViewList, AssessmentView, AssessmentViewList, GenericCollectorView, GenericCollectorViewList, AssessmentPayloads # noqa flask_api.add_resource(AssessmentViewList, '/api/assessments') flask_api.add_resource(AssessmentView, '/api/assessments/<int:id>') flask_api.add_resource(CaptureViewList, '/api/captures') flask_api.add_resource(CaptureView, '/api/captures/<int:id>') flask_api.add_resource(PuppyscriptView, '/api/puppyscript/<int:id>') flask_api.add_resource(PuppyscriptViewList, '/api/puppyscript') flask_api.add_resource(PayloadViewList, '/api/payloads') flask_api.add_resource(PayloadView, '/api/payloads/<int:id>') flask_api.add_resource(AccessLogViewList, '/api/access_log') flask_api.add_resource(AccessLogView, '/api/access_log/<int:id>') flask_api.add_resource(GenericCollectorViewList, '/api/generic_collector') flask_api.add_resource(GenericCollectorView, '/api/generic_collector/<int:id>') flask_api.add_resource(PuppyscriptAssociations, '/api/puppyscript_loader/<int:id>') flask_api.add_resource(AssessmentPayloads, '/api/assessment_payloads/<int:id>') # Initalize all Flask Admin dashboard views from admin.capture.views import CaptureView from admin.access_log.views import AccessLogView from admin.puppyscript.views import PuppyscriptView from admin.payload.views import PayloadView from admin.user.views import UserView from admin.assessment.views import AssessmentView from admin.collector.views import GenericCollectorView # Import the API views from admin import views # noqa # Configure mappers for db associations from sqlalchemy.orm import configure_mappers configure_mappers() # # Add all Flask Admin routes flask_admin.add_view(PuppyscriptView(db.session)) flask_admin.add_view(PayloadView(db.session)) flask_admin.add_view(CaptureView(db.session)) flask_admin.add_view(GenericCollectorView(db.session)) flask_admin.add_view(AccessLogView(db.session)) flask_admin.add_view(UserView(db.session)) flask_admin.add_view(AssessmentView(db.session)) flask_admin.add_view(AdministratorView(Administrator, db.session)) @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Origin', '*') response.headers.add('Access-Control-Allow-Methods', 'GET,POST') return response # # Route to serve static asset files via Flask @app.route('/static/<filename>') def send_js(filename): return send_from_directory(app.static_folder, filename) @app.route('/favicon.ico') def favicon(): return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico', mimetype='image/vnd.microsoft.icon')
apache-2.0
pambot/SMSBeds
lib/markupsafe/__init__.py
701
10338
# -*- coding: utf-8 -*- """ markupsafe ~~~~~~~~~~ Implements a Markup string. :copyright: (c) 2010 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import re import string from collections import Mapping from markupsafe._compat import text_type, string_types, int_types, \ unichr, iteritems, PY2 __all__ = ['Markup', 'soft_unicode', 'escape', 'escape_silent'] _striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)') _entity_re = re.compile(r'&([^;]+);') class Markup(text_type): r"""Marks a string as being safe for inclusion in HTML/XML output without needing to be escaped. This implements the `__html__` interface a couple of frameworks and web applications use. :class:`Markup` is a direct subclass of `unicode` and provides all the methods of `unicode` just that it escapes arguments passed and always returns `Markup`. The `escape` function returns markup objects so that double escaping can't happen. The constructor of the :class:`Markup` class can be used for three different things: When passed an unicode object it's assumed to be safe, when passed an object with an HTML representation (has an `__html__` method) that representation is used, otherwise the object passed is converted into a unicode string and then assumed to be safe: >>> Markup("Hello <em>World</em>!") Markup(u'Hello <em>World</em>!') >>> class Foo(object): ... def __html__(self): ... return '<a href="#">foo</a>' ... >>> Markup(Foo()) Markup(u'<a href="#">foo</a>') If you want object passed being always treated as unsafe you can use the :meth:`escape` classmethod to create a :class:`Markup` object: >>> Markup.escape("Hello <em>World</em>!") Markup(u'Hello &lt;em&gt;World&lt;/em&gt;!') Operations on a markup string are markup aware which means that all arguments are passed through the :func:`escape` function: >>> em = Markup("<em>%s</em>") >>> em % "foo & bar" Markup(u'<em>foo &amp; bar</em>') >>> strong = Markup("<strong>%(text)s</strong>") >>> strong % {'text': '<blink>hacker here</blink>'} Markup(u'<strong>&lt;blink&gt;hacker here&lt;/blink&gt;</strong>') >>> Markup("<em>Hello</em> ") + "<foo>" Markup(u'<em>Hello</em> &lt;foo&gt;') """ __slots__ = () def __new__(cls, base=u'', encoding=None, errors='strict'): if hasattr(base, '__html__'): base = base.__html__() if encoding is None: return text_type.__new__(cls, base) return text_type.__new__(cls, base, encoding, errors) def __html__(self): return self def __add__(self, other): if isinstance(other, string_types) or hasattr(other, '__html__'): return self.__class__(super(Markup, self).__add__(self.escape(other))) return NotImplemented def __radd__(self, other): if hasattr(other, '__html__') or isinstance(other, string_types): return self.escape(other).__add__(self) return NotImplemented def __mul__(self, num): if isinstance(num, int_types): return self.__class__(text_type.__mul__(self, num)) return NotImplemented __rmul__ = __mul__ def __mod__(self, arg): if isinstance(arg, tuple): arg = tuple(_MarkupEscapeHelper(x, self.escape) for x in arg) else: arg = _MarkupEscapeHelper(arg, self.escape) return self.__class__(text_type.__mod__(self, arg)) def __repr__(self): return '%s(%s)' % ( self.__class__.__name__, text_type.__repr__(self) ) def join(self, seq): return self.__class__(text_type.join(self, map(self.escape, seq))) join.__doc__ = text_type.join.__doc__ def split(self, *args, **kwargs): return list(map(self.__class__, text_type.split(self, *args, **kwargs))) split.__doc__ = text_type.split.__doc__ def rsplit(self, *args, **kwargs): return list(map(self.__class__, text_type.rsplit(self, *args, **kwargs))) rsplit.__doc__ = text_type.rsplit.__doc__ def splitlines(self, *args, **kwargs): return list(map(self.__class__, text_type.splitlines( self, *args, **kwargs))) splitlines.__doc__ = text_type.splitlines.__doc__ def unescape(self): r"""Unescape markup again into an text_type string. This also resolves known HTML4 and XHTML entities: >>> Markup("Main &raquo; <em>About</em>").unescape() u'Main \xbb <em>About</em>' """ from markupsafe._constants import HTML_ENTITIES def handle_match(m): name = m.group(1) if name in HTML_ENTITIES: return unichr(HTML_ENTITIES[name]) try: if name[:2] in ('#x', '#X'): return unichr(int(name[2:], 16)) elif name.startswith('#'): return unichr(int(name[1:])) except ValueError: pass return u'' return _entity_re.sub(handle_match, text_type(self)) def striptags(self): r"""Unescape markup into an text_type string and strip all tags. This also resolves known HTML4 and XHTML entities. Whitespace is normalized to one: >>> Markup("Main &raquo; <em>About</em>").striptags() u'Main \xbb About' """ stripped = u' '.join(_striptags_re.sub('', self).split()) return Markup(stripped).unescape() @classmethod def escape(cls, s): """Escape the string. Works like :func:`escape` with the difference that for subclasses of :class:`Markup` this function would return the correct subclass. """ rv = escape(s) if rv.__class__ is not cls: return cls(rv) return rv def make_simple_escaping_wrapper(name): orig = getattr(text_type, name) def func(self, *args, **kwargs): args = _escape_argspec(list(args), enumerate(args), self.escape) _escape_argspec(kwargs, iteritems(kwargs), self.escape) return self.__class__(orig(self, *args, **kwargs)) func.__name__ = orig.__name__ func.__doc__ = orig.__doc__ return func for method in '__getitem__', 'capitalize', \ 'title', 'lower', 'upper', 'replace', 'ljust', \ 'rjust', 'lstrip', 'rstrip', 'center', 'strip', \ 'translate', 'expandtabs', 'swapcase', 'zfill': locals()[method] = make_simple_escaping_wrapper(method) # new in python 2.5 if hasattr(text_type, 'partition'): def partition(self, sep): return tuple(map(self.__class__, text_type.partition(self, self.escape(sep)))) def rpartition(self, sep): return tuple(map(self.__class__, text_type.rpartition(self, self.escape(sep)))) # new in python 2.6 if hasattr(text_type, 'format'): def format(*args, **kwargs): self, args = args[0], args[1:] formatter = EscapeFormatter(self.escape) kwargs = _MagicFormatMapping(args, kwargs) return self.__class__(formatter.vformat(self, args, kwargs)) def __html_format__(self, format_spec): if format_spec: raise ValueError('Unsupported format specification ' 'for Markup.') return self # not in python 3 if hasattr(text_type, '__getslice__'): __getslice__ = make_simple_escaping_wrapper('__getslice__') del method, make_simple_escaping_wrapper class _MagicFormatMapping(Mapping): """This class implements a dummy wrapper to fix a bug in the Python standard library for string formatting. See http://bugs.python.org/issue13598 for information about why this is necessary. """ def __init__(self, args, kwargs): self._args = args self._kwargs = kwargs self._last_index = 0 def __getitem__(self, key): if key == '': idx = self._last_index self._last_index += 1 try: return self._args[idx] except LookupError: pass key = str(idx) return self._kwargs[key] def __iter__(self): return iter(self._kwargs) def __len__(self): return len(self._kwargs) if hasattr(text_type, 'format'): class EscapeFormatter(string.Formatter): def __init__(self, escape): self.escape = escape def format_field(self, value, format_spec): if hasattr(value, '__html_format__'): rv = value.__html_format__(format_spec) elif hasattr(value, '__html__'): if format_spec: raise ValueError('No format specification allowed ' 'when formatting an object with ' 'its __html__ method.') rv = value.__html__() else: rv = string.Formatter.format_field(self, value, format_spec) return text_type(self.escape(rv)) def _escape_argspec(obj, iterable, escape): """Helper for various string-wrapped functions.""" for key, value in iterable: if hasattr(value, '__html__') or isinstance(value, string_types): obj[key] = escape(value) return obj class _MarkupEscapeHelper(object): """Helper for Markup.__mod__""" def __init__(self, obj, escape): self.obj = obj self.escape = escape __getitem__ = lambda s, x: _MarkupEscapeHelper(s.obj[x], s.escape) __unicode__ = __str__ = lambda s: text_type(s.escape(s.obj)) __repr__ = lambda s: str(s.escape(repr(s.obj))) __int__ = lambda s: int(s.obj) __float__ = lambda s: float(s.obj) # we have to import it down here as the speedups and native # modules imports the markup type which is define above. try: from markupsafe._speedups import escape, escape_silent, soft_unicode except ImportError: from markupsafe._native import escape, escape_silent, soft_unicode if not PY2: soft_str = soft_unicode __all__.append('soft_str')
gpl-2.0
numenta/nupic.research
tests/unit/frameworks/dendrites/routing_test.py
3
2900
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2020, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- """ This module contains unit tests to ensure the RoutingFunction class correctly implements the random routing function """ import unittest import torch from nupic.research.frameworks.dendrites.routing import RoutingFunction class RoutingFunctionTest(unittest.TestCase): """ Tests to check the correctness of the routing function R(j, x), as implemented by the RoutingFunction class """ def test_function_output_satisfies_masks(self): dim_in = 100 dim_out = 100 num_output_masks = 10 sparsity = 0.7 r = RoutingFunction( dim_in=dim_in, dim_out=dim_out, k=num_output_masks, sparsity=sparsity ) x = torch.randn((1, dim_in)) for j in range(num_output_masks): output = r([j], x) self.assertEqual(output.ndim, 2) output = output.view(-1) output_mask_j = r.get_output_mask(j) for i in range(dim_out): if output_mask_j[i] == 0.0: self.assertEqual(output[i], 0.0) def test_function_output(self): dim_in = 100 dim_out = 100 num_output_masks = 10 sparsity = 0.7 r = RoutingFunction( dim_in=dim_in, dim_out=dim_out, k=num_output_masks, sparsity=sparsity ) x = torch.randn((1, dim_in)) output = torch.matmul(r.weights, x.view(-1)) for j in range(num_output_masks): output_mask_j = r.get_output_mask(j) expected_output = output_mask_j * output actual_output = r([j], x) self.assertEqual(actual_output.ndim, 2) actual_output = actual_output.view(-1) for i in range(dim_out): self.assertEqual(actual_output[i], expected_output[i]) if __name__ == "__main__": unittest.main()
agpl-3.0
jamespcole/home-assistant
homeassistant/helpers/system_info.py
11
1220
"""Helper to gather system info.""" import os import platform from typing import Dict from homeassistant.const import __version__ as current_version from homeassistant.loader import bind_hass from homeassistant.util.package import is_virtual_env from .typing import HomeAssistantType @bind_hass async def async_get_system_info(hass: HomeAssistantType) -> Dict: """Return info about the system.""" info_object = { 'version': current_version, 'dev': 'dev' in current_version, 'hassio': hass.components.hassio.is_hassio(), 'virtualenv': is_virtual_env(), 'python_version': platform.python_version(), 'docker': False, 'arch': platform.machine(), 'timezone': str(hass.config.time_zone), 'os_name': platform.system(), } if platform.system() == 'Windows': info_object['os_version'] = platform.win32_ver()[0] elif platform.system() == 'Darwin': info_object['os_version'] = platform.mac_ver()[0] elif platform.system() == 'FreeBSD': info_object['os_version'] = platform.release() elif platform.system() == 'Linux': info_object['docker'] = os.path.isfile('/.dockerenv') return info_object
apache-2.0
Endika/OpenUpgrade
addons/sale_stock/sale_stock.py
8
27378
# -*- 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/>. # ############################################################################## from datetime import datetime, timedelta from openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT, DATETIME_FORMATS_MAP, float_compare from openerp.osv import fields, osv from openerp.tools.safe_eval import safe_eval as eval from openerp.tools.translate import _ import pytz from openerp import SUPERUSER_ID class sale_order(osv.osv): _inherit = "sale.order" def _get_default_warehouse(self, cr, uid, context=None): company_id = self.pool.get('res.users')._get_company(cr, uid, context=context) warehouse_ids = self.pool.get('stock.warehouse').search(cr, uid, [('company_id', '=', company_id)], context=context) if not warehouse_ids: return False return warehouse_ids[0] def _get_shipped(self, cr, uid, ids, name, args, context=None): res = {} for sale in self.browse(cr, uid, ids, context=context): group = sale.procurement_group_id if group: res[sale.id] = all([proc.state in ['cancel', 'done'] for proc in group.procurement_ids]) else: res[sale.id] = False return res def _get_orders(self, cr, uid, ids, context=None): res = set() for move in self.browse(cr, uid, ids, context=context): if move.procurement_id and move.procurement_id.sale_line_id: res.add(move.procurement_id.sale_line_id.order_id.id) return list(res) def _get_orders_procurements(self, cr, uid, ids, context=None): res = set() for proc in self.pool.get('procurement.order').browse(cr, uid, ids, context=context): if proc.state =='done' and proc.sale_line_id: res.add(proc.sale_line_id.order_id.id) return list(res) def _get_picking_ids(self, cr, uid, ids, name, args, context=None): res = {} for sale in self.browse(cr, uid, ids, context=context): if not sale.procurement_group_id: res[sale.id] = [] continue res[sale.id] = self.pool.get('stock.picking').search(cr, uid, [('group_id', '=', sale.procurement_group_id.id)], context=context) return res def _prepare_order_line_procurement(self, cr, uid, order, line, group_id=False, context=None): vals = super(sale_order, self)._prepare_order_line_procurement(cr, uid, order, line, group_id=group_id, context=context) location_id = order.partner_shipping_id.property_stock_customer.id vals['location_id'] = location_id routes = line.route_id and [(4, line.route_id.id)] or [] vals['route_ids'] = routes vals['warehouse_id'] = order.warehouse_id and order.warehouse_id.id or False vals['partner_dest_id'] = order.partner_shipping_id.id return vals _columns = { 'incoterm': fields.many2one('stock.incoterms', 'Incoterm', help="International Commercial Terms are a series of predefined commercial terms used in international transactions."), 'picking_policy': fields.selection([('direct', 'Deliver each product when available'), ('one', 'Deliver all products at once')], 'Shipping Policy', required=True, readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, help="""Pick 'Deliver each product when available' if you allow partial delivery."""), 'order_policy': fields.selection([ ('manual', 'On Demand'), ('picking', 'On Delivery Order'), ('prepaid', 'Before Delivery'), ], 'Create Invoice', required=True, readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, help="""On demand: A draft invoice can be created from the sales order when needed. \nOn delivery order: A draft invoice can be created from the delivery order when the products have been delivered. \nBefore delivery: A draft invoice is created from the sales order and must be paid before the products can be delivered."""), 'shipped': fields.function(_get_shipped, string='Delivered', type='boolean', store={ 'procurement.order': (_get_orders_procurements, ['state'], 10) }), 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', required=True), 'picking_ids': fields.function(_get_picking_ids, method=True, type='one2many', relation='stock.picking', string='Picking associated to this sale'), } _defaults = { 'warehouse_id': _get_default_warehouse, 'picking_policy': 'direct', 'order_policy': 'manual', } def onchange_warehouse_id(self, cr, uid, ids, warehouse_id, context=None): val = {} if warehouse_id: warehouse = self.pool.get('stock.warehouse').browse(cr, uid, warehouse_id, context=context) if warehouse.company_id: val['company_id'] = warehouse.company_id.id return {'value': val} def action_view_delivery(self, cr, uid, ids, context=None): ''' This function returns an action that display existing delivery orders of given sales order ids. It can either be a in a list or in a form view, if there is only one delivery order to show. ''' mod_obj = self.pool.get('ir.model.data') act_obj = self.pool.get('ir.actions.act_window') result = mod_obj.get_object_reference(cr, uid, 'stock', 'action_picking_tree_all') id = result and result[1] or False result = act_obj.read(cr, uid, [id], context=context)[0] #compute the number of delivery orders to display pick_ids = [] for so in self.browse(cr, uid, ids, context=context): pick_ids += [picking.id for picking in so.picking_ids] #choose the view_mode accordingly if len(pick_ids) > 1: result['domain'] = "[('id','in',[" + ','.join(map(str, pick_ids)) + "])]" else: res = mod_obj.get_object_reference(cr, uid, 'stock', 'view_picking_form') result['views'] = [(res and res[1] or False, 'form')] result['res_id'] = pick_ids and pick_ids[0] or False return result def action_invoice_create(self, cr, uid, ids, grouped=False, states=['confirmed', 'done', 'exception'], date_invoice = False, context=None): move_obj = self.pool.get("stock.move") res = super(sale_order,self).action_invoice_create(cr, uid, ids, grouped=grouped, states=states, date_invoice = date_invoice, context=context) for order in self.browse(cr, uid, ids, context=context): if order.order_policy == 'picking': for picking in order.picking_ids: move_obj.write(cr, uid, [x.id for x in picking.move_lines], {'invoice_state': 'invoiced'}, context=context) return res def action_wait(self, cr, uid, ids, context=None): res = super(sale_order, self).action_wait(cr, uid, ids, context=context) for o in self.browse(cr, uid, ids): noprod = self.test_no_product(cr, uid, o, context) if noprod and o.order_policy=='picking': self.write(cr, uid, [o.id], {'order_policy': 'manual'}, context=context) return res def _get_date_planned(self, cr, uid, order, line, start_date, context=None): date_planned = super(sale_order, self)._get_date_planned(cr, uid, order, line, start_date, context=context) date_planned = (date_planned - timedelta(days=order.company_id.security_lead)).strftime(DEFAULT_SERVER_DATETIME_FORMAT) return date_planned def _prepare_procurement_group(self, cr, uid, order, context=None): res = super(sale_order, self)._prepare_procurement_group(cr, uid, order, context=None) res.update({'move_type': order.picking_policy}) return res def action_ship_end(self, cr, uid, ids, context=None): super(sale_order, self).action_ship_end(cr, uid, ids, context=context) for order in self.browse(cr, uid, ids, context=context): val = {'shipped': True} if order.state == 'shipping_except': val['state'] = 'progress' if (order.order_policy == 'manual'): for line in order.order_line: if (not line.invoiced) and (line.state not in ('cancel', 'draft')): val['state'] = 'manual' break res = self.write(cr, uid, [order.id], val) return True def has_stockable_products(self, cr, uid, ids, *args): for order in self.browse(cr, uid, ids): for order_line in order.order_line: if order_line.state == 'cancel': continue if order_line.product_id and order_line.product_id.type in ('product', 'consu'): return True return False class product_product(osv.osv): _inherit = 'product.product' def need_procurement(self, cr, uid, ids, context=None): #when sale/product is installed alone, there is no need to create procurements, but with sale_stock #we must create a procurement for each product that is not a service. for product in self.browse(cr, uid, ids, context=context): if product.id and product.type != 'service': return True return super(product_product, self).need_procurement(cr, uid, ids, context=context) class sale_order_line(osv.osv): _inherit = 'sale.order.line' def _number_packages(self, cr, uid, ids, field_name, arg, context=None): res = {} for line in self.browse(cr, uid, ids, context=context): try: res[line.id] = int((line.product_uom_qty+line.product_packaging.qty-0.0001) / line.product_packaging.qty) except: res[line.id] = 1 return res _columns = { 'product_packaging': fields.many2one('product.packaging', 'Packaging'), 'number_packages': fields.function(_number_packages, type='integer', string='Number Packages'), 'route_id': fields.many2one('stock.location.route', 'Route', domain=[('sale_selectable', '=', True)]), 'product_tmpl_id': fields.related('product_id', 'product_tmpl_id', type='many2one', relation='product.template', string='Product Template'), } _defaults = { 'product_packaging': False, } def product_packaging_change(self, cr, uid, ids, pricelist, product, qty=0, uom=False, partner_id=False, packaging=False, flag=False, context=None): if not product: return {'value': {'product_packaging': False}} product_obj = self.pool.get('product.product') product_uom_obj = self.pool.get('product.uom') pack_obj = self.pool.get('product.packaging') warning = {} result = {} warning_msgs = '' if flag: res = self.product_id_change(cr, uid, ids, pricelist=pricelist, product=product, qty=qty, uom=uom, partner_id=partner_id, packaging=packaging, flag=False, context=context) warning_msgs = res.get('warning') and res['warning'].get('message', '') or '' products = product_obj.browse(cr, uid, product, context=context) if not products.packaging_ids: packaging = result['product_packaging'] = False if packaging: default_uom = products.uom_id and products.uom_id.id pack = pack_obj.browse(cr, uid, packaging, context=context) q = product_uom_obj._compute_qty(cr, uid, uom, pack.qty, default_uom) # qty = qty - qty % q + q if qty and (q and not (qty % q) == 0): ean = pack.ean or _('(n/a)') qty_pack = pack.qty type_ul = pack.ul if not warning_msgs: warn_msg = _("You selected a quantity of %d Units.\n" "But it's not compatible with the selected packaging.\n" "Here is a proposition of quantities according to the packaging:\n" "EAN: %s Quantity: %s Type of ul: %s") % \ (qty, ean, qty_pack, type_ul.name) warning_msgs += _("Picking Information ! : ") + warn_msg + "\n\n" warning = { 'title': _('Configuration Error!'), 'message': warning_msgs } result['product_uom_qty'] = qty return {'value': result, 'warning': warning} def _check_routing(self, cr, uid, ids, product, warehouse_id, context=None): """ Verify the route of the product based on the warehouse return True if the product availibility in stock does not need to be verified """ is_available = False if warehouse_id: warehouse = self.pool['stock.warehouse'].browse(cr, uid, warehouse_id, context=context) for product_route in product.route_ids: if warehouse.mto_pull_id and warehouse.mto_pull_id.route_id and warehouse.mto_pull_id.route_id.id == product_route.id: is_available = True break else: try: mto_route_id = self.pool['stock.warehouse']._get_mto_route(cr, uid, context=context) except osv.except_osv: # if route MTO not found in ir_model_data, we treat the product as in MTS mto_route_id = False if mto_route_id: for product_route in product.route_ids: if product_route.id == mto_route_id: is_available = True break if not is_available: product_routes = product.route_ids + product.categ_id.total_route_ids for pull_rule in product_routes.mapped('pull_ids'): if pull_rule.picking_type_id.sudo().default_location_src_id.usage == 'supplier' and\ pull_rule.picking_type_id.sudo().default_location_dest_id.usage == 'customer': is_available = True break return is_available def product_id_change_with_wh(self, cr, uid, ids, pricelist, product, qty=0, uom=False, qty_uos=0, uos=False, name='', partner_id=False, lang=False, update_tax=True, date_order=False, packaging=False, fiscal_position=False, flag=False, warehouse_id=False, context=None): context = context or {} product_uom_obj = self.pool.get('product.uom') product_obj = self.pool.get('product.product') warning = {} #UoM False due to hack which makes sure uom changes price, ... in product_id_change res = self.product_id_change(cr, uid, ids, pricelist, product, qty=qty, uom=False, qty_uos=qty_uos, uos=uos, name=name, partner_id=partner_id, lang=lang, update_tax=update_tax, date_order=date_order, packaging=packaging, fiscal_position=fiscal_position, flag=flag, context=context) if not product: res['value'].update({'product_packaging': False}) return res # set product uom in context to get virtual stock in current uom if 'product_uom' in res.get('value', {}): # use the uom changed by super call context = dict(context, uom=res['value']['product_uom']) elif uom: # fallback on selected context = dict(context, uom=uom) #update of result obtained in super function product_obj = product_obj.browse(cr, uid, product, context=context) res['value'].update({'product_tmpl_id': product_obj.product_tmpl_id.id, 'delay': (product_obj.sale_delay or 0.0)}) # Calling product_packaging_change function after updating UoM res_packing = self.product_packaging_change(cr, uid, ids, pricelist, product, qty, uom, partner_id, packaging, context=context) res['value'].update(res_packing.get('value', {})) warning_msgs = res_packing.get('warning') and res_packing['warning']['message'] or '' if product_obj.type == 'product': #determine if the product needs further check for stock availibility is_available = self._check_routing(cr, uid, ids, product_obj, warehouse_id, context=context) #check if product is available, and if not: raise a warning, but do this only for products that aren't processed in MTO if not is_available: uom_record = False if uom: uom_record = product_uom_obj.browse(cr, uid, uom, context=context) if product_obj.uom_id.category_id.id != uom_record.category_id.id: uom_record = False if not uom_record: uom_record = product_obj.uom_id compare_qty = float_compare(product_obj.virtual_available, qty, precision_rounding=uom_record.rounding) if compare_qty == -1: warn_msg = _('You plan to sell %.2f %s but you only have %.2f %s available !\nThe real stock is %.2f %s. (without reservations)') % \ (qty, uom_record.name, max(0,product_obj.virtual_available), uom_record.name, max(0,product_obj.qty_available), uom_record.name) warning_msgs += _("Not enough stock ! : ") + warn_msg + "\n\n" #update of warning messages if warning_msgs: warning = { 'title': _('Configuration Error!'), 'message' : warning_msgs } res.update({'warning': warning}) return res def button_cancel(self, cr, uid, ids, context=None): lines = self.browse(cr, uid, ids, context=context) for procurement in lines.mapped('procurement_ids'): for move in procurement.move_ids: if move.state == 'done' and not move.scrapped: raise osv.except_osv(_('Invalid Action!'), _('You cannot cancel a sale order line which is linked to a stock move already done.')) return super(sale_order_line, self).button_cancel(cr, uid, ids, context=context) class stock_move(osv.osv): _inherit = 'stock.move' def _create_invoice_line_from_vals(self, cr, uid, move, invoice_line_vals, context=None): invoice_line_id = super(stock_move, self)._create_invoice_line_from_vals(cr, uid, move, invoice_line_vals, context=context) if context.get('inv_type') in ('out_invoice', 'out_refund') and move.procurement_id and move.procurement_id.sale_line_id: sale_line = move.procurement_id.sale_line_id self.pool.get('sale.order.line').write(cr, uid, [sale_line.id], { 'invoice_lines': [(4, invoice_line_id)] }, context=context) self.pool.get('sale.order').write(cr, uid, [sale_line.order_id.id], { 'invoice_ids': [(4, invoice_line_vals['invoice_id'])], }) sale_line_obj = self.pool.get('sale.order.line') invoice_line_obj = self.pool.get('account.invoice.line') sale_line_ids = sale_line_obj.search(cr, uid, [('order_id', '=', move.procurement_id.sale_line_id.order_id.id), ('invoiced', '=', False), '|', ('product_id', '=', False), ('product_id.type', '=', 'service')], context=context) if sale_line_ids: created_lines = sale_line_obj.invoice_line_create(cr, uid, sale_line_ids, context=context) invoice_line_obj.write(cr, uid, created_lines, {'invoice_id': invoice_line_vals['invoice_id']}, context=context) return invoice_line_id def _get_master_data(self, cr, uid, move, company, context=None): if context.get('inv_type') in ('out_invoice', 'out_refund') and move.procurement_id and move.procurement_id.sale_line_id and move.procurement_id.sale_line_id.order_id.order_policy == 'picking': sale_order = move.procurement_id.sale_line_id.order_id return sale_order.partner_invoice_id, sale_order.user_id.id, sale_order.pricelist_id.currency_id.id elif move.picking_id.sale_id and context.get('inv_type') in ('out_invoice', 'out_refund'): # In case of extra move, it is better to use the same data as the original moves sale_order = move.picking_id.sale_id return sale_order.partner_invoice_id, sale_order.user_id.id, sale_order.pricelist_id.currency_id.id return super(stock_move, self)._get_master_data(cr, uid, move, company, context=context) def _get_invoice_line_vals(self, cr, uid, move, partner, inv_type, context=None): res = super(stock_move, self)._get_invoice_line_vals(cr, uid, move, partner, inv_type, context=context) if inv_type in ('out_invoice', 'out_refund') and move.procurement_id and move.procurement_id.sale_line_id: sale_line = move.procurement_id.sale_line_id res['invoice_line_tax_id'] = [(6, 0, [x.id for x in sale_line.tax_id])] res['account_analytic_id'] = sale_line.order_id.project_id and sale_line.order_id.project_id.id or False res['discount'] = sale_line.discount if move.product_id.id != sale_line.product_id.id: res['price_unit'] = self.pool['product.pricelist'].price_get( cr, uid, [sale_line.order_id.pricelist_id.id], move.product_id.id, move.product_uom_qty or 1.0, sale_line.order_id.partner_id, context=context)[sale_line.order_id.pricelist_id.id] else: res['price_unit'] = sale_line.price_unit uos_coeff = move.product_uom_qty and move.product_uos_qty / move.product_uom_qty or 1.0 res['price_unit'] = res['price_unit'] / uos_coeff return res def _get_moves_taxes(self, cr, uid, moves, inv_type, context=None): is_extra_move, extra_move_tax = super(stock_move, self)._get_moves_taxes(cr, uid, moves, inv_type, context=context) if inv_type == 'out_invoice': for move in moves: if move.procurement_id and move.procurement_id.sale_line_id: is_extra_move[move.id] = False extra_move_tax[move.picking_id, move.product_id] = [(6, 0, [x.id for x in move.procurement_id.sale_line_id.tax_id])] elif move.picking_id.sale_id and move.product_id.product_tmpl_id.taxes_id: fp = move.picking_id.sale_id.fiscal_position res = self.pool.get("account.invoice.line").product_id_change(cr, uid, [], move.product_id.id, None, partner_id=move.picking_id.partner_id.id, fposition_id=(fp and fp.id), context=context) extra_move_tax[0, move.product_id] = [(6, 0, res['value']['invoice_line_tax_id'])] else: extra_move_tax[0, move.product_id] = [(6, 0, [x.id for x in move.product_id.product_tmpl_id.taxes_id])] return (is_extra_move, extra_move_tax) def _get_taxes(self, cr, uid, move, context=None): if move.procurement_id.sale_line_id.tax_id: return [tax.id for tax in move.procurement_id.sale_line_id.tax_id] return super(stock_move, self)._get_taxes(cr, uid, move, context=context) class stock_location_route(osv.osv): _inherit = "stock.location.route" _columns = { 'sale_selectable': fields.boolean("Selectable on Sales Order Line") } class stock_picking(osv.osv): _inherit = "stock.picking" def _get_partner_to_invoice(self, cr, uid, picking, context=None): """ Inherit the original function of the 'stock' module We select the partner of the sales order as the partner of the customer invoice """ if context.get('inv_type') and context['inv_type'] in ('out_invoice', 'out_refund'): if picking.sale_id: saleorder_ids = self.pool['sale.order'].search(cr, uid, [('procurement_group_id' ,'=', picking.group_id.id)], context=context) saleorders = self.pool['sale.order'].browse(cr, uid, saleorder_ids, context=context) if saleorders and saleorders[0] and saleorders[0].order_policy == 'picking': saleorder = saleorders[0] return saleorder.partner_invoice_id.id return super(stock_picking, self)._get_partner_to_invoice(cr, uid, picking, context=context) def _get_sale_id(self, cr, uid, ids, name, args, context=None): sale_obj = self.pool.get("sale.order") res = {} for picking in self.browse(cr, uid, ids, context=context): res[picking.id] = False if picking.group_id: sale_ids = sale_obj.search(cr, uid, [('procurement_group_id', '=', picking.group_id.id)], context=context) if sale_ids: res[picking.id] = sale_ids[0] return res _columns = { 'sale_id': fields.function(_get_sale_id, type="many2one", relation="sale.order", string="Sale Order"), } def _create_invoice_from_picking(self, cr, uid, picking, vals, context=None): sale_obj = self.pool.get('sale.order') sale_line_obj = self.pool.get('sale.order.line') invoice_line_obj = self.pool.get('account.invoice.line') invoice_id = super(stock_picking, self)._create_invoice_from_picking(cr, uid, picking, vals, context=context) return invoice_id def _get_invoice_vals(self, cr, uid, key, inv_type, journal_id, move, context=None): inv_vals = super(stock_picking, self)._get_invoice_vals(cr, uid, key, inv_type, journal_id, move, context=context) sale = move.picking_id.sale_id if sale and inv_type in ('out_invoice', 'out_refund'): inv_vals.update({ 'fiscal_position': sale.fiscal_position.id, 'payment_term': sale.payment_term.id, 'user_id': sale.user_id.id, 'section_id': sale.section_id.id, 'name': sale.client_order_ref or '', 'comment': sale.note, }) return inv_vals
agpl-3.0
rvalyi/OpenUpgrade
addons/point_of_sale/report/pos_order_report.py
46
4005
# -*- 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/>. # ############################################################################## from openerp import tools from openerp.osv import fields,osv class pos_order_report(osv.osv): _name = "report.pos.order" _description = "Point of Sale Orders Statistics" _auto = False _columns = { 'date': fields.date('Date Order', readonly=True), 'partner_id':fields.many2one('res.partner', 'Partner', readonly=True), 'product_id':fields.many2one('product.product', 'Product', readonly=True), 'state': fields.selection([('draft', 'New'), ('paid', 'Closed'), ('done', 'Synchronized'), ('invoiced', 'Invoiced'), ('cancel', 'Cancelled')], 'Status'), 'user_id':fields.many2one('res.users', 'Salesperson', readonly=True), 'price_total':fields.float('Total Price', readonly=True), 'total_discount':fields.float('Total Discount', readonly=True), 'average_price': fields.float('Average Price', readonly=True,group_operator="avg"), 'location_id':fields.many2one('stock.location', 'Location', readonly=True), 'company_id':fields.many2one('res.company', 'Company', readonly=True), 'nbr':fields.integer('# of Lines', readonly=True), 'product_qty':fields.integer('# of Qty', readonly=True), 'journal_id': fields.many2one('account.journal', 'Journal'), 'delay_validation': fields.integer('Delay Validation'), } _order = 'date desc' def init(self, cr): tools.drop_view_if_exists(cr, 'report_pos_order') cr.execute(""" create or replace view report_pos_order as ( select min(l.id) as id, count(*) as nbr, s.date_order as date, sum(l.qty * u.factor) as product_qty, sum(l.qty * l.price_unit) as price_total, sum((l.qty * l.price_unit) * (l.discount / 100)) as total_discount, (sum(l.qty*l.price_unit)/sum(l.qty * u.factor))::decimal(16,2) as average_price, sum(cast(to_char(date_trunc('day',s.date_order) - date_trunc('day',s.create_date),'DD') as int)) as delay_validation, s.partner_id as partner_id, s.state as state, s.user_id as user_id, s.location_id as location_id, s.company_id as company_id, s.sale_journal as journal_id, l.product_id as product_id from pos_order_line as l left join pos_order s on (s.id=l.order_id) left join product_template pt on (pt.id=l.product_id) left join product_uom u on (u.id=pt.uom_id) group by s.date_order, s.partner_id,s.state, s.user_id,s.location_id,s.company_id,s.sale_journal,l.product_id,s.create_date having sum(l.qty * u.factor) != 0)""") # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
hgl888/chromium-crosswalk-efl
build/win/install-build-deps.py
153
1463
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import shutil import sys import os def patch_msbuild(): """VS2010 MSBuild has a ULDI bug that we patch here. See http://goo.gl/Pn8tj. """ source_path = os.path.join(os.environ['ProgramFiles(x86)'], "MSBuild", "Microsoft.Cpp", "v4.0", "Microsoft.CppBuild.targets") backup_path = source_path + ".backup" if not os.path.exists(backup_path): try: print "Backing up %s..." % source_path shutil.copyfile(source_path, backup_path) except IOError: print "Could not back up %s to %s. Run as Administrator?" % ( source_path, backup_path) return 1 source = open(source_path).read() base = ('''<Target Name="GetResolvedLinkObjs" Returns="@(ObjFullPath)" ''' '''DependsOnTargets="$(CommonBuildOnlyTargets);ComputeCLOutputs;''' '''ResolvedLinkObjs"''') find = base + '>' replace = base + ''' Condition="'$(ConfigurationType)'=='StaticLibrary'">''' result = source.replace(find, replace) if result != source: open(source_path, "w").write(result) print "Patched %s." % source_path return 0 def main(): return patch_msbuild() if __name__ == "__main__": sys.exit(main())
bsd-3-clause
spacecowboy/gensim
gensim/models/word2vec.py
10
71322
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2013 Radim Rehurek <me@radimrehurek.com> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html """ Deep learning via word2vec's "skip-gram and CBOW models", using either hierarchical softmax or negative sampling [1]_ [2]_. The training algorithms were originally ported from the C package https://code.google.com/p/word2vec/ and extended with additional functionality. For a blog tutorial on gensim word2vec, with an interactive web app trained on GoogleNews, visit http://radimrehurek.com/2014/02/word2vec-tutorial/ **Make sure you have a C compiler before installing gensim, to use optimized (compiled) word2vec training** (70x speedup compared to plain NumPy implementation [3]_). Initialize a model with e.g.:: >>> model = Word2Vec(sentences, size=100, window=5, min_count=5, workers=4) Persist a model to disk with:: >>> model.save(fname) >>> model = Word2Vec.load(fname) # you can continue training with the loaded model! The model can also be instantiated from an existing file on disk in the word2vec C format:: >>> model = Word2Vec.load_word2vec_format('/tmp/vectors.txt', binary=False) # C text format >>> model = Word2Vec.load_word2vec_format('/tmp/vectors.bin', binary=True) # C binary format You can perform various syntactic/semantic NLP word tasks with the model. Some of them are already built-in:: >>> model.most_similar(positive=['woman', 'king'], negative=['man']) [('queen', 0.50882536), ...] >>> model.doesnt_match("breakfast cereal dinner lunch".split()) 'cereal' >>> model.similarity('woman', 'man') 0.73723527 >>> model['computer'] # raw numpy vector of a word array([-0.00449447, -0.00310097, 0.02421786, ...], dtype=float32) and so on. If you're finished training a model (=no more updates, only querying), you can do >>> model.init_sims(replace=True) to trim unneeded model memory = use (much) less RAM. Note that there is a :mod:`gensim.models.phrases` module which lets you automatically detect phrases longer than one word. Using phrases, you can learn a word2vec model where "words" are actually multiword expressions, such as `new_york_times` or `financial_crisis`: >>> bigram_transformer = gensim.models.Phrases(sentences) >>> model = Word2Vec(bigram_transformed[sentences], size=100, ...) .. [1] Tomas Mikolov, Kai Chen, Greg Corrado, and Jeffrey Dean. Efficient Estimation of Word Representations in Vector Space. In Proceedings of Workshop at ICLR, 2013. .. [2] Tomas Mikolov, Ilya Sutskever, Kai Chen, Greg Corrado, and Jeffrey Dean. Distributed Representations of Words and Phrases and their Compositionality. In Proceedings of NIPS, 2013. .. [3] Optimizing word2vec in gensim, http://radimrehurek.com/2013/09/word2vec-in-python-part-two-optimizing/ """ from __future__ import division # py3 "true division" import logging import sys import os import heapq from timeit import default_timer from copy import deepcopy from collections import defaultdict import threading import time try: from queue import Queue, Empty except ImportError: from Queue import Queue, Empty from numpy import exp, log, dot, zeros, outer, random, dtype, float32 as REAL,\ uint32, seterr, array, uint8, vstack, fromstring, sqrt, newaxis,\ ndarray, empty, sum as np_sum, prod, ones from gensim import utils, matutils # utility fnc for pickling, common scipy operations etc from six import iteritems, itervalues, string_types from six.moves import xrange from types import GeneratorType logger = logging.getLogger("gensim.models.word2vec") try: from gensim.models.word2vec_inner import train_sentence_sg, train_sentence_cbow, FAST_VERSION except ImportError: # failed... fall back to plain numpy (20-80x slower training than the above) FAST_VERSION = -1 def train_sentence_sg(model, sentence, alpha, work=None): """ Update skip-gram model by training on a single sentence. The sentence is a list of string tokens, which are looked up in the model's vocab dictionary. Called internally from `Word2Vec.train()`. This is the non-optimized, Python version. If you have cython installed, gensim will use the optimized version from word2vec_inner instead. """ word_vocabs = [model.vocab[w] for w in sentence if w in model.vocab and model.vocab[w].sample_int > model.random.rand() * 2**32] for pos, word in enumerate(word_vocabs): reduced_window = model.random.randint(model.window) # `b` in the original word2vec code # now go over all words from the (reduced) window, predicting each one in turn start = max(0, pos - model.window + reduced_window) for pos2, word2 in enumerate(word_vocabs[start:(pos + model.window + 1 - reduced_window)], start): # don't train on the `word` itself if pos2 != pos: train_sg_pair(model, model.index2word[word.index], word2.index, alpha) return len(word_vocabs) def train_sentence_cbow(model, sentence, alpha, work=None, neu1=None): """ Update CBOW model by training on a single sentence. The sentence is a list of string tokens, which are looked up in the model's vocab dictionary. Called internally from `Word2Vec.train()`. This is the non-optimized, Python version. If you have cython installed, gensim will use the optimized version from word2vec_inner instead. """ word_vocabs = [model.vocab[w] for w in sentence if w in model.vocab and model.vocab[w].sample_int > model.random.rand() * 2**32] for pos, word in enumerate(word_vocabs): reduced_window = model.random.randint(model.window) # `b` in the original word2vec code start = max(0, pos - model.window + reduced_window) window_pos = enumerate(word_vocabs[start:(pos + model.window + 1 - reduced_window)], start) word2_indices = [word2.index for pos2, word2 in window_pos if (word2 is not None and pos2 != pos)] l1 = np_sum(model.syn0[word2_indices], axis=0) # 1 x vector_size if word2_indices and model.cbow_mean: l1 /= len(word2_indices) train_cbow_pair(model, word, word2_indices, l1, alpha) return len(word_vocabs) def train_sg_pair(model, word, context_index, alpha, learn_vectors=True, learn_hidden=True, context_vectors=None, context_locks=None): if context_vectors is None: context_vectors = model.syn0 if context_locks is None: context_locks = model.syn0_lockf if word not in model.vocab: return predict_word = model.vocab[word] # target word (NN output) l1 = context_vectors[context_index] # input word (NN input/projection layer) lock_factor = context_locks[context_index] neu1e = zeros(l1.shape) if model.hs: # work on the entire tree at once, to push as much work into numpy's C routines as possible (performance) l2a = deepcopy(model.syn1[predict_word.point]) # 2d matrix, codelen x layer1_size fa = 1.0 / (1.0 + exp(-dot(l1, l2a.T))) # propagate hidden -> output ga = (1 - predict_word.code - fa) * alpha # vector of error gradients multiplied by the learning rate if learn_hidden: model.syn1[predict_word.point] += outer(ga, l1) # learn hidden -> output neu1e += dot(ga, l2a) # save error if model.negative: # use this word (label = 1) + `negative` other random words not from this sentence (label = 0) word_indices = [predict_word.index] while len(word_indices) < model.negative + 1: w = model.cum_table.searchsorted(model.random.randint(model.cum_table[-1])) if w != predict_word.index: word_indices.append(w) l2b = model.syn1neg[word_indices] # 2d matrix, k+1 x layer1_size fb = 1. / (1. + exp(-dot(l1, l2b.T))) # propagate hidden -> output gb = (model.neg_labels - fb) * alpha # vector of error gradients multiplied by the learning rate if learn_hidden: model.syn1neg[word_indices] += outer(gb, l1) # learn hidden -> output neu1e += dot(gb, l2b) # save error if learn_vectors: l1 += neu1e * lock_factor # learn input -> hidden (mutates model.syn0[word2.index], if that is l1) return neu1e def train_cbow_pair(model, word, input_word_indices, l1, alpha, learn_vectors=True, learn_hidden=True): neu1e = zeros(l1.shape) if model.hs: l2a = model.syn1[word.point] # 2d matrix, codelen x layer1_size fa = 1. / (1. + exp(-dot(l1, l2a.T))) # propagate hidden -> output ga = (1. - word.code - fa) * alpha # vector of error gradients multiplied by the learning rate if learn_hidden: model.syn1[word.point] += outer(ga, l1) # learn hidden -> output neu1e += dot(ga, l2a) # save error if model.negative: # use this word (label = 1) + `negative` other random words not from this sentence (label = 0) word_indices = [word.index] while len(word_indices) < model.negative + 1: w = model.cum_table.searchsorted(model.random.randint(model.cum_table[-1])) if w != word.index: word_indices.append(w) l2b = model.syn1neg[word_indices] # 2d matrix, k+1 x layer1_size fb = 1. / (1. + exp(-dot(l1, l2b.T))) # propagate hidden -> output gb = (model.neg_labels - fb) * alpha # vector of error gradients multiplied by the learning rate if learn_hidden: model.syn1neg[word_indices] += outer(gb, l1) # learn hidden -> output neu1e += dot(gb, l2b) # save error if learn_vectors: # learn input -> hidden, here for all words in the window separately if not model.cbow_mean and input_word_indices: neu1e /= len(input_word_indices) for i in input_word_indices: model.syn0[i] += neu1e * model.syn0_lockf[i] return neu1e # could move this import up to where train_* is imported, # but for now just do it separately incase there are unforseen bugs in score_ try: from gensim.models.word2vec_inner import score_sentence_sg, score_sentence_cbow except ImportError: def score_sentence_sg(model, sentence, work=None): """ Obtain likelihood score for a single sentence in a fitted skip-gram representaion. The sentence is a list of Vocab objects (or None, when the corresponding word is not in the vocabulary). Called internally from `Word2Vec.score()`. This is the non-optimized, Python version. If you have cython installed, gensim will use the optimized version from word2vec_inner instead. """ log_prob_sentence = 0.0 if model.negative: raise RuntimeError("scoring is only available for HS=True") word_vocabs = [model.vocab[w] for w in sentence if w in model.vocab] for pos, word in enumerate(word_vocabs): if word is None: continue # OOV word in the input sentence => skip # now go over all words from the window, predicting each one in turn start = max(0, pos - model.window) for pos2, word2 in enumerate(sentence[start:(pos + model.window + 1)], start): # don't train on OOV words and on the `word` itself if word2 and not (pos2 == pos): log_prob_sentence += score_sg_pair(model, word, word2) return log_prob_sentence def score_sentence_cbow(model, sentence, alpha, work=None, neu1=None): """ Obtain likelihood score for a single sentence in a fitted CBOW representaion. The sentence is a list of Vocab objects (or None, where the corresponding word is not in the vocabulary. Called internally from `Word2Vec.score()`. This is the non-optimized, Python version. If you have cython installed, gensim will use the optimized version from word2vec_inner instead. """ log_prob_sentence = 0.0 if model.negative: raise RuntimeError("scoring is only available for HS=True") word_vocabs = [model.vocab[w] for w in sentence if w in model.vocab] for pos, word in enumerate(word_vocabs): if word is None: continue # OOV word in the input sentence => skip start = max(0, pos - model.window) window_pos = enumerate(sentence[start:(pos + model.window + 1)], start) word2_indices = [word2.index for pos2, word2 in window_pos if (word2 is not None and pos2 != pos)] l1 = np_sum(model.syn0[word2_indices], axis=0) # 1 x layer1_size if word2_indices and model.cbow_mean: l1 /= len(word2_indices) log_prob_sentence += score_cbow_pair(model, word, word2_indices, l1) return log_prob_sentence def score_sg_pair(model, word, word2): l1 = model.syn0[word2.index] l2a = deepcopy(model.syn1[word.point]) # 2d matrix, codelen x layer1_size sgn = -1.0**word.code # ch function, 0-> 1, 1 -> -1 lprob = -log(1.0 + exp(-sgn*dot(l1, l2a.T))) return sum(lprob) def score_cbow_pair(model, word, word2_indices, l1): l2a = model.syn1[word.point] # 2d matrix, codelen x layer1_size sgn = -1.0**word.code # ch function, 0-> 1, 1 -> -1 lprob = -log(1.0 + exp(-sgn*dot(l1, l2a.T))) return sum(lprob) class Vocab(object): """ A single vocabulary item, used internally for collecting per-word frequency/sampling info, and for constructing binary trees (incl. both word leaves and inner nodes). """ def __init__(self, **kwargs): self.count = 0 self.__dict__.update(kwargs) def __lt__(self, other): # used for sorting in a priority queue return self.count < other.count def __str__(self): vals = ['%s:%r' % (key, self.__dict__[key]) for key in sorted(self.__dict__) if not key.startswith('_')] return "%s(%s)" % (self.__class__.__name__, ', '.join(vals)) class Word2Vec(utils.SaveLoad): """ Class for training, using and evaluating neural networks described in https://code.google.com/p/word2vec/ The model can be stored/loaded via its `save()` and `load()` methods, or stored/loaded in a format compatible with the original word2vec implementation via `save_word2vec_format()` and `load_word2vec_format()`. """ def __init__( self, sentences=None, size=100, alpha=0.025, window=5, min_count=5, max_vocab_size=None, sample=0, seed=1, workers=1, min_alpha=0.0001, sg=1, hs=1, negative=0, cbow_mean=0, hashfxn=hash, iter=1, null_word=0): """ Initialize the model from an iterable of `sentences`. Each sentence is a list of words (unicode strings) that will be used for training. The `sentences` iterable can be simply a list, but for larger corpora, consider an iterable that streams the sentences directly from disk/network. See :class:`BrownCorpus`, :class:`Text8Corpus` or :class:`LineSentence` in this module for such examples. If you don't supply `sentences`, the model is left uninitialized -- use if you plan to initialize it in some other way. `sg` defines the training algorithm. By default (`sg=1`), skip-gram is used. Otherwise, `cbow` is employed. `size` is the dimensionality of the feature vectors. `window` is the maximum distance between the current and predicted word within a sentence. `alpha` is the initial learning rate (will linearly drop to zero as training progresses). `seed` = for the random number generator. Initial vectors for each word are seeded with a hash of the concatenation of word + str(seed). `min_count` = ignore all words with total frequency lower than this. `max_vocab_size` = limit RAM during vocabulary building; if there are more unique words than this, then prune the infrequent ones. Every 10 million word types need about 1GB of RAM. Set to `None` for no limit (default). `sample` = threshold for configuring which higher-frequency words are randomly downsampled; default is 0 (off), useful value is 1e-5. `workers` = use this many worker threads to train the model (=faster training with multicore machines). `hs` = if 1 (default), hierarchical sampling will be used for model training (else set to 0). `negative` = if > 0, negative sampling will be used, the int for negative specifies how many "noise words" should be drawn (usually between 5-20). `cbow_mean` = if 0 (default), use the sum of the context word vectors. If 1, use the mean. Only applies when cbow is used. `hashfxn` = hash function to use to randomly initialize weights, for increased training reproducibility. Default is Python's rudimentary built in hash function. `iter` = number of iterations (epochs) over the corpus. """ self.vocab = {} # mapping from a word (string) to a Vocab object self.index2word = [] # map from a word's matrix index (int) to word (string) self.sg = int(sg) self.cum_table = None # for negative sampling self.vector_size = int(size) self.layer1_size = int(size) if size % 4 != 0: logger.warning("consider setting layer size to a multiple of 4 for greater performance") self.alpha = float(alpha) self.window = int(window) self.max_vocab_size = max_vocab_size self.seed = seed self.random = random.RandomState(seed) self.min_count = min_count self.sample = sample self.workers = workers self.min_alpha = min_alpha self.hs = hs self.negative = negative self.cbow_mean = int(cbow_mean) self.hashfxn = hashfxn self.iter = iter self.null_word = null_word self.train_count = 0 self.total_train_time = 0 if sentences is not None: if isinstance(sentences, GeneratorType): raise TypeError("You can't pass a generator as the sentences argument. Try an iterator.") self.build_vocab(sentences) self.train(sentences) def make_cum_table(self, power=0.75, domain=2**31 - 1): """ Create a cumulative-distribution table using stored vocabulary word counts for drawing random words in the negative-sampling training routines. To draw a word index, choose a random integer up to the maximum value in the table (cum_table[-1]), then finding that integer's sorted insertion point (as if by bisect_left or ndarray.searchsorted()). That insertion point is the drawn index, coming up in proportion equal to the increment at that slot. Called internally from 'build_vocab()'. """ vocab_size = len(self.index2word) self.cum_table = zeros(vocab_size, dtype=uint32) # compute sum of all power (Z in paper) train_words_pow = float(sum([self.vocab[word].count**power for word in self.vocab])) cumulative = 0.0 for word_index in range(vocab_size): cumulative += self.vocab[self.index2word[word_index]].count**power / train_words_pow self.cum_table[word_index] = round(cumulative * domain) if len(self.cum_table) > 0: assert self.cum_table[-1] == domain def create_binary_tree(self): """ Create a binary Huffman tree using stored vocabulary word counts. Frequent words will have shorter binary codes. Called internally from `build_vocab()`. """ logger.info("constructing a huffman tree from %i words", len(self.vocab)) # build the huffman tree heap = list(itervalues(self.vocab)) heapq.heapify(heap) for i in xrange(len(self.vocab) - 1): min1, min2 = heapq.heappop(heap), heapq.heappop(heap) heapq.heappush(heap, Vocab(count=min1.count + min2.count, index=i + len(self.vocab), left=min1, right=min2)) # recurse over the tree, assigning a binary code to each vocabulary word if heap: max_depth, stack = 0, [(heap[0], [], [])] while stack: node, codes, points = stack.pop() if node.index < len(self.vocab): # leaf node => store its path from the root node.code, node.point = codes, points max_depth = max(len(codes), max_depth) else: # inner node => continue recursion points = array(list(points) + [node.index - len(self.vocab)], dtype=uint32) stack.append((node.left, array(list(codes) + [0], dtype=uint8), points)) stack.append((node.right, array(list(codes) + [1], dtype=uint8), points)) logger.info("built huffman tree with maximum node depth %i", max_depth) def build_vocab(self, sentences, keep_raw_vocab=False): """ Build vocabulary from a sequence of sentences (can be a once-only generator stream). Each sentence must be a list of unicode strings. """ self.scan_vocab(sentences) # initial survey self.scale_vocab(keep_raw_vocab) # trim by min_count & precalculate downsampling self.finalize_vocab() # build tables & arrays def scan_vocab(self, sentences, progress_per=10000): """Do an initial scan of all words appearing in sentences.""" logger.info("collecting all words and their counts") sentence_no = -1 total_words = 0 min_reduce = 1 vocab = defaultdict(int) for sentence_no, sentence in enumerate(sentences): if sentence_no % progress_per == 0: logger.info("PROGRESS: at sentence #%i, processed %i words, keeping %i word types", sentence_no, sum(itervalues(vocab)) + total_words, len(vocab)) for word in sentence: vocab[word] += 1 if self.max_vocab_size and len(vocab) > self.max_vocab_size: total_words += utils.prune_vocab(vocab, min_reduce) min_reduce += 1 total_words += sum(itervalues(vocab)) logger.info("collected %i word types from a corpus of %i raw words and %i sentences", len(vocab), total_words, sentence_no + 1) self.corpus_count = sentence_no + 1 self.raw_vocab = vocab def scale_vocab(self, min_count=None, sample=None, dry_run=False, keep_raw_vocab=False): """ Apply vocabulary settings for `min_count` (discarding less-frequent words) and `sample` (controlling the downsampling of more-frequent words). Calling with `dry_run=True` will only simulate the provided settings and report the size of the retained vocabulary, effective corpus length, and estimated memory requirements. Results are both printed via logging and returned as a dict. Delete the raw vocabulary after the scaling is done to free up RAM, unless `keep_raw_vocab` is set. """ min_count = min_count or self.min_count sample = sample or self.sample # Discard words less-frequent than min_count if not dry_run: self.index2word = [] # make stored settings match these applied settings self.min_count = min_count self.sample = sample self.vocab = {} drop_unique, drop_total, retain_total, original_total = 0, 0, 0, 0 retain_words = [] for word, v in iteritems(self.raw_vocab): if v >= min_count: retain_words.append(word) retain_total += v original_total += v if not dry_run: self.vocab[word] = Vocab(count=v, index=len(self.index2word)) self.index2word.append(word) else: drop_unique += 1 drop_total += v original_total += v logger.info("min_count=%d retains %i unique words (drops %i)", min_count, len(retain_words), drop_unique) logger.info("min_count leaves %i word corpus (%i%% of original %i)", retain_total, retain_total * 100 / max(original_total, 1), original_total) # Precalculate each vocabulary item's threshold for sampling if not sample: # no words downsampled threshold_count = retain_total elif sample < 1.0: # traditional meaning: set parameter as proportion of total threshold_count = sample * retain_total else: # new shorthand: sample >= 1 means downsample all words with higher count than sample threshold_count = int(sample * (3 + sqrt(5)) / 2) downsample_total, downsample_unique = 0, 0 for w in retain_words: v = self.raw_vocab[w] word_probability = (sqrt(v / threshold_count) + 1) * (threshold_count / v) if word_probability < 1.0: downsample_unique += 1 downsample_total += word_probability * v else: word_probability = 1.0 downsample_total += v if not dry_run: self.vocab[w].sample_int = int(round(word_probability * 2**32)) if not dry_run and not keep_raw_vocab: logger.info("deleting the raw counts dictionary of %i items", len(self.raw_vocab)) self.raw_vocab = defaultdict(int) logger.info("sample=%g downsamples %i most-common words", sample, downsample_unique) logger.info("downsampling leaves estimated %i word corpus (%.1f%% of prior %i)", downsample_total, downsample_total * 100.0 / max(retain_total, 1), retain_total) # return from each step: words-affected, resulting-corpus-size report_values = {'drop_unique': drop_unique, 'retain_total': retain_total, 'downsample_unique': downsample_unique, 'downsample_total': int(downsample_total)} # print extra memory estimates report_values['memory'] = self.estimate_memory(vocab_size=len(retain_words)) return report_values def finalize_vocab(self): """Build tables and model weights based on final vocabulary settings.""" if not self.index2word: self.scale_vocab() if self.hs: # add info about each word's Huffman encoding self.create_binary_tree() if self.negative: # build the table for drawing random words (for negative sampling) self.make_cum_table() if self.null_word: # create null pseudo-word for padding when using concatenative L1 (run-of-words) # this word is only ever input – never predicted – so count, huffman-point, etc doesn't matter word, v = '\0', Vocab(count=1, sample_int=0) v.index = len(self.vocab) self.index2word.append(word) self.vocab[word] = v # set initial input/projection and hidden weights self.reset_weights() def reset_from(self, other_model): """ Borrow shareable pre-built structures (like vocab) from the other_model. Useful if testing multiple models in parallel on the same corpus. """ self.vocab = other_model.vocab self.index2word = other_model.index2word self.cum_table = other_model.cum_table self.corpus_count = other_model.corpus_count self.reset_weights() def _do_train_job(self, job, alpha, inits): work, neu1 = inits tally = 0 raw_tally = 0 for sentence in job: if self.sg: tally += train_sentence_sg(self, sentence, alpha, work) else: tally += train_sentence_cbow(self, sentence, alpha, work, neu1) raw_tally += len(sentence) return (tally, raw_tally) def _raw_word_count(self, items): return sum(len(item) for item in items) def train(self, sentences, total_words=None, word_count=0, chunksize=100, total_examples=None, queue_factor=2, report_delay=1): """ Update the model's neural weights from a sequence of sentences (can be a once-only generator stream). For Word2Vec, each sentence must be a list of unicode strings. (Subclasses may accept other examples.) To support linear learning-rate decay from (initial) alpha to min_alpha, either total_examples (count of sentences) or total_words (count of raw words in sentences) should be provided, unless the sentences are the same as those that were used to initially build the vocabulary. """ if FAST_VERSION < 0: import warnings warnings.warn("C extension not loaded for Word2Vec, training will be slow. " "Install a C compiler and reinstall gensim for fast training.") self.neg_labels = [] if self.negative > 0: # precompute negative labels optimization for pure-python training self.neg_labels = zeros(self.negative + 1) self.neg_labels[0] = 1. logger.info( "training model with %i workers on %i vocabulary and %i features, " "using sg=%s hs=%s sample=%s and negative=%s", self.workers, len(self.vocab), self.layer1_size, self.sg, self.hs, self.sample, self.negative) if not self.vocab: raise RuntimeError("you must first build vocabulary before training the model") if not hasattr(self, 'syn0'): raise RuntimeError("you must first finalize vocabulary before training the model") if total_words is None and total_examples is None: if self.corpus_count: total_examples = self.corpus_count logger.info("expecting %i examples, matching count from corpus used for vocabulary survey", total_examples) else: raise ValueError("you must provide either total_words or total_examples, to enable alpha and progress calculations") if self.iter > 1: sentences = utils.RepeatCorpusNTimes(sentences, self.iter) total_words = total_words and total_words * self.iter total_examples = total_examples and total_examples * self.iter def worker_init(): work = matutils.zeros_aligned(self.layer1_size, dtype=REAL) # per-thread private work memory neu1 = matutils.zeros_aligned(self.layer1_size, dtype=REAL) return (work, neu1) def worker_one_job(job, inits): items, alpha = job if items is None: # signal to finish return False # train & return tally tally, raw_tally = self._do_train_job(items, alpha, inits) progress_queue.put((len(items), tally, raw_tally)) # report progress return True def worker_loop(): """Train the model, lifting lists of sentences from the jobs queue.""" init = worker_init() while True: job = job_queue.get() if not worker_one_job(job, init): break start, next_report = default_timer(), 1.0 # buffer ahead only a limited number of jobs.. this is the reason we can't simply use ThreadPool :( if self.workers > 0: job_queue = Queue(maxsize=queue_factor * self.workers) else: job_queue = FakeJobQueue(worker_init, worker_one_job) progress_queue = Queue(maxsize=(queue_factor + 1) * self.workers) workers = [threading.Thread(target=worker_loop) for _ in xrange(self.workers)] for thread in workers: thread.daemon = True # make interrupting the process with ctrl+c easier thread.start() pushed_words = 0 pushed_examples = 0 example_count = 0 trained_word_count = 0 raw_word_count = word_count push_done = False done_jobs = 0 next_alpha = self.alpha jobs_source = enumerate(utils.grouper(sentences, chunksize)) # fill jobs queue with (sentence, alpha) job tuples while True: try: job_no, items = next(jobs_source) logger.debug("putting job #%i in the queue at alpha %.05f", job_no, next_alpha) job_queue.put((items, next_alpha)) # update the learning rate before every next job if self.min_alpha < next_alpha: if total_examples: # examples-based decay pushed_examples += len(items) next_alpha = self.alpha - (self.alpha - self.min_alpha) * (pushed_examples / total_examples) else: # words-based decay pushed_words += self._raw_word_count(items) next_alpha = self.alpha - (self.alpha - self.min_alpha) * (pushed_words / total_words) next_alpha = max(next_alpha, self.min_alpha) except StopIteration: logger.info( "reached end of input; waiting to finish %i outstanding jobs", job_no - done_jobs + 1) for _ in xrange(self.workers): job_queue.put((None, 0)) # give the workers heads up that they can finish -- no more work! push_done = True try: while done_jobs < (job_no+1) or not push_done: examples, trained_words, raw_words = progress_queue.get(push_done) # only block after all jobs pushed example_count += examples trained_word_count += trained_words # only words in vocab & sampled raw_word_count += raw_words done_jobs += 1 elapsed = default_timer() - start if elapsed >= next_report: if total_examples: # examples-based progress % logger.info( "PROGRESS: at %.2f%% examples, %.0f words/s", 100.0 * example_count / total_examples, trained_word_count / elapsed) else: # words-based progress % logger.info( "PROGRESS: at %.2f%% words, %.0f words/s", 100.0 * raw_word_count / total_words, trained_word_count / elapsed) next_report = elapsed + report_delay # don't flood log, wait report_delay seconds else: # loop ended by job count; really done break except Empty: pass # already out of loop; continue to next push elapsed = default_timer() - start logger.info( "training on %i raw words took %.1fs, %.0f trained words/s", raw_word_count, elapsed, trained_word_count / elapsed if elapsed else 0.0) if total_examples and total_examples != example_count: logger.warn("supplied example count (%i) did not equal expected count (%i)", example_count, total_examples) if total_words and total_words != raw_word_count: logger.warn("supplied raw word count (%i) did not equal expected count (%i)", raw_word_count, total_words) self.train_count += 1 # number of times train() has been called self.total_train_time += elapsed self.clear_sims() return trained_word_count def _score_job_words(self, sentence, inits): work, neu1 = inits if self.sg: return score_sentence_sg(self, sentence, work) else: return score_sentence_cbow(self, sentence, work, neu1) # basics copied from the train() function def score(self, sentences, total_sentences=int(1e9), chunksize=100, queue_factor=2, report_delay=1): """ Score the log probability for a sequence of sentences (can be a once-only generator stream). Each sentence must be a list of unicode strings. This does not change the fitted model in any way (see Word2Vec.train() for that) Note that you should specify total_sentences; we'll run into problems if you ask to score more than the default See the article by Taddy [taddy]_ for examples of how to use such scores in document classification. .. [taddy] Taddy, Matt. Document Classification by Inversion of Distributed Language Representations, in Proceedings of the 2015 Conference of the Association of Computational Linguistics. """ if FAST_VERSION < 0: import warnings warnings.warn("C extension compilation failed, scoring will be slow. " "Install a C compiler and reinstall gensim for fastness.") logger.info( "scoring sentences with %i workers on %i vocabulary and %i features, " "using sg=%s hs=%s sample=%s and negative=%s", self.workers, len(self.vocab), self.layer1_size, self.sg, self.hs, self.sample, self.negative) if not self.vocab: raise RuntimeError("you must first build vocabulary before scoring new data") if not self.hs: raise RuntimeError("we have only implemented score for hs") def worker_init(): work = zeros(1, dtype=REAL) # for sg hs, we actually only need one memory loc (running sum) neu1 = matutils.zeros_aligned(self.layer1_size, dtype=REAL) return (work, neu1) def worker_one_job(job, inits): if job is None: # signal to finish return False ns = 0 for (id, sentence) in job: sentence_scores[id] = self._score_job_words(sentence, inits) ns += 1 progress_queue.put(ns) # report progress return True def worker_loop(): """Train the model, lifting lists of sentences from the jobs queue.""" init = worker_init() while True: job = job_queue.get() if not worker_one_job(job, init): break start, next_report = default_timer(), 1.0 # buffer ahead only a limited number of jobs.. this is the reason we can't simply use ThreadPool :( if self.workers > 0: job_queue = Queue(maxsize=queue_factor * self.workers) else: job_queue = FakeJobQueue(worker_init, worker_one_job) progress_queue = Queue(maxsize=(queue_factor + 1) * self.workers) workers = [threading.Thread(target=worker_loop) for _ in xrange(self.workers)] for thread in workers: thread.daemon = True # make interrupting the process with ctrl+c easier thread.start() sentence_count = 0 sentence_scores = matutils.zeros_aligned(total_sentences, dtype=REAL) push_done = False done_jobs = 0 jobs_source = enumerate(utils.grouper(enumerate(sentences), chunksize)) # fill jobs queue with (id, sentence) job items while True: try: job_no, items = next(jobs_source) logger.debug("putting job #%i in the queue", job_no) job_queue.put(items) except StopIteration: logger.info( "reached end of input; waiting to finish %i outstanding jobs", job_no - done_jobs + 1) for _ in xrange(self.workers): job_queue.put(None) # give the workers heads up that they can finish -- no more work! push_done = True try: while done_jobs < (job_no+1) or not push_done: ns = progress_queue.get(push_done) # only block after all jobs pushed sentence_count += ns done_jobs += 1 elapsed = default_timer() - start if elapsed >= next_report: logger.info( "PROGRESS: at %.2f%% sentences, %.0f sentences/s", 100.0 * sentence_count, sentence_count / elapsed) next_report = elapsed + report_delay # don't flood log, wait report_delay seconds else: # loop ended by job count; really done break except Empty: pass # already out of loop; continue to next push elapsed = default_timer() - start self.clear_sims() logger.info("scoring %i sentences took %.1fs, %.0f sentences/s" % (sentence_count, elapsed, sentence_count / elapsed if elapsed else 0.0)) return sentence_scores[:sentence_count] def clear_sims(self): self.syn0norm = None def reset_weights(self): """Reset all projection weights to an initial (untrained) state, but keep the existing vocabulary.""" logger.info("resetting layer weights") self.syn0 = empty((len(self.vocab), self.vector_size), dtype=REAL) # randomize weights vector by vector, rather than materializing a huge random matrix in RAM at once for i in xrange(len(self.vocab)): # construct deterministic seed from word AND seed argument self.syn0[i] = self.seeded_vector(self.index2word[i] + str(self.seed)) if self.hs: self.syn1 = zeros((len(self.vocab), self.layer1_size), dtype=REAL) if self.negative: self.syn1neg = zeros((len(self.vocab), self.layer1_size), dtype=REAL) self.syn0norm = None self.syn0_lockf = ones(len(self.vocab), dtype=REAL) # zeros suppress learning def seeded_vector(self, seed_string): """Create one 'random' vector (but deterministic by seed_string)""" # Note: built-in hash() may vary by Python version or even (in Py3.x) per launch once = random.RandomState(uint32(self.hashfxn(seed_string))) return (once.rand(self.vector_size) - 0.5) / self.vector_size def save_word2vec_format(self, fname, fvocab=None, binary=False): """ Store the input-hidden weight matrix in the same format used by the original C word2vec-tool, for compatibility. """ if fvocab is not None: logger.info("Storing vocabulary in %s" % (fvocab)) with utils.smart_open(fvocab, 'wb') as vout: for word, vocab in sorted(iteritems(self.vocab), key=lambda item: -item[1].count): vout.write(utils.to_utf8("%s %s\n" % (word, vocab.count))) logger.info("storing %sx%s projection weights into %s" % (len(self.vocab), self.vector_size, fname)) assert (len(self.vocab), self.vector_size) == self.syn0.shape with utils.smart_open(fname, 'wb') as fout: fout.write(utils.to_utf8("%s %s\n" % self.syn0.shape)) # store in sorted order: most frequent words at the top for word, vocab in sorted(iteritems(self.vocab), key=lambda item: -item[1].count): row = self.syn0[vocab.index] if binary: fout.write(utils.to_utf8(word) + b" " + row.tostring()) else: fout.write(utils.to_utf8("%s %s\n" % (word, ' '.join("%f" % val for val in row)))) @classmethod def load_word2vec_format(cls, fname, fvocab=None, binary=False, norm_only=True, encoding='utf8'): """ Load the input-hidden weight matrix from the original C word2vec-tool format. Note that the information stored in the file is incomplete (the binary tree is missing), so while you can query for word similarity etc., you cannot continue training with a model loaded this way. `binary` is a boolean indicating whether the data is in binary word2vec format. `norm_only` is a boolean indicating whether to only store normalised word2vec vectors in memory. Word counts are read from `fvocab` filename, if set (this is the file generated by `-save-vocab` flag of the original C tool). If you trained the C model using non-utf8 encoding for words, specify that encoding in `encoding`. """ counts = None if fvocab is not None: logger.info("loading word counts from %s" % (fvocab)) counts = {} with utils.smart_open(fvocab) as fin: for line in fin: word, count = utils.to_unicode(line).strip().split() counts[word] = int(count) logger.info("loading projection weights from %s" % (fname)) with utils.smart_open(fname) as fin: header = utils.to_unicode(fin.readline(), encoding=encoding) vocab_size, vector_size = map(int, header.split()) # throws for invalid file format result = Word2Vec(size=vector_size) result.syn0 = zeros((vocab_size, vector_size), dtype=REAL) if binary: binary_len = dtype(REAL).itemsize * vector_size for line_no in xrange(vocab_size): # mixed text and binary: read text first, then binary word = [] while True: ch = fin.read(1) if ch == b' ': break if ch != b'\n': # ignore newlines in front of words (some binary files have) word.append(ch) word = utils.to_unicode(b''.join(word), encoding=encoding) if counts is None: result.vocab[word] = Vocab(index=line_no, count=vocab_size - line_no) elif word in counts: result.vocab[word] = Vocab(index=line_no, count=counts[word]) else: logger.warning("vocabulary file is incomplete") result.vocab[word] = Vocab(index=line_no, count=None) result.index2word.append(word) result.syn0[line_no] = fromstring(fin.read(binary_len), dtype=REAL) else: for line_no, line in enumerate(fin): parts = utils.to_unicode(line.rstrip(), encoding=encoding).split(" ") if len(parts) != vector_size + 1: raise ValueError("invalid vector on line %s (is this really the text format?)" % (line_no)) word, weights = parts[0], list(map(REAL, parts[1:])) if counts is None: result.vocab[word] = Vocab(index=line_no, count=vocab_size - line_no) elif word in counts: result.vocab[word] = Vocab(index=line_no, count=counts[word]) else: logger.warning("vocabulary file is incomplete") result.vocab[word] = Vocab(index=line_no, count=None) result.index2word.append(word) result.syn0[line_no] = weights logger.info("loaded %s matrix from %s" % (result.syn0.shape, fname)) result.init_sims(norm_only) return result def intersect_word2vec_format(self, fname, binary=False, encoding='utf8'): """ Merge the input-hidden weight matrix from the original C word2vec-tool format given, where it intersects with the current vocabulary. (No words are added to the existing vocabulary, but intersecting words adopt the file's weights, and non-intersecting words are left alone.) `binary` is a boolean indicating whether the data is in binary word2vec format. """ overlap_count = 0 logger.info("loading projection weights from %s" % (fname)) with utils.smart_open(fname) as fin: header = utils.to_unicode(fin.readline(), encoding=encoding) vocab_size, vector_size = map(int, header.split()) # throws for invalid file format if not vector_size == self.vector_size: raise ValueError("incompatible vector size %d in file %s" % (vector_size, fname)) # TOCONSIDER: maybe mismatched vectors still useful enough to merge (truncating/padding)? if binary: binary_len = dtype(REAL).itemsize * vector_size for line_no in xrange(vocab_size): # mixed text and binary: read text first, then binary word = [] while True: ch = fin.read(1) if ch == b' ': break if ch != b'\n': # ignore newlines in front of words (some binary files have) word.append(ch) word = utils.to_unicode(b''.join(word), encoding=encoding) weights = fromstring(fin.read(binary_len), dtype=REAL) if word in self.vocab: overlap_count += 1 self.syn0[self.vocab[word].index] = weights self.syn0_lockf[self.vocab[word].index] = 0.0 # lock it else: for line_no, line in enumerate(fin): parts = utils.to_unicode(line.rstrip(), encoding=encoding).split(" ") if len(parts) != vector_size + 1: raise ValueError("invalid vector on line %s (is this really the text format?)" % (line_no)) word, weights = parts[0], list(map(REAL, parts[1:])) if word in self.vocab: overlap_count += 1 self.syn0[self.vocab[word].index] = weights logger.info("merged %d vectors into %s matrix from %s" % (overlap_count, self.syn0.shape, fname)) def most_similar(self, positive=[], negative=[], topn=10): """ Find the top-N most similar words. Positive words contribute positively towards the similarity, negative words negatively. This method computes cosine similarity between a simple mean of the projection weight vectors of the given words and the vectors for each word in the model. The method corresponds to the `word-analogy` and `distance` scripts in the original word2vec implementation. If topn is False, most_similar returns the vector of similarity scores. Example:: >>> trained_model.most_similar(positive=['woman', 'king'], negative=['man']) [('queen', 0.50882536), ...] """ self.init_sims() if isinstance(positive, string_types) and not negative: # allow calls like most_similar('dog'), as a shorthand for most_similar(['dog']) positive = [positive] # add weights for each word, if not already present; default to 1.0 for positive and -1.0 for negative words positive = [ (word, 1.0) if isinstance(word, string_types + (ndarray,)) else word for word in positive ] negative = [ (word, -1.0) if isinstance(word, string_types + (ndarray,)) else word for word in negative ] # compute the weighted average of all words all_words, mean = set(), [] for word, weight in positive + negative: if isinstance(word, ndarray): mean.append(weight * word) elif word in self.vocab: mean.append(weight * self.syn0norm[self.vocab[word].index]) all_words.add(self.vocab[word].index) else: raise KeyError("word '%s' not in vocabulary" % word) if not mean: raise ValueError("cannot compute similarity with no input") mean = matutils.unitvec(array(mean).mean(axis=0)).astype(REAL) dists = dot(self.syn0norm, mean) if not topn: return dists best = matutils.argsort(dists, topn=topn + len(all_words), reverse=True) # ignore (don't return) words from the input result = [(self.index2word[sim], float(dists[sim])) for sim in best if sim not in all_words] return result[:topn] def most_similar_cosmul(self, positive=[], negative=[], topn=10): """ Find the top-N most similar words, using the multiplicative combination objective proposed by Omer Levy and Yoav Goldberg in [4]_. Positive words still contribute positively towards the similarity, negative words negatively, but with less susceptibility to one large distance dominating the calculation. In the common analogy-solving case, of two positive and one negative examples, this method is equivalent to the "3CosMul" objective (equation (4)) of Levy and Goldberg. Additional positive or negative examples contribute to the numerator or denominator, respectively – a potentially sensible but untested extension of the method. (With a single positive example, rankings will be the same as in the default most_similar.) Example:: >>> trained_model.most_similar_cosmul(positive=['baghdad', 'england'], negative=['london']) [(u'iraq', 0.8488819003105164), ...] .. [4] Omer Levy and Yoav Goldberg. Linguistic Regularities in Sparse and Explicit Word Representations, 2014. """ self.init_sims() if isinstance(positive, string_types) and not negative: # allow calls like most_similar_cosmul('dog'), as a shorthand for most_similar_cosmul(['dog']) positive = [positive] all_words = set() def word_vec(word): if isinstance(word, ndarray): return word elif word in self.vocab: all_words.add(self.vocab[word].index) return self.syn0norm[self.vocab[word].index] else: raise KeyError("word '%s' not in vocabulary" % word) positive = [word_vec(word) for word in positive] negative = [word_vec(word) for word in negative] if not positive: raise ValueError("cannot compute similarity with no input") # equation (4) of Levy & Goldberg "Linguistic Regularities...", # with distances shifted to [0,1] per footnote (7) pos_dists = [((1 + dot(self.syn0norm, term)) / 2) for term in positive] neg_dists = [((1 + dot(self.syn0norm, term)) / 2) for term in negative] dists = prod(pos_dists, axis=0) / (prod(neg_dists, axis=0) + 0.000001) if not topn: return dists best = matutils.argsort(dists, topn=topn + len(all_words), reverse=True) # ignore (don't return) words from the input result = [(self.index2word[sim], float(dists[sim])) for sim in best if sim not in all_words] return result[:topn] def doesnt_match(self, words): """ Which word from the given list doesn't go with the others? Example:: >>> trained_model.doesnt_match("breakfast cereal dinner lunch".split()) 'cereal' """ self.init_sims() words = [word for word in words if word in self.vocab] # filter out OOV words logger.debug("using words %s" % words) if not words: raise ValueError("cannot select a word from an empty list") vectors = vstack(self.syn0norm[self.vocab[word].index] for word in words).astype(REAL) mean = matutils.unitvec(vectors.mean(axis=0)).astype(REAL) dists = dot(vectors, mean) return sorted(zip(dists, words))[0][1] def __getitem__(self, words): """ Accept a single word or a list of words as input. If a single word: returns the word's representations in vector space, as a 1D numpy array. Multiple words: return the words' representations in vector space, as a 2d numpy array: #words x #vector_size. Matrix rows are in the same order as in input. Example:: >>> trained_model['office'] array([ -1.40128313e-02, ...]) >>> trained_model[['office', 'products']] array([ -1.40128313e-02, ...] [ -1.70425311e-03, ...] ...) """ if isinstance(words, string_types): # allow calls like trained_model['office'], as a shorthand for trained_model[['office']] return self.syn0[self.vocab[words].index] return vstack([self.syn0[self.vocab[word].index] for word in words]) def __contains__(self, word): return word in self.vocab def similarity(self, w1, w2): """ Compute cosine similarity between two words. Example:: >>> trained_model.similarity('woman', 'man') 0.73723527 >>> trained_model.similarity('woman', 'woman') 1.0 """ return dot(matutils.unitvec(self[w1]), matutils.unitvec(self[w2])) def n_similarity(self, ws1, ws2): """ Compute cosine similarity between two sets of words. Example:: >>> trained_model.n_similarity(['sushi', 'shop'], ['japanese', 'restaurant']) 0.61540466561049689 >>> trained_model.n_similarity(['restaurant', 'japanese'], ['japanese', 'restaurant']) 1.0000000000000004 >>> trained_model.n_similarity(['sushi'], ['restaurant']) == trained_model.similarity('sushi', 'restaurant') True """ v1 = [self[word] for word in ws1] v2 = [self[word] for word in ws2] return dot(matutils.unitvec(array(v1).mean(axis=0)), matutils.unitvec(array(v2).mean(axis=0))) def init_sims(self, replace=False): """ Precompute L2-normalized vectors. If `replace` is set, forget the original vectors and only keep the normalized ones = saves lots of memory! Note that you **cannot continue training** after doing a replace. The model becomes effectively read-only = you can call `most_similar`, `similarity` etc., but not `train`. """ if getattr(self, 'syn0norm', None) is None or replace: logger.info("precomputing L2-norms of word weight vectors") if replace: for i in xrange(self.syn0.shape[0]): self.syn0[i, :] /= sqrt((self.syn0[i, :] ** 2).sum(-1)) self.syn0norm = self.syn0 if hasattr(self, 'syn1'): del self.syn1 else: self.syn0norm = (self.syn0 / sqrt((self.syn0 ** 2).sum(-1))[..., newaxis]).astype(REAL) def estimate_memory(self, vocab_size=None, report=None): """Estimate required memory for a model using current settings and provided vocabulary size.""" vocab_size = vocab_size or len(self.vocab) report = report or {} report['vocab'] = vocab_size * (700 if self.hs else 500) report['syn0'] = vocab_size * self.vector_size * dtype(REAL).itemsize if self.hs: report['syn1'] = vocab_size * self.layer1_size * dtype(REAL).itemsize if self.negative: report['syn1neg'] = vocab_size * self.layer1_size * dtype(REAL).itemsize report['total'] = sum(report.values()) logger.info("estimated required memory for %i words and %i dimensions: %i bytes", vocab_size, self.vector_size, report['total']) return report @staticmethod def log_accuracy(section): correct, incorrect = len(section['correct']), len(section['incorrect']) if correct + incorrect > 0: logger.info("%s: %.1f%% (%i/%i)" % (section['section'], 100.0 * correct / (correct + incorrect), correct, correct + incorrect)) def accuracy(self, questions, restrict_vocab=30000, most_similar=most_similar): """ Compute accuracy of the model. `questions` is a filename where lines are 4-tuples of words, split into sections by ": SECTION NAME" lines. See https://code.google.com/p/word2vec/source/browse/trunk/questions-words.txt for an example. The accuracy is reported (=printed to log and returned as a list) for each section separately, plus there's one aggregate summary at the end. Use `restrict_vocab` to ignore all questions containing a word whose frequency is not in the top-N most frequent words (default top 30,000). This method corresponds to the `compute-accuracy` script of the original C word2vec. """ ok_vocab = dict(sorted(iteritems(self.vocab), key=lambda item: -item[1].count)[:restrict_vocab]) ok_index = set(v.index for v in itervalues(ok_vocab)) sections, section = [], None for line_no, line in enumerate(utils.smart_open(questions)): # TODO: use level3 BLAS (=evaluate multiple questions at once), for speed line = utils.to_unicode(line) if line.startswith(': '): # a new section starts => store the old section if section: sections.append(section) self.log_accuracy(section) section = {'section': line.lstrip(': ').strip(), 'correct': [], 'incorrect': []} else: if not section: raise ValueError("missing section header before line #%i in %s" % (line_no, questions)) try: a, b, c, expected = [word.lower() for word in line.split()] # TODO assumes vocabulary preprocessing uses lowercase, too... except: logger.info("skipping invalid line #%i in %s" % (line_no, questions)) if a not in ok_vocab or b not in ok_vocab or c not in ok_vocab or expected not in ok_vocab: logger.debug("skipping line #%i with OOV words: %s" % (line_no, line.strip())) continue ignore = set(self.vocab[v].index for v in [a, b, c]) # indexes of words to ignore predicted = None # find the most likely prediction, ignoring OOV words and input words sims = most_similar(self, positive=[b, c], negative=[a], topn=False) for index in matutils.argsort(sims, reverse=True): if index in ok_index and index not in ignore: predicted = self.index2word[index] if predicted != expected: logger.debug("%s: expected %s, predicted %s", line.strip(), expected, predicted) break if predicted == expected: section['correct'].append((a, b, c, expected)) else: section['incorrect'].append((a, b, c, expected)) if section: # store the last section, too sections.append(section) self.log_accuracy(section) total = { 'section': 'total', 'correct': sum((s['correct'] for s in sections), []), 'incorrect': sum((s['incorrect'] for s in sections), []), } self.log_accuracy(total) sections.append(total) return sections def __str__(self): return "%s(vocab=%s, size=%s, alpha=%s)" % (self.__class__.__name__, len(self.index2word), self.vector_size, self.alpha) def save(self, *args, **kwargs): # don't bother storing the cached normalized vectors, recalculable table kwargs['ignore'] = kwargs.get('ignore', ['syn0norm', 'table', 'cum_table']) super(Word2Vec, self).save(*args, **kwargs) save.__doc__ = utils.SaveLoad.save.__doc__ @classmethod def load(cls, *args, **kwargs): model = super(Word2Vec, cls).load(*args, **kwargs) # update older models if hasattr(model, 'table'): delattr(model, 'table') # discard in favor of cum_table if model.negative: model.make_cum_table() # rebuild cum_table from vocabulary if not hasattr(model, 'corpus_count'): model.corpus_count = None for v in model.vocab.values(): if hasattr(v, 'sample_int'): break # already 0.12.0+ style int probabilities else: v.sample_int = int(round(v.sample_probability * 2**32)) del v.sample_probability if not hasattr(model, 'syn0_lockf'): model.syn0_lockf = ones(len(model.syn0), dtype=REAL) if not hasattr(model, 'random'): model.random = random.RandomState(model.seed) if not hasattr(model, 'train_count'): model.train_count = 0 model.total_train_time = 0 return model class FakeJobQueue(object): """Pretends to be a Queue; does equivalent of work_loop in calling thread.""" def __init__(self, init_fn, job_fn): self.inits = init_fn() self.job_fn = job_fn def put(self, job): self.job_fn(job, self.inits) class BrownCorpus(object): """Iterate over sentences from the Brown corpus (part of NLTK data).""" def __init__(self, dirname): self.dirname = dirname def __iter__(self): for fname in os.listdir(self.dirname): fname = os.path.join(self.dirname, fname) if not os.path.isfile(fname): continue for line in utils.smart_open(fname): line = utils.to_unicode(line) # each file line is a single sentence in the Brown corpus # each token is WORD/POS_TAG token_tags = [t.split('/') for t in line.split() if len(t.split('/')) == 2] # ignore words with non-alphabetic tags like ",", "!" etc (punctuation, weird stuff) words = ["%s/%s" % (token.lower(), tag[:2]) for token, tag in token_tags if tag[:2].isalpha()] if not words: # don't bother sending out empty sentences continue yield words class Text8Corpus(object): """Iterate over sentences from the "text8" corpus, unzipped from http://mattmahoney.net/dc/text8.zip .""" def __init__(self, fname, max_sentence_length=1000): self.fname = fname self.max_sentence_length = max_sentence_length def __iter__(self): # the entire corpus is one gigantic line -- there are no sentence marks at all # so just split the sequence of tokens arbitrarily: 1 sentence = 1000 tokens sentence, rest = [], b'' with utils.smart_open(self.fname) as fin: while True: text = rest + fin.read(8192) # avoid loading the entire file (=1 line) into RAM if text == rest: # EOF sentence.extend(rest.split()) # return the last chunk of words, too (may be shorter/longer) if sentence: yield sentence break last_token = text.rfind(b' ') # last token may have been split in two... keep for next iteration words, rest = (utils.to_unicode(text[:last_token]).split(), text[last_token:].strip()) if last_token >= 0 else ([], text) sentence.extend(words) while len(sentence) >= self.max_sentence_length: yield sentence[:self.max_sentence_length] sentence = sentence[self.max_sentence_length:] class LineSentence(object): """Simple format: one sentence = one line; words already preprocessed and separated by whitespace.""" def __init__(self, source, max_sentence_length=10000): """ `source` can be either a string or a file object. Example:: sentences = LineSentence('myfile.txt') Or for compressed files:: sentences = LineSentence('compressed_text.txt.bz2') sentences = LineSentence('compressed_text.txt.gz') """ self.source = source self.max_sentence_length = max_sentence_length def __iter__(self): """Iterate through the lines in the source.""" try: # Assume it is a file-like object and try treating it as such # Things that don't have seek will trigger an exception self.source.seek(0) for line in self.source: line = utils.to_unicode(line).split() i = 0 while i < len(line): yield line[i:(i + self.max_sentence_length)] i += self.max_sentence_length except AttributeError: # If it didn't work like a file, use it as a string filename with utils.smart_open(self.source) as fin: for line in fin: line = utils.to_unicode(line).split() i = 0 while i < len(line): yield line[i:(i + self.max_sentence_length)] i += self.max_sentence_length # Example: ./word2vec.py ~/workspace/word2vec/text8 ~/workspace/word2vec/questions-words.txt ./text8 if __name__ == "__main__": logging.basicConfig( format='%(asctime)s : %(threadName)s : %(levelname)s : %(message)s', level=logging.INFO) logging.info("running %s", " ".join(sys.argv)) logging.info("using optimization %s", FAST_VERSION) # check and process cmdline input program = os.path.basename(sys.argv[0]) if len(sys.argv) < 2: print(globals()['__doc__'] % locals()) sys.exit(1) infile = sys.argv[1] from gensim.models.word2vec import Word2Vec # avoid referencing __main__ in pickle seterr(all='raise') # don't ignore numpy errors # model = Word2Vec(LineSentence(infile), size=200, min_count=5, workers=4) model = Word2Vec(Text8Corpus(infile), size=200, min_count=5, workers=1) if len(sys.argv) > 3: outfile = sys.argv[3] model.save(outfile + '.model') model.save_word2vec_format(outfile + '.model.bin', binary=True) model.save_word2vec_format(outfile + '.model.txt', binary=False) if len(sys.argv) > 2: questions_file = sys.argv[2] model.accuracy(sys.argv[2]) logging.info("finished running %s", program)
gpl-3.0
cloud9ers/gurumate
environment/lib/python2.7/site-packages/MySQL_python-1.2.4c1-py2.7-linux-x86_64.egg/_mysql_exceptions.py
99
2352
"""_mysql_exceptions: Exception classes for _mysql and MySQLdb. These classes are dictated by the DB API v2.0: http://www.python.org/topics/database/DatabaseAPI-2.0.html """ try: from exceptions import Exception, StandardError, Warning except ImportError: # Python 3 StandardError = Exception class MySQLError(StandardError): """Exception related to operation with MySQL.""" class Warning(Warning, MySQLError): """Exception raised for important warnings like data truncations while inserting, etc.""" class Error(MySQLError): """Exception that is the base class of all other error exceptions (not Warning).""" class InterfaceError(Error): """Exception raised for errors that are related to the database interface rather than the database itself.""" class DatabaseError(Error): """Exception raised for errors that are related to the database.""" class DataError(DatabaseError): """Exception raised for errors that are due to problems with the processed data like division by zero, numeric value out of range, etc.""" class OperationalError(DatabaseError): """Exception raised for errors that are related to the database's operation and not necessarily under the control of the programmer, e.g. an unexpected disconnect occurs, the data source name is not found, a transaction could not be processed, a memory allocation error occurred during processing, etc.""" class IntegrityError(DatabaseError): """Exception raised when the relational integrity of the database is affected, e.g. a foreign key check fails, duplicate key, etc.""" class InternalError(DatabaseError): """Exception raised when the database encounters an internal error, e.g. the cursor is not valid anymore, the transaction is out of sync, etc.""" class ProgrammingError(DatabaseError): """Exception raised for programming errors, e.g. table not found or already exists, syntax error in the SQL statement, wrong number of parameters specified, etc.""" class NotSupportedError(DatabaseError): """Exception raised in case a method or database API was used which is not supported by the database, e.g. requesting a .rollback() on a connection that does not support transaction or has transactions turned off."""
lgpl-3.0
BrainTech/openbci
obci/logic/experiment_builder/imbir/kamil_oddball/kamil_consts.py
1
1944
#name of a file with words in format: every column for one group RAW_WORDS_FILE='raw_words.csv' #to-be-created-every-time file with experiment words with rows: #group, word, fixation time WORDS_FILE='words.csv' #if true then it is assumed that there is word.csv file and itll be used USE_EXISTING_WORDS_FILE = False #how many repetitions of the experiment in a one session? #used to generate WORDS_FILE file REPS = 3 #dummy word for the experiment #used to generate WORDS_FILE file DUMMY_WORD='Drewno' #after every target word there will be N dummy wordse #where N is a random between 1 and DUMMY_WORD_MULT #used to generate WORDS_FILE file DUMMY_WORD_MULT= 6 #fixation min and max time (to be randomised) #used to generate WORDS_FILE file FIX_MIN = 0.5 FIX_MAX = 1.5 #every BLINK words blink instruction will occur BLINK_MIN = 10 BLINK_MAX = 15 # Which buttons are interpreted as emotional? 'color' property is to be used # in user`s instruction, eg. 'Hit Czerwony button for emotional words, hit Zielony button for non emotional words. # 'button' property is a button the user is to push. REMEMBER, place 'color' indicator on 'button' button on keyboard. # Eg. place Czerwony color on 'c' button. # WARNING - this property works only after running 'kamil_replace_consts.py' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! EMOTIONS = { 'color':'Czerwony', 'button':'c', 'color_rep':'COLOR_FOR_EMOTION', 'button_rep':'BUTTON_FOR_EMOTION', } NON_EMOTIONS = { 'color':'Zielony', 'button':'n', 'color_rep':'COLOR_FOR_NON_EMOTION', 'button_rep':'BUTTON_FOR_NON_EMOTION', } #true if send trigger USE_SERIAL = False #a value to be send to trigger on init SERIAL_INIT_VALUE = 1 #serial port name PORT_NAME = "COM1" #internal ************************ NUM_OF_VALS = 3 START_ST = 100 START_DUR = 1000 s_st = [0.0, 1.0, 1.0] s_dur = [1.0, 1.0, 2.0]
gpl-3.0
sam-tsai/django
django/contrib/gis/gdal/prototypes/ds.py
349
4403
""" This module houses the ctypes function prototypes for OGR DataSource related data structures. OGR_Dr_*, OGR_DS_*, OGR_L_*, OGR_F_*, OGR_Fld_* routines are relevant here. """ from ctypes import POINTER, c_char_p, c_double, c_int, c_long, c_void_p from django.contrib.gis.gdal.envelope import OGREnvelope from django.contrib.gis.gdal.libgdal import GDAL_VERSION, lgdal from django.contrib.gis.gdal.prototypes.generation import ( const_string_output, double_output, geom_output, int64_output, int_output, srs_output, void_output, voidptr_output, ) c_int_p = POINTER(c_int) # shortcut type # Driver Routines register_all = void_output(lgdal.OGRRegisterAll, [], errcheck=False) cleanup_all = void_output(lgdal.OGRCleanupAll, [], errcheck=False) get_driver = voidptr_output(lgdal.OGRGetDriver, [c_int]) get_driver_by_name = voidptr_output(lgdal.OGRGetDriverByName, [c_char_p], errcheck=False) get_driver_count = int_output(lgdal.OGRGetDriverCount, []) get_driver_name = const_string_output(lgdal.OGR_Dr_GetName, [c_void_p], decoding='ascii') # DataSource open_ds = voidptr_output(lgdal.OGROpen, [c_char_p, c_int, POINTER(c_void_p)]) destroy_ds = void_output(lgdal.OGR_DS_Destroy, [c_void_p], errcheck=False) release_ds = void_output(lgdal.OGRReleaseDataSource, [c_void_p]) get_ds_name = const_string_output(lgdal.OGR_DS_GetName, [c_void_p]) get_layer = voidptr_output(lgdal.OGR_DS_GetLayer, [c_void_p, c_int]) get_layer_by_name = voidptr_output(lgdal.OGR_DS_GetLayerByName, [c_void_p, c_char_p]) get_layer_count = int_output(lgdal.OGR_DS_GetLayerCount, [c_void_p]) # Layer Routines get_extent = void_output(lgdal.OGR_L_GetExtent, [c_void_p, POINTER(OGREnvelope), c_int]) get_feature = voidptr_output(lgdal.OGR_L_GetFeature, [c_void_p, c_long]) get_feature_count = int_output(lgdal.OGR_L_GetFeatureCount, [c_void_p, c_int]) get_layer_defn = voidptr_output(lgdal.OGR_L_GetLayerDefn, [c_void_p]) get_layer_srs = srs_output(lgdal.OGR_L_GetSpatialRef, [c_void_p]) get_next_feature = voidptr_output(lgdal.OGR_L_GetNextFeature, [c_void_p]) reset_reading = void_output(lgdal.OGR_L_ResetReading, [c_void_p], errcheck=False) test_capability = int_output(lgdal.OGR_L_TestCapability, [c_void_p, c_char_p]) get_spatial_filter = geom_output(lgdal.OGR_L_GetSpatialFilter, [c_void_p]) set_spatial_filter = void_output(lgdal.OGR_L_SetSpatialFilter, [c_void_p, c_void_p], errcheck=False) set_spatial_filter_rect = void_output(lgdal.OGR_L_SetSpatialFilterRect, [c_void_p, c_double, c_double, c_double, c_double], errcheck=False ) # Feature Definition Routines get_fd_geom_type = int_output(lgdal.OGR_FD_GetGeomType, [c_void_p]) get_fd_name = const_string_output(lgdal.OGR_FD_GetName, [c_void_p]) get_feat_name = const_string_output(lgdal.OGR_FD_GetName, [c_void_p]) get_field_count = int_output(lgdal.OGR_FD_GetFieldCount, [c_void_p]) get_field_defn = voidptr_output(lgdal.OGR_FD_GetFieldDefn, [c_void_p, c_int]) # Feature Routines clone_feature = voidptr_output(lgdal.OGR_F_Clone, [c_void_p]) destroy_feature = void_output(lgdal.OGR_F_Destroy, [c_void_p], errcheck=False) feature_equal = int_output(lgdal.OGR_F_Equal, [c_void_p, c_void_p]) get_feat_geom_ref = geom_output(lgdal.OGR_F_GetGeometryRef, [c_void_p]) get_feat_field_count = int_output(lgdal.OGR_F_GetFieldCount, [c_void_p]) get_feat_field_defn = voidptr_output(lgdal.OGR_F_GetFieldDefnRef, [c_void_p, c_int]) get_fid = int_output(lgdal.OGR_F_GetFID, [c_void_p]) get_field_as_datetime = int_output(lgdal.OGR_F_GetFieldAsDateTime, [c_void_p, c_int, c_int_p, c_int_p, c_int_p, c_int_p, c_int_p, c_int_p] ) get_field_as_double = double_output(lgdal.OGR_F_GetFieldAsDouble, [c_void_p, c_int]) get_field_as_integer = int_output(lgdal.OGR_F_GetFieldAsInteger, [c_void_p, c_int]) if GDAL_VERSION >= (2, 0): get_field_as_integer64 = int64_output(lgdal.OGR_F_GetFieldAsInteger64, [c_void_p, c_int]) get_field_as_string = const_string_output(lgdal.OGR_F_GetFieldAsString, [c_void_p, c_int]) get_field_index = int_output(lgdal.OGR_F_GetFieldIndex, [c_void_p, c_char_p]) # Field Routines get_field_name = const_string_output(lgdal.OGR_Fld_GetNameRef, [c_void_p]) get_field_precision = int_output(lgdal.OGR_Fld_GetPrecision, [c_void_p]) get_field_type = int_output(lgdal.OGR_Fld_GetType, [c_void_p]) get_field_type_name = const_string_output(lgdal.OGR_GetFieldTypeName, [c_int]) get_field_width = int_output(lgdal.OGR_Fld_GetWidth, [c_void_p])
bsd-3-clause
qenter/vlc-android
toolchains/arm/lib/python2.7/bsddb/test/test_dbenv.py
68
19274
import unittest import os, glob from test_all import db, test_support, get_new_environment_path, \ get_new_database_path #---------------------------------------------------------------------- class DBEnv(unittest.TestCase): def setUp(self): self.homeDir = get_new_environment_path() self.env = db.DBEnv() def tearDown(self): self.env.close() del self.env test_support.rmtree(self.homeDir) class DBEnv_general(DBEnv) : def test_get_open_flags(self) : flags = db.DB_CREATE | db.DB_INIT_MPOOL self.env.open(self.homeDir, flags) self.assertEqual(flags, self.env.get_open_flags()) def test_get_open_flags2(self) : flags = db.DB_CREATE | db.DB_INIT_MPOOL | \ db.DB_INIT_LOCK | db.DB_THREAD self.env.open(self.homeDir, flags) self.assertEqual(flags, self.env.get_open_flags()) if db.version() >= (4, 7) : def test_lk_partitions(self) : for i in [10, 20, 40] : self.env.set_lk_partitions(i) self.assertEqual(i, self.env.get_lk_partitions()) def test_getset_intermediate_dir_mode(self) : self.assertEqual(None, self.env.get_intermediate_dir_mode()) for mode in ["rwx------", "rw-rw-rw-", "rw-r--r--"] : self.env.set_intermediate_dir_mode(mode) self.assertEqual(mode, self.env.get_intermediate_dir_mode()) self.assertRaises(db.DBInvalidArgError, self.env.set_intermediate_dir_mode, "abcde") if db.version() >= (4, 6) : def test_thread(self) : for i in [16, 100, 1000] : self.env.set_thread_count(i) self.assertEqual(i, self.env.get_thread_count()) def test_cache_max(self) : for size in [64, 128] : size = size*1024*1024 # Megabytes self.env.set_cache_max(0, size) size2 = self.env.get_cache_max() self.assertEqual(0, size2[0]) self.assertTrue(size <= size2[1]) self.assertTrue(2*size > size2[1]) if db.version() >= (4, 4) : def test_mutex_stat(self) : self.env.open(self.homeDir, db.DB_CREATE | db.DB_INIT_MPOOL | db.DB_INIT_LOCK) stat = self.env.mutex_stat() self.assertTrue("mutex_inuse_max" in stat) def test_lg_filemode(self) : for i in [0600, 0660, 0666] : self.env.set_lg_filemode(i) self.assertEqual(i, self.env.get_lg_filemode()) def test_mp_max_openfd(self) : for i in [17, 31, 42] : self.env.set_mp_max_openfd(i) self.assertEqual(i, self.env.get_mp_max_openfd()) def test_mp_max_write(self) : for i in [100, 200, 300] : for j in [1, 2, 3] : j *= 1000000 self.env.set_mp_max_write(i, j) v=self.env.get_mp_max_write() self.assertEqual((i, j), v) def test_invalid_txn(self) : # This environment doesn't support transactions self.assertRaises(db.DBInvalidArgError, self.env.txn_begin) def test_mp_mmapsize(self) : for i in [16, 32, 64] : i *= 1024*1024 self.env.set_mp_mmapsize(i) self.assertEqual(i, self.env.get_mp_mmapsize()) def test_tmp_dir(self) : for i in ["a", "bb", "ccc"] : self.env.set_tmp_dir(i) self.assertEqual(i, self.env.get_tmp_dir()) def test_flags(self) : self.env.set_flags(db.DB_AUTO_COMMIT, 1) self.assertEqual(db.DB_AUTO_COMMIT, self.env.get_flags()) self.env.set_flags(db.DB_TXN_NOSYNC, 1) self.assertEqual(db.DB_AUTO_COMMIT | db.DB_TXN_NOSYNC, self.env.get_flags()) self.env.set_flags(db.DB_AUTO_COMMIT, 0) self.assertEqual(db.DB_TXN_NOSYNC, self.env.get_flags()) self.env.set_flags(db.DB_TXN_NOSYNC, 0) self.assertEqual(0, self.env.get_flags()) def test_lk_max_objects(self) : for i in [1000, 2000, 3000] : self.env.set_lk_max_objects(i) self.assertEqual(i, self.env.get_lk_max_objects()) def test_lk_max_locks(self) : for i in [1000, 2000, 3000] : self.env.set_lk_max_locks(i) self.assertEqual(i, self.env.get_lk_max_locks()) def test_lk_max_lockers(self) : for i in [1000, 2000, 3000] : self.env.set_lk_max_lockers(i) self.assertEqual(i, self.env.get_lk_max_lockers()) def test_lg_regionmax(self) : for i in [128, 256, 1000] : i = i*1024*1024 self.env.set_lg_regionmax(i) j = self.env.get_lg_regionmax() self.assertTrue(i <= j) self.assertTrue(2*i > j) def test_lk_detect(self) : flags= [db.DB_LOCK_DEFAULT, db.DB_LOCK_EXPIRE, db.DB_LOCK_MAXLOCKS, db.DB_LOCK_MINLOCKS, db.DB_LOCK_MINWRITE, db.DB_LOCK_OLDEST, db.DB_LOCK_RANDOM, db.DB_LOCK_YOUNGEST] flags.append(db.DB_LOCK_MAXWRITE) for i in flags : self.env.set_lk_detect(i) self.assertEqual(i, self.env.get_lk_detect()) def test_lg_dir(self) : for i in ["a", "bb", "ccc", "dddd"] : self.env.set_lg_dir(i) self.assertEqual(i, self.env.get_lg_dir()) def test_lg_bsize(self) : log_size = 70*1024 self.env.set_lg_bsize(log_size) self.assertTrue(self.env.get_lg_bsize() >= log_size) self.assertTrue(self.env.get_lg_bsize() < 4*log_size) self.env.set_lg_bsize(4*log_size) self.assertTrue(self.env.get_lg_bsize() >= 4*log_size) def test_setget_data_dirs(self) : dirs = ("a", "b", "c", "d") for i in dirs : self.env.set_data_dir(i) self.assertEqual(dirs, self.env.get_data_dirs()) def test_setget_cachesize(self) : cachesize = (0, 512*1024*1024, 3) self.env.set_cachesize(*cachesize) self.assertEqual(cachesize, self.env.get_cachesize()) cachesize = (0, 1*1024*1024, 5) self.env.set_cachesize(*cachesize) cachesize2 = self.env.get_cachesize() self.assertEqual(cachesize[0], cachesize2[0]) self.assertEqual(cachesize[2], cachesize2[2]) # Berkeley DB expands the cache 25% accounting overhead, # if the cache is small. self.assertEqual(125, int(100.0*cachesize2[1]/cachesize[1])) # You can not change configuration after opening # the environment. self.env.open(self.homeDir, db.DB_CREATE | db.DB_INIT_MPOOL) cachesize = (0, 2*1024*1024, 1) self.assertRaises(db.DBInvalidArgError, self.env.set_cachesize, *cachesize) cachesize3 = self.env.get_cachesize() self.assertEqual(cachesize2[0], cachesize3[0]) self.assertEqual(cachesize2[2], cachesize3[2]) # In Berkeley DB 5.1, the cachesize can change when opening the Env self.assertTrue(cachesize2[1] <= cachesize3[1]) def test_set_cachesize_dbenv_db(self) : # You can not configure the cachesize using # the database handle, if you are using an environment. d = db.DB(self.env) self.assertRaises(db.DBInvalidArgError, d.set_cachesize, 0, 1024*1024, 1) def test_setget_shm_key(self) : shm_key=137 self.env.set_shm_key(shm_key) self.assertEqual(shm_key, self.env.get_shm_key()) self.env.set_shm_key(shm_key+1) self.assertEqual(shm_key+1, self.env.get_shm_key()) # You can not change configuration after opening # the environment. self.env.open(self.homeDir, db.DB_CREATE | db.DB_INIT_MPOOL) # If we try to reconfigure cache after opening the # environment, core dump. self.assertRaises(db.DBInvalidArgError, self.env.set_shm_key, shm_key) self.assertEqual(shm_key+1, self.env.get_shm_key()) if db.version() >= (4, 4) : def test_mutex_setget_max(self) : v = self.env.mutex_get_max() v2 = v*2+1 self.env.mutex_set_max(v2) self.assertEqual(v2, self.env.mutex_get_max()) self.env.mutex_set_max(v) self.assertEqual(v, self.env.mutex_get_max()) # You can not change configuration after opening # the environment. self.env.open(self.homeDir, db.DB_CREATE) self.assertRaises(db.DBInvalidArgError, self.env.mutex_set_max, v2) def test_mutex_setget_increment(self) : v = self.env.mutex_get_increment() v2 = 127 self.env.mutex_set_increment(v2) self.assertEqual(v2, self.env.mutex_get_increment()) self.env.mutex_set_increment(v) self.assertEqual(v, self.env.mutex_get_increment()) # You can not change configuration after opening # the environment. self.env.open(self.homeDir, db.DB_CREATE) self.assertRaises(db.DBInvalidArgError, self.env.mutex_set_increment, v2) def test_mutex_setget_tas_spins(self) : self.env.mutex_set_tas_spins(0) # Default = BDB decides v = self.env.mutex_get_tas_spins() v2 = v*2+1 self.env.mutex_set_tas_spins(v2) self.assertEqual(v2, self.env.mutex_get_tas_spins()) self.env.mutex_set_tas_spins(v) self.assertEqual(v, self.env.mutex_get_tas_spins()) # In this case, you can change configuration # after opening the environment. self.env.open(self.homeDir, db.DB_CREATE) self.env.mutex_set_tas_spins(v2) def test_mutex_setget_align(self) : v = self.env.mutex_get_align() v2 = 64 if v == 64 : v2 = 128 self.env.mutex_set_align(v2) self.assertEqual(v2, self.env.mutex_get_align()) # Requires a nonzero power of two self.assertRaises(db.DBInvalidArgError, self.env.mutex_set_align, 0) self.assertRaises(db.DBInvalidArgError, self.env.mutex_set_align, 17) self.env.mutex_set_align(2*v2) self.assertEqual(2*v2, self.env.mutex_get_align()) # You can not change configuration after opening # the environment. self.env.open(self.homeDir, db.DB_CREATE) self.assertRaises(db.DBInvalidArgError, self.env.mutex_set_align, v2) class DBEnv_log(DBEnv) : def setUp(self): DBEnv.setUp(self) self.env.open(self.homeDir, db.DB_CREATE | db.DB_INIT_MPOOL | db.DB_INIT_LOG) def test_log_file(self) : log_file = self.env.log_file((1, 1)) self.assertEqual("log.0000000001", log_file[-14:]) if db.version() >= (4, 4) : # The version with transactions is checked in other test object def test_log_printf(self) : msg = "This is a test..." self.env.log_printf(msg) logc = self.env.log_cursor() self.assertTrue(msg in (logc.last()[1])) if db.version() >= (4, 7) : def test_log_config(self) : self.env.log_set_config(db.DB_LOG_DSYNC | db.DB_LOG_ZERO, 1) self.assertTrue(self.env.log_get_config(db.DB_LOG_DSYNC)) self.assertTrue(self.env.log_get_config(db.DB_LOG_ZERO)) self.env.log_set_config(db.DB_LOG_ZERO, 0) self.assertTrue(self.env.log_get_config(db.DB_LOG_DSYNC)) self.assertFalse(self.env.log_get_config(db.DB_LOG_ZERO)) class DBEnv_log_txn(DBEnv) : def setUp(self): DBEnv.setUp(self) self.env.open(self.homeDir, db.DB_CREATE | db.DB_INIT_MPOOL | db.DB_INIT_LOG | db.DB_INIT_TXN) if (db.version() >= (4, 5)) and (db.version() < (5, 2)) : def test_tx_max(self) : txns=[] def tx() : for i in xrange(self.env.get_tx_max()) : txns.append(self.env.txn_begin()) tx() self.assertRaises(MemoryError, tx) # Abort the transactions before garbage collection, # to avoid "warnings". for i in txns : i.abort() if db.version() >= (4, 4) : # The version without transactions is checked in other test object def test_log_printf(self) : msg = "This is a test..." txn = self.env.txn_begin() self.env.log_printf(msg, txn=txn) txn.commit() logc = self.env.log_cursor() logc.last() # Skip the commit self.assertTrue(msg in (logc.prev()[1])) msg = "This is another test..." txn = self.env.txn_begin() self.env.log_printf(msg, txn=txn) txn.abort() # Do not store the new message logc.last() # Skip the abort self.assertTrue(msg not in (logc.prev()[1])) msg = "This is a third test..." txn = self.env.txn_begin() self.env.log_printf(msg, txn=txn) txn.commit() # Do not store the new message logc.last() # Skip the commit self.assertTrue(msg in (logc.prev()[1])) class DBEnv_memp(DBEnv): def setUp(self): DBEnv.setUp(self) self.env.open(self.homeDir, db.DB_CREATE | db.DB_INIT_MPOOL | db.DB_INIT_LOG) self.db = db.DB(self.env) self.db.open("test", db.DB_HASH, db.DB_CREATE, 0660) def tearDown(self): self.db.close() del self.db DBEnv.tearDown(self) def test_memp_1_trickle(self) : self.db.put("hi", "bye") self.assertTrue(self.env.memp_trickle(100) > 0) # Preserve the order, do "memp_trickle" test first def test_memp_2_sync(self) : self.db.put("hi", "bye") self.env.memp_sync() # Full flush # Nothing to do... self.assertTrue(self.env.memp_trickle(100) == 0) self.db.put("hi", "bye2") self.env.memp_sync((1, 0)) # NOP, probably # Something to do... or not self.assertTrue(self.env.memp_trickle(100) >= 0) self.db.put("hi", "bye3") self.env.memp_sync((123, 99)) # Full flush # Nothing to do... self.assertTrue(self.env.memp_trickle(100) == 0) def test_memp_stat_1(self) : stats = self.env.memp_stat() # No param self.assertTrue(len(stats)==2) self.assertTrue("cache_miss" in stats[0]) stats = self.env.memp_stat(db.DB_STAT_CLEAR) # Positional param self.assertTrue("cache_miss" in stats[0]) stats = self.env.memp_stat(flags=0) # Keyword param self.assertTrue("cache_miss" in stats[0]) def test_memp_stat_2(self) : stats=self.env.memp_stat()[1] self.assertTrue(len(stats))==1 self.assertTrue("test" in stats) self.assertTrue("page_in" in stats["test"]) class DBEnv_logcursor(DBEnv): def setUp(self): DBEnv.setUp(self) self.env.open(self.homeDir, db.DB_CREATE | db.DB_INIT_MPOOL | db.DB_INIT_LOG | db.DB_INIT_TXN) txn = self.env.txn_begin() self.db = db.DB(self.env) self.db.open("test", db.DB_HASH, db.DB_CREATE, 0660, txn=txn) txn.commit() for i in ["2", "8", "20"] : txn = self.env.txn_begin() self.db.put(key = i, data = i*int(i), txn=txn) txn.commit() def tearDown(self): self.db.close() del self.db DBEnv.tearDown(self) def _check_return(self, value) : self.assertTrue(isinstance(value, tuple)) self.assertEqual(len(value), 2) self.assertTrue(isinstance(value[0], tuple)) self.assertEqual(len(value[0]), 2) self.assertTrue(isinstance(value[0][0], int)) self.assertTrue(isinstance(value[0][1], int)) self.assertTrue(isinstance(value[1], str)) # Preserve test order def test_1_first(self) : logc = self.env.log_cursor() v = logc.first() self._check_return(v) self.assertTrue((1, 1) < v[0]) self.assertTrue(len(v[1])>0) def test_2_last(self) : logc = self.env.log_cursor() lsn_first = logc.first()[0] v = logc.last() self._check_return(v) self.assertTrue(lsn_first < v[0]) def test_3_next(self) : logc = self.env.log_cursor() lsn_last = logc.last()[0] self.assertEqual(logc.next(), None) lsn_first = logc.first()[0] v = logc.next() self._check_return(v) self.assertTrue(lsn_first < v[0]) self.assertTrue(lsn_last > v[0]) v2 = logc.next() self.assertTrue(v2[0] > v[0]) self.assertTrue(lsn_last > v2[0]) v3 = logc.next() self.assertTrue(v3[0] > v2[0]) self.assertTrue(lsn_last > v3[0]) def test_4_prev(self) : logc = self.env.log_cursor() lsn_first = logc.first()[0] self.assertEqual(logc.prev(), None) lsn_last = logc.last()[0] v = logc.prev() self._check_return(v) self.assertTrue(lsn_first < v[0]) self.assertTrue(lsn_last > v[0]) v2 = logc.prev() self.assertTrue(v2[0] < v[0]) self.assertTrue(lsn_first < v2[0]) v3 = logc.prev() self.assertTrue(v3[0] < v2[0]) self.assertTrue(lsn_first < v3[0]) def test_5_current(self) : logc = self.env.log_cursor() logc.first() v = logc.next() self.assertEqual(v, logc.current()) def test_6_set(self) : logc = self.env.log_cursor() logc.first() v = logc.next() self.assertNotEqual(v, logc.next()) self.assertNotEqual(v, logc.next()) self.assertEqual(v, logc.set(v[0])) def test_explicit_close(self) : logc = self.env.log_cursor() logc.close() self.assertRaises(db.DBCursorClosedError, logc.next) def test_implicit_close(self) : logc = [self.env.log_cursor() for i in xrange(10)] self.env.close() # This close should close too all its tree for i in logc : self.assertRaises(db.DBCursorClosedError, i.next) def test_suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(DBEnv_general)) suite.addTest(unittest.makeSuite(DBEnv_memp)) suite.addTest(unittest.makeSuite(DBEnv_logcursor)) suite.addTest(unittest.makeSuite(DBEnv_log)) suite.addTest(unittest.makeSuite(DBEnv_log_txn)) return suite if __name__ == '__main__': unittest.main(defaultTest='test_suite')
gpl-2.0
jcoady9/youtube-dl
youtube_dl/extractor/macgamestore.py
142
1275
from __future__ import unicode_literals from .common import InfoExtractor from ..utils import ExtractorError class MacGameStoreIE(InfoExtractor): IE_NAME = 'macgamestore' IE_DESC = 'MacGameStore trailers' _VALID_URL = r'https?://www\.macgamestore\.com/mediaviewer\.php\?trailer=(?P<id>\d+)' _TEST = { 'url': 'http://www.macgamestore.com/mediaviewer.php?trailer=2450', 'md5': '8649b8ea684b6666b4c5be736ecddc61', 'info_dict': { 'id': '2450', 'ext': 'm4v', 'title': 'Crow', } } def _real_extract(self, url): video_id = self._match_id(url) webpage = self._download_webpage( url, video_id, 'Downloading trailer page') if '>Missing Media<' in webpage: raise ExtractorError( 'Trailer %s does not exist' % video_id, expected=True) video_title = self._html_search_regex( r'<title>MacGameStore: (.*?) Trailer</title>', webpage, 'title') video_url = self._html_search_regex( r'(?s)<div\s+id="video-player".*?href="([^"]+)"\s*>', webpage, 'video URL') return { 'id': video_id, 'url': video_url, 'title': video_title }
unlicense
webmull/phantomjs
src/breakpad/src/tools/gyp/pylib/gyp/input.py
137
84791
#!/usr/bin/python # Copyright (c) 2009 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from compiler.ast import Const from compiler.ast import Dict from compiler.ast import Discard from compiler.ast import List from compiler.ast import Module from compiler.ast import Node from compiler.ast import Stmt import compiler import copy import gyp.common import optparse import os.path import re import shlex import subprocess import sys # A list of types that are treated as linkable. linkable_types = ['executable', 'shared_library', 'loadable_module'] # A list of sections that contain links to other targets. dependency_sections = ['dependencies', 'export_dependent_settings'] # base_path_sections is a list of sections defined by GYP that contain # pathnames. The generators can provide more keys, the two lists are merged # into path_sections, but you should call IsPathSection instead of using either # list directly. base_path_sections = [ 'destination', 'files', 'include_dirs', 'inputs', 'libraries', 'outputs', 'sources', ] path_sections = [] def IsPathSection(section): if section in path_sections or \ section.endswith('_dir') or section.endswith('_dirs') or \ section.endswith('_file') or section.endswith('_files') or \ section.endswith('_path') or section.endswith('_paths'): return True return False # base_non_configuraiton_keys is a list of key names that belong in the target # itself and should not be propagated into its configurations. It is merged # with a list that can come from the generator to # create non_configuration_keys. base_non_configuration_keys = [ # Sections that must exist inside targets and not configurations. 'actions', 'configurations', 'copies', 'default_configuration', 'dependencies', 'dependencies_original', 'link_languages', 'libraries', 'postbuilds', 'product_dir', 'product_extension', 'product_name', 'rules', 'run_as', 'sources', 'suppress_wildcard', 'target_name', 'test', 'toolset', 'toolsets', 'type', 'variants', # Sections that can be found inside targets or configurations, but that # should not be propagated from targets into their configurations. 'variables', ] non_configuration_keys = [] # Controls how the generator want the build file paths. absolute_build_file_paths = False # Controls whether or not the generator supports multiple toolsets. multiple_toolsets = False def GetIncludedBuildFiles(build_file_path, aux_data, included=None): """Return a list of all build files included into build_file_path. The returned list will contain build_file_path as well as all other files that it included, either directly or indirectly. Note that the list may contain files that were included into a conditional section that evaluated to false and was not merged into build_file_path's dict. aux_data is a dict containing a key for each build file or included build file. Those keys provide access to dicts whose "included" keys contain lists of all other files included by the build file. included should be left at its default None value by external callers. It is used for recursion. The returned list will not contain any duplicate entries. Each build file in the list will be relative to the current directory. """ if included == None: included = [] if build_file_path in included: return included included.append(build_file_path) for included_build_file in aux_data[build_file_path].get('included', []): GetIncludedBuildFiles(included_build_file, aux_data, included) return included def CheckedEval(file_contents): """Return the eval of a gyp file. The gyp file is restricted to dictionaries and lists only, and repeated keys are not allowed. Note that this is slower than eval() is. """ ast = compiler.parse(file_contents) assert isinstance(ast, Module) c1 = ast.getChildren() assert c1[0] is None assert isinstance(c1[1], Stmt) c2 = c1[1].getChildren() assert isinstance(c2[0], Discard) c3 = c2[0].getChildren() assert len(c3) == 1 return CheckNode(c3[0],0) def CheckNode(node, level): if isinstance(node, Dict): c = node.getChildren() dict = {} for n in range(0, len(c), 2): assert isinstance(c[n], Const) key = c[n].getChildren()[0] if key in dict: raise KeyError, "Key '" + key + "' repeated at level " + \ repr(level) dict[key] = CheckNode(c[n + 1], level + 1) return dict elif isinstance(node, List): c = node.getChildren() list = [] for child in c: list.append(CheckNode(child, level + 1)) return list elif isinstance(node, Const): return node.getChildren()[0] else: raise TypeError, "Unknown AST node " + repr(node) def LoadOneBuildFile(build_file_path, data, aux_data, variables, includes, is_target, check): if build_file_path in data: return data[build_file_path] if os.path.exists(build_file_path): build_file_contents = open(build_file_path).read() else: raise Exception("%s not found (cwd: %s)" % (build_file_path, os.getcwd())) build_file_data = None try: if check: build_file_data = CheckedEval(build_file_contents) else: build_file_data = eval(build_file_contents, {'__builtins__': None}, None) except SyntaxError, e: e.filename = build_file_path raise except Exception, e: gyp.common.ExceptionAppend(e, 'while reading ' + build_file_path) raise data[build_file_path] = build_file_data aux_data[build_file_path] = {} # Scan for includes and merge them in. try: if is_target: LoadBuildFileIncludesIntoDict(build_file_data, build_file_path, data, aux_data, variables, includes, check) else: LoadBuildFileIncludesIntoDict(build_file_data, build_file_path, data, aux_data, variables, None, check) except Exception, e: gyp.common.ExceptionAppend(e, 'while reading includes of ' + build_file_path) raise return build_file_data def LoadBuildFileIncludesIntoDict(subdict, subdict_path, data, aux_data, variables, includes, check): includes_list = [] if includes != None: includes_list.extend(includes) if 'includes' in subdict: for include in subdict['includes']: # "include" is specified relative to subdict_path, so compute the real # path to include by appending the provided "include" to the directory # in which subdict_path resides. relative_include = \ os.path.normpath(os.path.join(os.path.dirname(subdict_path), include)) includes_list.append(relative_include) # Unhook the includes list, it's no longer needed. del subdict['includes'] # Merge in the included files. for include in includes_list: if not 'included' in aux_data[subdict_path]: aux_data[subdict_path]['included'] = [] aux_data[subdict_path]['included'].append(include) gyp.DebugOutput(gyp.DEBUG_INCLUDES, "Loading Included File: '%s'" % include) MergeDicts(subdict, LoadOneBuildFile(include, data, aux_data, variables, None, False, check), subdict_path, include) # Recurse into subdictionaries. for k, v in subdict.iteritems(): if v.__class__ == dict: LoadBuildFileIncludesIntoDict(v, subdict_path, data, aux_data, variables, None, check) elif v.__class__ == list: LoadBuildFileIncludesIntoList(v, subdict_path, data, aux_data, variables, check) # This recurses into lists so that it can look for dicts. def LoadBuildFileIncludesIntoList(sublist, sublist_path, data, aux_data, variables, check): for item in sublist: if item.__class__ == dict: LoadBuildFileIncludesIntoDict(item, sublist_path, data, aux_data, variables, None, check) elif item.__class__ == list: LoadBuildFileIncludesIntoList(item, sublist_path, data, aux_data, variables, check) # Processes toolsets in all the targets. This recurses into condition entries # since they can contain toolsets as well. def ProcessToolsetsInDict(data): if 'targets' in data: target_list = data['targets'] new_target_list = [] for target in target_list: global multiple_toolsets if multiple_toolsets: toolsets = target.get('toolsets', ['target']) else: toolsets = ['target'] if len(toolsets) > 0: # Optimization: only do copies if more than one toolset is specified. for build in toolsets[1:]: new_target = copy.deepcopy(target) new_target['toolset'] = build new_target_list.append(new_target) target['toolset'] = toolsets[0] new_target_list.append(target) data['targets'] = new_target_list if 'conditions' in data: for condition in data['conditions']: if isinstance(condition, list): for condition_dict in condition[1:]: ProcessToolsetsInDict(condition_dict) # TODO(mark): I don't love this name. It just means that it's going to load # a build file that contains targets and is expected to provide a targets dict # that contains the targets... def LoadTargetBuildFile(build_file_path, data, aux_data, variables, includes, depth, check): global absolute_build_file_paths # If depth is set, predefine the DEPTH variable to be a relative path from # this build file's directory to the directory identified by depth. if depth: d = gyp.common.RelativePath(depth, os.path.dirname(build_file_path)) if d == '': variables['DEPTH'] = '.' else: variables['DEPTH'] = d # If the generator needs absolue paths, then do so. if absolute_build_file_paths: build_file_path = os.path.abspath(build_file_path) if build_file_path in data['target_build_files']: # Already loaded. return data['target_build_files'].add(build_file_path) gyp.DebugOutput(gyp.DEBUG_INCLUDES, "Loading Target Build File '%s'" % build_file_path) build_file_data = LoadOneBuildFile(build_file_path, data, aux_data, variables, includes, True, check) # Store DEPTH for later use in generators. build_file_data['_DEPTH'] = depth # Set up the included_files key indicating which .gyp files contributed to # this target dict. if 'included_files' in build_file_data: raise KeyError, build_file_path + ' must not contain included_files key' included = GetIncludedBuildFiles(build_file_path, aux_data) build_file_data['included_files'] = [] for included_file in included: # included_file is relative to the current directory, but it needs to # be made relative to build_file_path's directory. included_relative = \ gyp.common.RelativePath(included_file, os.path.dirname(build_file_path)) build_file_data['included_files'].append(included_relative) ProcessToolsetsInDict(build_file_data) # Apply "pre"/"early" variable expansions and condition evaluations. ProcessVariablesAndConditionsInDict(build_file_data, False, variables, build_file_path) # Look at each project's target_defaults dict, and merge settings into # targets. if 'target_defaults' in build_file_data: index = 0 if 'targets' in build_file_data: while index < len(build_file_data['targets']): # This procedure needs to give the impression that target_defaults is # used as defaults, and the individual targets inherit from that. # The individual targets need to be merged into the defaults. Make # a deep copy of the defaults for each target, merge the target dict # as found in the input file into that copy, and then hook up the # copy with the target-specific data merged into it as the replacement # target dict. old_target_dict = build_file_data['targets'][index] new_target_dict = copy.deepcopy(build_file_data['target_defaults']) MergeDicts(new_target_dict, old_target_dict, build_file_path, build_file_path) build_file_data['targets'][index] = new_target_dict index = index + 1 else: raise Exception, \ "Unable to find targets in build file %s" % build_file_path # No longer needed. del build_file_data['target_defaults'] # Look for dependencies. This means that dependency resolution occurs # after "pre" conditionals and variable expansion, but before "post" - # in other words, you can't put a "dependencies" section inside a "post" # conditional within a target. if 'targets' in build_file_data: for target_dict in build_file_data['targets']: if 'dependencies' not in target_dict: continue for dependency in target_dict['dependencies']: other_build_file = \ gyp.common.ResolveTarget(build_file_path, dependency, None)[0] try: LoadTargetBuildFile(other_build_file, data, aux_data, variables, includes, depth, check) except Exception, e: gyp.common.ExceptionAppend( e, 'while loading dependencies of %s' % build_file_path) raise return data # Look for the bracket that matches the first bracket seen in a # string, and return the start and end as a tuple. For example, if # the input is something like "<(foo <(bar)) blah", then it would # return (1, 13), indicating the entire string except for the leading # "<" and trailing " blah". def FindEnclosingBracketGroup(input): brackets = { '}': '{', ']': '[', ')': '(', } stack = [] count = 0 start = -1 for char in input: if char in brackets.values(): stack.append(char) if start == -1: start = count if char in brackets.keys(): try: last_bracket = stack.pop() except IndexError: return (-1, -1) if last_bracket != brackets[char]: return (-1, -1) if len(stack) == 0: return (start, count + 1) count = count + 1 return (-1, -1) canonical_int_re = re.compile('^(0|-?[1-9][0-9]*)$') def IsStrCanonicalInt(string): """Returns True if |string| is in its canonical integer form. The canonical form is such that str(int(string)) == string. """ if not isinstance(string, str) or not canonical_int_re.match(string): return False return True early_variable_re = re.compile('(?P<replace>(?P<type><!?@?)' '\((?P<is_array>\s*\[?)' '(?P<content>.*?)(\]?)\))') late_variable_re = re.compile('(?P<replace>(?P<type>>!?@?)' '\((?P<is_array>\s*\[?)' '(?P<content>.*?)(\]?)\))') # Global cache of results from running commands so they don't have to be run # more then once. cached_command_results = {} def ExpandVariables(input, is_late, variables, build_file): # Look for the pattern that gets expanded into variables if not is_late: variable_re = early_variable_re else: variable_re = late_variable_re input_str = str(input) # Get the entire list of matches as a list of MatchObject instances. # (using findall here would return strings, and we want # MatchObjects). matches = [match for match in variable_re.finditer(input_str)] output = input_str if matches: # Reverse the list of matches so that replacements are done right-to-left. # That ensures that earlier replacements won't mess up the string in a # way that causes later calls to find the earlier substituted text instead # of what's intended for replacement. matches.reverse() for match_group in matches: match = match_group.groupdict() gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Matches: %s" % repr(match)) # match['replace'] is the substring to look for, match['type'] # is the character code for the replacement type (< > <! >! <@ # >@ <!@ >!@), match['is_array'] contains a '[' for command # arrays, and match['content'] is the name of the variable (< >) # or command to run (<! >!). # run_command is true if a ! variant is used. run_command = '!' in match['type'] # Capture these now so we can adjust them later. replace_start = match_group.start('replace') replace_end = match_group.end('replace') # Find the ending paren, and re-evaluate the contained string. (c_start, c_end) = FindEnclosingBracketGroup(input_str[replace_start:]) # Adjust the replacement range to match the entire command # found by FindEnclosingBracketGroup (since the variable_re # probably doesn't match the entire command if it contained # nested variables). replace_end = replace_start + c_end # Find the "real" replacement, matching the appropriate closing # paren, and adjust the replacement start and end. replacement = input_str[replace_start:replace_end] # Figure out what the contents of the variable parens are. contents_start = replace_start + c_start + 1 contents_end = replace_end - 1 contents = input_str[contents_start:contents_end] # Recurse to expand variables in the contents contents = ExpandVariables(contents, is_late, variables, build_file) # Strip off leading/trailing whitespace so that variable matches are # simpler below (and because they are rarely needed). contents = contents.strip() # expand_to_list is true if an @ variant is used. In that case, # the expansion should result in a list. Note that the caller # is to be expecting a list in return, and not all callers do # because not all are working in list context. Also, for list # expansions, there can be no other text besides the variable # expansion in the input string. expand_to_list = '@' in match['type'] and input_str == replacement if run_command: # Run the command in the build file's directory. build_file_dir = os.path.dirname(build_file) if build_file_dir == '': # If build_file is just a leaf filename indicating a file in the # current directory, build_file_dir might be an empty string. Set # it to None to signal to subprocess.Popen that it should run the # command in the current directory. build_file_dir = None use_shell = True if match['is_array']: contents = eval(contents) use_shell = False # Check for a cached value to avoid executing commands more than once. # TODO(http://code.google.com/p/gyp/issues/detail?id=112): It is # possible that the command being invoked depends on the current # directory. For that case the syntax needs to be extended so that the # directory is also used in cache_key (it becomes a tuple). # TODO(http://code.google.com/p/gyp/issues/detail?id=111): In theory, # someone could author a set of GYP files where each time the command # is invoked it produces different output by design. When the need # arises, the syntax should be extended to support no caching off a # command's output so it is run every time. cache_key = str(contents) cached_value = cached_command_results.get(cache_key, None) if cached_value is None: gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Executing command '%s' in directory '%s'" % (contents,build_file_dir)) p = subprocess.Popen(contents, shell=use_shell, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, cwd=build_file_dir) (p_stdout, p_stderr) = p.communicate('') if p.wait() != 0 or p_stderr: sys.stderr.write(p_stderr) # Simulate check_call behavior, since check_call only exists # in python 2.5 and later. raise Exception("Call to '%s' returned exit status %d." % (contents, p.returncode)) replacement = p_stdout.rstrip() cached_command_results[cache_key] = replacement else: gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Had cache value for command '%s' in directory '%s'" % (contents,build_file_dir)) replacement = cached_value else: if not contents in variables: raise KeyError, 'Undefined variable ' + contents + \ ' in ' + build_file replacement = variables[contents] if isinstance(replacement, list): for item in replacement: if not isinstance(item, str) and not isinstance(item, int): raise TypeError, 'Variable ' + contents + \ ' must expand to a string or list of strings; ' + \ 'list contains a ' + \ item.__class__.__name__ # Run through the list and handle variable expansions in it. Since # the list is guaranteed not to contain dicts, this won't do anything # with conditions sections. ProcessVariablesAndConditionsInList(replacement, is_late, variables, build_file) elif not isinstance(replacement, str) and \ not isinstance(replacement, int): raise TypeError, 'Variable ' + contents + \ ' must expand to a string or list of strings; ' + \ 'found a ' + replacement.__class__.__name__ if expand_to_list: # Expanding in list context. It's guaranteed that there's only one # replacement to do in |input_str| and that it's this replacement. See # above. if isinstance(replacement, list): # If it's already a list, make a copy. output = replacement[:] else: # Split it the same way sh would split arguments. output = shlex.split(str(replacement)) else: # Expanding in string context. encoded_replacement = '' if isinstance(replacement, list): # When expanding a list into string context, turn the list items # into a string in a way that will work with a subprocess call. # # TODO(mark): This isn't completely correct. This should # call a generator-provided function that observes the # proper list-to-argument quoting rules on a specific # platform instead of just calling the POSIX encoding # routine. encoded_replacement = gyp.common.EncodePOSIXShellList(replacement) else: encoded_replacement = replacement output = output[:replace_start] + str(encoded_replacement) + \ output[replace_end:] # Prepare for the next match iteration. input_str = output # Look for more matches now that we've replaced some, to deal with # expanding local variables (variables defined in the same # variables block as this one). gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Found output %s, recursing." % repr(output)) if isinstance(output, list): new_output = [] for item in output: new_output.append(ExpandVariables(item, is_late, variables, build_file)) output = new_output else: output = ExpandVariables(output, is_late, variables, build_file) # Convert all strings that are canonically-represented integers into integers. if isinstance(output, list): for index in xrange(0, len(output)): if IsStrCanonicalInt(output[index]): output[index] = int(output[index]) elif IsStrCanonicalInt(output): output = int(output) gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Expanding %s to %s" % (repr(input), repr(output))) return output def ProcessConditionsInDict(the_dict, is_late, variables, build_file): # Process a 'conditions' or 'target_conditions' section in the_dict, # depending on is_late. If is_late is False, 'conditions' is used. # # Each item in a conditions list consists of cond_expr, a string expression # evaluated as the condition, and true_dict, a dict that will be merged into # the_dict if cond_expr evaluates to true. Optionally, a third item, # false_dict, may be present. false_dict is merged into the_dict if # cond_expr evaluates to false. # # Any dict merged into the_dict will be recursively processed for nested # conditionals and other expansions, also according to is_late, immediately # prior to being merged. if not is_late: conditions_key = 'conditions' else: conditions_key = 'target_conditions' if not conditions_key in the_dict: return conditions_list = the_dict[conditions_key] # Unhook the conditions list, it's no longer needed. del the_dict[conditions_key] for condition in conditions_list: if not isinstance(condition, list): raise TypeError, conditions_key + ' must be a list' if len(condition) != 2 and len(condition) != 3: # It's possible that condition[0] won't work in which case this # attempt will raise its own IndexError. That's probably fine. raise IndexError, conditions_key + ' ' + condition[0] + \ ' must be length 2 or 3, not ' + len(condition) [cond_expr, true_dict] = condition[0:2] false_dict = None if len(condition) == 3: false_dict = condition[2] # Do expansions on the condition itself. Since the conditon can naturally # contain variable references without needing to resort to GYP expansion # syntax, this is of dubious value for variables, but someone might want to # use a command expansion directly inside a condition. cond_expr_expanded = ExpandVariables(cond_expr, is_late, variables, build_file) if not isinstance(cond_expr_expanded, str) and \ not isinstance(cond_expr_expanded, int): raise ValueError, \ 'Variable expansion in this context permits str and int ' + \ 'only, found ' + expanded.__class__.__name__ try: ast_code = compile(cond_expr_expanded, '<string>', 'eval') if eval(ast_code, {'__builtins__': None}, variables): merge_dict = true_dict else: merge_dict = false_dict except SyntaxError, e: syntax_error = SyntaxError('%s while evaluating condition \'%s\' in %s ' 'at character %d.' % (str(e.args[0]), e.text, build_file, e.offset), e.filename, e.lineno, e.offset, e.text) raise syntax_error except NameError, e: gyp.common.ExceptionAppend(e, 'while evaluating condition \'%s\' in %s' % (cond_expr_expanded, build_file)) raise if merge_dict != None: # Expand variables and nested conditinals in the merge_dict before # merging it. ProcessVariablesAndConditionsInDict(merge_dict, is_late, variables, build_file) MergeDicts(the_dict, merge_dict, build_file, build_file) def LoadAutomaticVariablesFromDict(variables, the_dict): # Any keys with plain string values in the_dict become automatic variables. # The variable name is the key name with a "_" character prepended. for key, value in the_dict.iteritems(): if isinstance(value, str) or isinstance(value, int) or \ isinstance(value, list): variables['_' + key] = value def LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key): # Any keys in the_dict's "variables" dict, if it has one, becomes a # variable. The variable name is the key name in the "variables" dict. # Variables that end with the % character are set only if they are unset in # the variables dict. the_dict_key is the name of the key that accesses # the_dict in the_dict's parent dict. If the_dict's parent is not a dict # (it could be a list or it could be parentless because it is a root dict), # the_dict_key will be None. for key, value in the_dict.get('variables', {}).iteritems(): if not isinstance(value, str) and not isinstance(value, int) and \ not isinstance(value, list): continue if key.endswith('%'): variable_name = key[:-1] if variable_name in variables: # If the variable is already set, don't set it. continue if the_dict_key is 'variables' and variable_name in the_dict: # If the variable is set without a % in the_dict, and the_dict is a # variables dict (making |variables| a varaibles sub-dict of a # variables dict), use the_dict's definition. value = the_dict[variable_name] else: variable_name = key variables[variable_name] = value def ProcessVariablesAndConditionsInDict(the_dict, is_late, variables_in, build_file, the_dict_key=None): """Handle all variable and command expansion and conditional evaluation. This function is the public entry point for all variable expansions and conditional evaluations. The variables_in dictionary will not be modified by this function. """ # Make a copy of the variables_in dict that can be modified during the # loading of automatics and the loading of the variables dict. variables = variables_in.copy() LoadAutomaticVariablesFromDict(variables, the_dict) if 'variables' in the_dict: # Make sure all the local variables are added to the variables # list before we process them so that you can reference one # variable from another. They will be fully expanded by recursion # in ExpandVariables. for key, value in the_dict['variables'].iteritems(): variables[key] = value # Handle the associated variables dict first, so that any variable # references within can be resolved prior to using them as variables. # Pass a copy of the variables dict to avoid having it be tainted. # Otherwise, it would have extra automatics added for everything that # should just be an ordinary variable in this scope. ProcessVariablesAndConditionsInDict(the_dict['variables'], is_late, variables, build_file, 'variables') LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key) for key, value in the_dict.iteritems(): # Skip "variables", which was already processed if present. if key != 'variables' and isinstance(value, str): expanded = ExpandVariables(value, is_late, variables, build_file) if not isinstance(expanded, str) and not isinstance(expanded, int): raise ValueError, \ 'Variable expansion in this context permits str and int ' + \ 'only, found ' + expanded.__class__.__name__ + ' for ' + key the_dict[key] = expanded # Variable expansion may have resulted in changes to automatics. Reload. # TODO(mark): Optimization: only reload if no changes were made. variables = variables_in.copy() LoadAutomaticVariablesFromDict(variables, the_dict) LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key) # Process conditions in this dict. This is done after variable expansion # so that conditions may take advantage of expanded variables. For example, # if the_dict contains: # {'type': '<(library_type)', # 'conditions': [['_type=="static_library"', { ... }]]}, # _type, as used in the condition, will only be set to the value of # library_type if variable expansion is performed before condition # processing. However, condition processing should occur prior to recursion # so that variables (both automatic and "variables" dict type) may be # adjusted by conditions sections, merged into the_dict, and have the # intended impact on contained dicts. # # This arrangement means that a "conditions" section containing a "variables" # section will only have those variables effective in subdicts, not in # the_dict. The workaround is to put a "conditions" section within a # "variables" section. For example: # {'conditions': [['os=="mac"', {'variables': {'define': 'IS_MAC'}}]], # 'defines': ['<(define)'], # 'my_subdict': {'defines': ['<(define)']}}, # will not result in "IS_MAC" being appended to the "defines" list in the # current scope but would result in it being appended to the "defines" list # within "my_subdict". By comparison: # {'variables': {'conditions': [['os=="mac"', {'define': 'IS_MAC'}]]}, # 'defines': ['<(define)'], # 'my_subdict': {'defines': ['<(define)']}}, # will append "IS_MAC" to both "defines" lists. # Evaluate conditions sections, allowing variable expansions within them # as well as nested conditionals. This will process a 'conditions' or # 'target_conditions' section, perform appropriate merging and recursive # conditional and variable processing, and then remove the conditions section # from the_dict if it is present. ProcessConditionsInDict(the_dict, is_late, variables, build_file) # Conditional processing may have resulted in changes to automatics or the # variables dict. Reload. variables = variables_in.copy() LoadAutomaticVariablesFromDict(variables, the_dict) LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key) # Recurse into child dicts, or process child lists which may result in # further recursion into descendant dicts. for key, value in the_dict.iteritems(): # Skip "variables" and string values, which were already processed if # present. if key == 'variables' or isinstance(value, str): continue if isinstance(value, dict): # Pass a copy of the variables dict so that subdicts can't influence # parents. ProcessVariablesAndConditionsInDict(value, is_late, variables, build_file, key) elif isinstance(value, list): # The list itself can't influence the variables dict, and # ProcessVariablesAndConditionsInList will make copies of the variables # dict if it needs to pass it to something that can influence it. No # copy is necessary here. ProcessVariablesAndConditionsInList(value, is_late, variables, build_file) elif not isinstance(value, int): raise TypeError, 'Unknown type ' + value.__class__.__name__ + \ ' for ' + key def ProcessVariablesAndConditionsInList(the_list, is_late, variables, build_file): # Iterate using an index so that new values can be assigned into the_list. index = 0 while index < len(the_list): item = the_list[index] if isinstance(item, dict): # Make a copy of the variables dict so that it won't influence anything # outside of its own scope. ProcessVariablesAndConditionsInDict(item, is_late, variables, build_file) elif isinstance(item, list): ProcessVariablesAndConditionsInList(item, is_late, variables, build_file) elif isinstance(item, str): expanded = ExpandVariables(item, is_late, variables, build_file) if isinstance(expanded, str) or isinstance(expanded, int): the_list[index] = expanded elif isinstance(expanded, list): del the_list[index] for expanded_item in expanded: the_list.insert(index, expanded_item) index = index + 1 # index now identifies the next item to examine. Continue right now # without falling into the index increment below. continue else: raise ValueError, \ 'Variable expansion in this context permits strings and ' + \ 'lists only, found ' + expanded.__class__.__name__ + ' at ' + \ index elif not isinstance(item, int): raise TypeError, 'Unknown type ' + item.__class__.__name__ + \ ' at index ' + index index = index + 1 def BuildTargetsDict(data): """Builds a dict mapping fully-qualified target names to their target dicts. |data| is a dict mapping loaded build files by pathname relative to the current directory. Values in |data| are build file contents. For each |data| value with a "targets" key, the value of the "targets" key is taken as a list containing target dicts. Each target's fully-qualified name is constructed from the pathname of the build file (|data| key) and its "target_name" property. These fully-qualified names are used as the keys in the returned dict. These keys provide access to the target dicts, the dicts in the "targets" lists. """ targets = {} for build_file in data['target_build_files']: for target in data[build_file].get('targets', []): target_name = gyp.common.QualifiedTarget(build_file, target['target_name'], target['toolset']) if target_name in targets: raise KeyError, 'Duplicate target definitions for ' + target_name targets[target_name] = target return targets def QualifyDependencies(targets): """Make dependency links fully-qualified relative to the current directory. |targets| is a dict mapping fully-qualified target names to their target dicts. For each target in this dict, keys known to contain dependency links are examined, and any dependencies referenced will be rewritten so that they are fully-qualified and relative to the current directory. All rewritten dependencies are suitable for use as keys to |targets| or a similar dict. """ for target, target_dict in targets.iteritems(): target_build_file = gyp.common.BuildFile(target) toolset = target_dict['toolset'] for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) for index in xrange(0, len(dependencies)): dep_file, dep_target, dep_toolset = gyp.common.ResolveTarget( target_build_file, dependencies[index], toolset) global multiple_toolsets if not multiple_toolsets: # Ignore toolset specification in the dependency if it is specified. dep_toolset = toolset dependency = gyp.common.QualifiedTarget(dep_file, dep_target, dep_toolset) dependencies[index] = dependency # Make sure anything appearing in a list other than "dependencies" also # appears in the "dependencies" list. if dependency_key != 'dependencies' and \ dependency not in target_dict['dependencies']: raise KeyError, 'Found ' + dependency + ' in ' + dependency_key + \ ' of ' + target + ', but not in dependencies' def ExpandWildcardDependencies(targets, data): """Expands dependencies specified as build_file:*. For each target in |targets|, examines sections containing links to other targets. If any such section contains a link of the form build_file:*, it is taken as a wildcard link, and is expanded to list each target in build_file. The |data| dict provides access to build file dicts. Any target that does not wish to be included by wildcard can provide an optional "suppress_wildcard" key in its target dict. When present and true, a wildcard dependency link will not include such targets. All dependency names, including the keys to |targets| and the values in each dependency list, must be qualified when this function is called. """ for target, target_dict in targets.iteritems(): toolset = target_dict['toolset'] target_build_file = gyp.common.BuildFile(target) for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) # Loop this way instead of "for dependency in" or "for index in xrange" # because the dependencies list will be modified within the loop body. index = 0 while index < len(dependencies): (dependency_build_file, dependency_target, dependency_toolset) = \ gyp.common.ParseQualifiedTarget(dependencies[index]) if dependency_target != '*' and dependency_toolset != '*': # Not a wildcard. Keep it moving. index = index + 1 continue if dependency_build_file == target_build_file: # It's an error for a target to depend on all other targets in # the same file, because a target cannot depend on itself. raise KeyError, 'Found wildcard in ' + dependency_key + ' of ' + \ target + ' referring to same build file' # Take the wildcard out and adjust the index so that the next # dependency in the list will be processed the next time through the # loop. del dependencies[index] index = index - 1 # Loop through the targets in the other build file, adding them to # this target's list of dependencies in place of the removed # wildcard. dependency_target_dicts = data[dependency_build_file]['targets'] for dependency_target_dict in dependency_target_dicts: if int(dependency_target_dict.get('suppress_wildcard', False)): continue dependency_target_name = dependency_target_dict['target_name'] if (dependency_target != '*' and dependency_target != dependency_target_name): continue dependency_target_toolset = dependency_target_dict['toolset'] if (dependency_toolset != '*' and dependency_toolset != dependency_target_toolset): continue dependency = gyp.common.QualifiedTarget(dependency_build_file, dependency_target_name, dependency_target_toolset) index = index + 1 dependencies.insert(index, dependency) index = index + 1 class DependencyGraphNode(object): """ Attributes: ref: A reference to an object that this DependencyGraphNode represents. dependencies: List of DependencyGraphNodes on which this one depends. dependents: List of DependencyGraphNodes that depend on this one. """ class CircularException(Exception): pass def __init__(self, ref): self.ref = ref self.dependencies = [] self.dependents = [] def FlattenToList(self): # flat_list is the sorted list of dependencies - actually, the list items # are the "ref" attributes of DependencyGraphNodes. Every target will # appear in flat_list after all of its dependencies, and before all of its # dependents. flat_list = [] # in_degree_zeros is the list of DependencyGraphNodes that have no # dependencies not in flat_list. Initially, it is a copy of the children # of this node, because when the graph was built, nodes with no # dependencies were made implicit dependents of the root node. in_degree_zeros = self.dependents[:] while in_degree_zeros: # Nodes in in_degree_zeros have no dependencies not in flat_list, so they # can be appended to flat_list. Take these nodes out of in_degree_zeros # as work progresses, so that the next node to process from the list can # always be accessed at a consistent position. node = in_degree_zeros.pop(0) flat_list.append(node.ref) # Look at dependents of the node just added to flat_list. Some of them # may now belong in in_degree_zeros. for node_dependent in node.dependents: is_in_degree_zero = True for node_dependent_dependency in node_dependent.dependencies: if not node_dependent_dependency.ref in flat_list: # The dependent one or more dependencies not in flat_list. There # will be more chances to add it to flat_list when examining # it again as a dependent of those other dependencies, provided # that there are no cycles. is_in_degree_zero = False break if is_in_degree_zero: # All of the dependent's dependencies are already in flat_list. Add # it to in_degree_zeros where it will be processed in a future # iteration of the outer loop. in_degree_zeros.append(node_dependent) return flat_list def DirectDependencies(self, dependencies=None): """Returns a list of just direct dependencies.""" if dependencies == None: dependencies = [] for dependency in self.dependencies: # Check for None, corresponding to the root node. if dependency.ref != None and dependency.ref not in dependencies: dependencies.append(dependency.ref) return dependencies def _AddImportedDependencies(self, targets, dependencies=None): """Given a list of direct dependencies, adds indirect dependencies that other dependencies have declared to export their settings. This method does not operate on self. Rather, it operates on the list of dependencies in the |dependencies| argument. For each dependency in that list, if any declares that it exports the settings of one of its own dependencies, those dependencies whose settings are "passed through" are added to the list. As new items are added to the list, they too will be processed, so it is possible to import settings through multiple levels of dependencies. This method is not terribly useful on its own, it depends on being "primed" with a list of direct dependencies such as one provided by DirectDependencies. DirectAndImportedDependencies is intended to be the public entry point. """ if dependencies == None: dependencies = [] index = 0 while index < len(dependencies): dependency = dependencies[index] dependency_dict = targets[dependency] # Add any dependencies whose settings should be imported to the list # if not already present. Newly-added items will be checked for # their own imports when the list iteration reaches them. # Rather than simply appending new items, insert them after the # dependency that exported them. This is done to more closely match # the depth-first method used by DeepDependencies. add_index = 1 for imported_dependency in \ dependency_dict.get('export_dependent_settings', []): if imported_dependency not in dependencies: dependencies.insert(index + add_index, imported_dependency) add_index = add_index + 1 index = index + 1 return dependencies def DirectAndImportedDependencies(self, targets, dependencies=None): """Returns a list of a target's direct dependencies and all indirect dependencies that a dependency has advertised settings should be exported through the dependency for. """ dependencies = self.DirectDependencies(dependencies) return self._AddImportedDependencies(targets, dependencies) def DeepDependencies(self, dependencies=None): """Returns a list of all of a target's dependencies, recursively.""" if dependencies == None: dependencies = [] for dependency in self.dependencies: # Check for None, corresponding to the root node. if dependency.ref != None and dependency.ref not in dependencies: dependencies.append(dependency.ref) dependency.DeepDependencies(dependencies) return dependencies def LinkDependencies(self, targets, dependencies=None, initial=True): """Returns a list of dependency targets that are linked into this target. This function has a split personality, depending on the setting of |initial|. Outside callers should always leave |initial| at its default setting. When adding a target to the list of dependencies, this function will recurse into itself with |initial| set to False, to collect depenedencies that are linked into the linkable target for which the list is being built. """ if dependencies == None: dependencies = [] # Check for None, corresponding to the root node. if self.ref == None: return dependencies # It's kind of sucky that |targets| has to be passed into this function, # but that's presently the easiest way to access the target dicts so that # this function can find target types. if not 'target_name' in targets[self.ref]: raise Exception("Missing 'target_name' field in target.") try: target_type = targets[self.ref]['type'] except KeyError, e: raise Exception("Missing 'type' field in target %s" % targets[self.ref]['target_name']) is_linkable = target_type in linkable_types if initial and not is_linkable: # If this is the first target being examined and it's not linkable, # return an empty list of link dependencies, because the link # dependencies are intended to apply to the target itself (initial is # True) and this target won't be linked. return dependencies # Executables and loadable modules are already fully and finally linked. # Nothing else can be a link dependency of them, there can only be # dependencies in the sense that a dependent target might run an # executable or load the loadable_module. if not initial and target_type in ('executable', 'loadable_module'): return dependencies # The target is linkable, add it to the list of link dependencies. if self.ref not in dependencies: if target_type != 'none': # Special case: "none" type targets don't produce any linkable products # and shouldn't be exposed as link dependencies, although dependencies # of "none" type targets may still be link dependencies. dependencies.append(self.ref) if initial or not is_linkable: # If this is a subsequent target and it's linkable, don't look any # further for linkable dependencies, as they'll already be linked into # this target linkable. Always look at dependencies of the initial # target, and always look at dependencies of non-linkables. for dependency in self.dependencies: dependency.LinkDependencies(targets, dependencies, False) return dependencies def BuildDependencyList(targets): # Create a DependencyGraphNode for each target. Put it into a dict for easy # access. dependency_nodes = {} for target, spec in targets.iteritems(): if not target in dependency_nodes: dependency_nodes[target] = DependencyGraphNode(target) # Set up the dependency links. Targets that have no dependencies are treated # as dependent on root_node. root_node = DependencyGraphNode(None) for target, spec in targets.iteritems(): target_node = dependency_nodes[target] target_build_file = gyp.common.BuildFile(target) if not 'dependencies' in spec or len(spec['dependencies']) == 0: target_node.dependencies = [root_node] root_node.dependents.append(target_node) else: dependencies = spec['dependencies'] for index in xrange(0, len(dependencies)): try: dependency = dependencies[index] dependency_node = dependency_nodes[dependency] target_node.dependencies.append(dependency_node) dependency_node.dependents.append(target_node) except KeyError, e: gyp.common.ExceptionAppend(e, 'while trying to load target %s' % target) raise flat_list = root_node.FlattenToList() # If there's anything left unvisited, there must be a circular dependency # (cycle). If you need to figure out what's wrong, look for elements of # targets that are not in flat_list. if len(flat_list) != len(targets): raise DependencyGraphNode.CircularException, \ 'Some targets not reachable, cycle in dependency graph detected' return [dependency_nodes, flat_list] def DoDependentSettings(key, flat_list, targets, dependency_nodes): # key should be one of all_dependent_settings, direct_dependent_settings, # or link_settings. for target in flat_list: target_dict = targets[target] build_file = gyp.common.BuildFile(target) if key == 'all_dependent_settings': dependencies = dependency_nodes[target].DeepDependencies() elif key == 'direct_dependent_settings': dependencies = \ dependency_nodes[target].DirectAndImportedDependencies(targets) elif key == 'link_settings': dependencies = dependency_nodes[target].LinkDependencies(targets) else: raise KeyError, "DoDependentSettings doesn't know how to determine " + \ 'dependencies for ' + key for dependency in dependencies: dependency_dict = targets[dependency] if not key in dependency_dict: continue dependency_build_file = gyp.common.BuildFile(dependency) MergeDicts(target_dict, dependency_dict[key], build_file, dependency_build_file) def AdjustStaticLibraryDependencies(flat_list, targets, dependency_nodes): # Recompute target "dependencies" properties. For each static library # target, remove "dependencies" entries referring to other static libraries, # unless the dependency has the "hard_dependency" attribute set. For each # linkable target, add a "dependencies" entry referring to all of the # target's computed list of link dependencies (including static libraries # if no such entry is already present. for target in flat_list: target_dict = targets[target] target_type = target_dict['type'] if target_type == 'static_library': if not 'dependencies' in target_dict: continue target_dict['dependencies_original'] = target_dict.get( 'dependencies', [])[:] index = 0 while index < len(target_dict['dependencies']): dependency = target_dict['dependencies'][index] dependency_dict = targets[dependency] if dependency_dict['type'] == 'static_library' and \ (not 'hard_dependency' in dependency_dict or \ not dependency_dict['hard_dependency']): # A static library should not depend on another static library unless # the dependency relationship is "hard," which should only be done # when a dependent relies on some side effect other than just the # build product, like a rule or action output. Take the dependency # out of the list, and don't increment index because the next # dependency to analyze will shift into the index formerly occupied # by the one being removed. del target_dict['dependencies'][index] else: index = index + 1 # If the dependencies list is empty, it's not needed, so unhook it. if len(target_dict['dependencies']) == 0: del target_dict['dependencies'] elif target_type in linkable_types: # Get a list of dependency targets that should be linked into this # target. Add them to the dependencies list if they're not already # present. link_dependencies = dependency_nodes[target].LinkDependencies(targets) for dependency in link_dependencies: if dependency == target: continue if not 'dependencies' in target_dict: target_dict['dependencies'] = [] if not dependency in target_dict['dependencies']: target_dict['dependencies'].append(dependency) # Initialize this here to speed up MakePathRelative. exception_re = re.compile(r'''["']?[-/$<>]''') def MakePathRelative(to_file, fro_file, item): # If item is a relative path, it's relative to the build file dict that it's # coming from. Fix it up to make it relative to the build file dict that # it's going into. # Exception: any |item| that begins with these special characters is # returned without modification. # / Used when a path is already absolute (shortcut optimization; # such paths would be returned as absolute anyway) # $ Used for build environment variables # - Used for some build environment flags (such as -lapr-1 in a # "libraries" section) # < Used for our own variable and command expansions (see ExpandVariables) # > Used for our own variable and command expansions (see ExpandVariables) # # "/' Used when a value is quoted. If these are present, then we # check the second character instead. # if to_file == fro_file or exception_re.match(item): return item else: # TODO(dglazkov) The backslash/forward-slash replacement at the end is a # temporary measure. This should really be addressed by keeping all paths # in POSIX until actual project generation. return os.path.normpath(os.path.join( gyp.common.RelativePath(os.path.dirname(fro_file), os.path.dirname(to_file)), item)).replace('\\', '/') def MergeLists(to, fro, to_file, fro_file, is_paths=False, append=True): prepend_index = 0 for item in fro: singleton = False if isinstance(item, str) or isinstance(item, int): # The cheap and easy case. if is_paths: to_item = MakePathRelative(to_file, fro_file, item) else: to_item = item if not isinstance(item, str) or not item.startswith('-'): # Any string that doesn't begin with a "-" is a singleton - it can # only appear once in a list, to be enforced by the list merge append # or prepend. singleton = True elif isinstance(item, dict): # Make a copy of the dictionary, continuing to look for paths to fix. # The other intelligent aspects of merge processing won't apply because # item is being merged into an empty dict. to_item = {} MergeDicts(to_item, item, to_file, fro_file) elif isinstance(item, list): # Recurse, making a copy of the list. If the list contains any # descendant dicts, path fixing will occur. Note that here, custom # values for is_paths and append are dropped; those are only to be # applied to |to| and |fro|, not sublists of |fro|. append shouldn't # matter anyway because the new |to_item| list is empty. to_item = [] MergeLists(to_item, item, to_file, fro_file) else: raise TypeError, \ 'Attempt to merge list item of unsupported type ' + \ item.__class__.__name__ if append: # If appending a singleton that's already in the list, don't append. # This ensures that the earliest occurrence of the item will stay put. if not singleton or not to_item in to: to.append(to_item) else: # If prepending a singleton that's already in the list, remove the # existing instance and proceed with the prepend. This ensures that the # item appears at the earliest possible position in the list. while singleton and to_item in to: to.remove(to_item) # Don't just insert everything at index 0. That would prepend the new # items to the list in reverse order, which would be an unwelcome # surprise. to.insert(prepend_index, to_item) prepend_index = prepend_index + 1 def MergeDicts(to, fro, to_file, fro_file): # I wanted to name the parameter "from" but it's a Python keyword... for k, v in fro.iteritems(): # It would be nice to do "if not k in to: to[k] = v" but that wouldn't give # copy semantics. Something else may want to merge from the |fro| dict # later, and having the same dict ref pointed to twice in the tree isn't # what anyone wants considering that the dicts may subsequently be # modified. if k in to: bad_merge = False if isinstance(v, str) or isinstance(v, int): if not (isinstance(to[k], str) or isinstance(to[k], int)): bad_merge = True elif v.__class__ != to[k].__class__: bad_merge = True if bad_merge: raise TypeError, \ 'Attempt to merge dict value of type ' + v.__class__.__name__ + \ ' into incompatible type ' + to[k].__class__.__name__ + \ ' for key ' + k if isinstance(v, str) or isinstance(v, int): # Overwrite the existing value, if any. Cheap and easy. is_path = IsPathSection(k) if is_path: to[k] = MakePathRelative(to_file, fro_file, v) else: to[k] = v elif isinstance(v, dict): # Recurse, guaranteeing copies will be made of objects that require it. if not k in to: to[k] = {} MergeDicts(to[k], v, to_file, fro_file) elif isinstance(v, list): # Lists in dicts can be merged with different policies, depending on # how the key in the "from" dict (k, the from-key) is written. # # If the from-key has ...the to-list will have this action # this character appended:... applied when receiving the from-list: # = replace # + prepend # ? set, only if to-list does not yet exist # (none) append # # This logic is list-specific, but since it relies on the associated # dict key, it's checked in this dict-oriented function. ext = k[-1] append = True if ext == '=': list_base = k[:-1] lists_incompatible = [list_base, list_base + '?'] to[list_base] = [] elif ext == '+': list_base = k[:-1] lists_incompatible = [list_base + '=', list_base + '?'] append = False elif ext == '?': list_base = k[:-1] lists_incompatible = [list_base, list_base + '=', list_base + '+'] else: list_base = k lists_incompatible = [list_base + '=', list_base + '?'] # Some combinations of merge policies appearing together are meaningless. # It's stupid to replace and append simultaneously, for example. Append # and prepend are the only policies that can coexist. for list_incompatible in lists_incompatible: if list_incompatible in fro: raise KeyError, 'Incompatible list policies ' + k + ' and ' + \ list_incompatible if list_base in to: if ext == '?': # If the key ends in "?", the list will only be merged if it doesn't # already exist. continue if not isinstance(to[list_base], list): # This may not have been checked above if merging in a list with an # extension character. raise TypeError, \ 'Attempt to merge dict value of type ' + v.__class__.__name__ + \ ' into incompatible type ' + to[list_base].__class__.__name__ + \ ' for key ' + list_base + '(' + k + ')' else: to[list_base] = [] # Call MergeLists, which will make copies of objects that require it. # MergeLists can recurse back into MergeDicts, although this will be # to make copies of dicts (with paths fixed), there will be no # subsequent dict "merging" once entering a list because lists are # always replaced, appended to, or prepended to. is_paths = IsPathSection(list_base) MergeLists(to[list_base], v, to_file, fro_file, is_paths, append) else: raise TypeError, \ 'Attempt to merge dict value of unsupported type ' + \ v.__class__.__name__ + ' for key ' + k def MergeConfigWithInheritance(new_configuration_dict, build_file, target_dict, configuration, visited): # Skip if previously visted. if configuration in visited: return # Look at this configuration. configuration_dict = target_dict['configurations'][configuration] # Merge in parents. for parent in configuration_dict.get('inherit_from', []): MergeConfigWithInheritance(new_configuration_dict, build_file, target_dict, parent, visited + [configuration]) # Merge it into the new config. MergeDicts(new_configuration_dict, configuration_dict, build_file, build_file) # Drop abstract. if 'abstract' in new_configuration_dict: del new_configuration_dict['abstract'] def SetUpConfigurations(target, target_dict): global non_configuration_keys # key_suffixes is a list of key suffixes that might appear on key names. # These suffixes are handled in conditional evaluations (for =, +, and ?) # and rules/exclude processing (for ! and /). Keys with these suffixes # should be treated the same as keys without. key_suffixes = ['=', '+', '?', '!', '/'] build_file = gyp.common.BuildFile(target) # Provide a single configuration by default if none exists. # TODO(mark): Signal an error if default_configurations exists but # configurations does not. if not 'configurations' in target_dict: target_dict['configurations'] = {'Default': {}} if not 'default_configuration' in target_dict: concrete = [i for i in target_dict['configurations'].keys() if not target_dict['configurations'][i].get('abstract')] target_dict['default_configuration'] = sorted(concrete)[0] for configuration in target_dict['configurations'].keys(): old_configuration_dict = target_dict['configurations'][configuration] # Skip abstract configurations (saves work only). if old_configuration_dict.get('abstract'): continue # Configurations inherit (most) settings from the enclosing target scope. # Get the inheritance relationship right by making a copy of the target # dict. new_configuration_dict = copy.deepcopy(target_dict) # Take out the bits that don't belong in a "configurations" section. # Since configuration setup is done before conditional, exclude, and rules # processing, be careful with handling of the suffix characters used in # those phases. delete_keys = [] for key in new_configuration_dict: key_ext = key[-1:] if key_ext in key_suffixes: key_base = key[:-1] else: key_base = key if key_base in non_configuration_keys: delete_keys.append(key) for key in delete_keys: del new_configuration_dict[key] # Merge in configuration (with all its parents first). MergeConfigWithInheritance(new_configuration_dict, build_file, target_dict, configuration, []) # Put the new result back into the target dict as a configuration. target_dict['configurations'][configuration] = new_configuration_dict # Now drop all the abstract ones. for configuration in target_dict['configurations'].keys(): old_configuration_dict = target_dict['configurations'][configuration] if old_configuration_dict.get('abstract'): del target_dict['configurations'][configuration] # Now that all of the target's configurations have been built, go through # the target dict's keys and remove everything that's been moved into a # "configurations" section. delete_keys = [] for key in target_dict: key_ext = key[-1:] if key_ext in key_suffixes: key_base = key[:-1] else: key_base = key if not key_base in non_configuration_keys: delete_keys.append(key) for key in delete_keys: del target_dict[key] def ProcessListFiltersInDict(name, the_dict): """Process regular expression and exclusion-based filters on lists. An exclusion list is in a dict key named with a trailing "!", like "sources!". Every item in such a list is removed from the associated main list, which in this example, would be "sources". Removed items are placed into a "sources_excluded" list in the dict. Regular expression (regex) filters are contained in dict keys named with a trailing "/", such as "sources/" to operate on the "sources" list. Regex filters in a dict take the form: 'sources/': [ ['exclude', '_(linux|mac|win)\\.cc$'] ], ['include', '_mac\\.cc$'] ], The first filter says to exclude all files ending in _linux.cc, _mac.cc, and _win.cc. The second filter then includes all files ending in _mac.cc that are now or were once in the "sources" list. Items matching an "exclude" filter are subject to the same processing as would occur if they were listed by name in an exclusion list (ending in "!"). Items matching an "include" filter are brought back into the main list if previously excluded by an exclusion list or exclusion regex filter. Subsequent matching "exclude" patterns can still cause items to be excluded after matching an "include". """ # Look through the dictionary for any lists whose keys end in "!" or "/". # These are lists that will be treated as exclude lists and regular # expression-based exclude/include lists. Collect the lists that are # needed first, looking for the lists that they operate on, and assemble # then into |lists|. This is done in a separate loop up front, because # the _included and _excluded keys need to be added to the_dict, and that # can't be done while iterating through it. lists = [] del_lists = [] for key, value in the_dict.iteritems(): operation = key[-1] if operation != '!' and operation != '/': continue if not isinstance(value, list): raise ValueError, name + ' key ' + key + ' must be list, not ' + \ value.__class__.__name__ list_key = key[:-1] if list_key not in the_dict: # This happens when there's a list like "sources!" but no corresponding # "sources" list. Since there's nothing for it to operate on, queue up # the "sources!" list for deletion now. del_lists.append(key) continue if not isinstance(the_dict[list_key], list): raise ValueError, name + ' key ' + list_key + \ ' must be list, not ' + \ value.__class__.__name__ + ' when applying ' + \ {'!': 'exclusion', '/': 'regex'}[operation] if not list_key in lists: lists.append(list_key) # Delete the lists that are known to be unneeded at this point. for del_list in del_lists: del the_dict[del_list] for list_key in lists: the_list = the_dict[list_key] # Initialize the list_actions list, which is parallel to the_list. Each # item in list_actions identifies whether the corresponding item in # the_list should be excluded, unconditionally preserved (included), or # whether no exclusion or inclusion has been applied. Items for which # no exclusion or inclusion has been applied (yet) have value -1, items # excluded have value 0, and items included have value 1. Includes and # excludes override previous actions. All items in list_actions are # initialized to -1 because no excludes or includes have been processed # yet. list_actions = list((-1,) * len(the_list)) exclude_key = list_key + '!' if exclude_key in the_dict: for exclude_item in the_dict[exclude_key]: for index in xrange(0, len(the_list)): if exclude_item == the_list[index]: # This item matches the exclude_item, so set its action to 0 # (exclude). list_actions[index] = 0 # The "whatever!" list is no longer needed, dump it. del the_dict[exclude_key] regex_key = list_key + '/' if regex_key in the_dict: for regex_item in the_dict[regex_key]: [action, pattern] = regex_item pattern_re = re.compile(pattern) for index in xrange(0, len(the_list)): list_item = the_list[index] if pattern_re.search(list_item): # Regular expression match. if action == 'exclude': # This item matches an exclude regex, so set its value to 0 # (exclude). list_actions[index] = 0 elif action == 'include': # This item matches an include regex, so set its value to 1 # (include). list_actions[index] = 1 else: # This is an action that doesn't make any sense. raise ValueError, 'Unrecognized action ' + action + ' in ' + \ name + ' key ' + key # The "whatever/" list is no longer needed, dump it. del the_dict[regex_key] # Add excluded items to the excluded list. # # Note that exclude_key ("sources!") is different from excluded_key # ("sources_excluded"). The exclude_key list is input and it was already # processed and deleted; the excluded_key list is output and it's about # to be created. excluded_key = list_key + '_excluded' if excluded_key in the_dict: raise KeyError, \ name + ' key ' + excluded_key + ' must not be present prior ' + \ ' to applying exclusion/regex filters for ' + list_key excluded_list = [] # Go backwards through the list_actions list so that as items are deleted, # the indices of items that haven't been seen yet don't shift. That means # that things need to be prepended to excluded_list to maintain them in the # same order that they existed in the_list. for index in xrange(len(list_actions) - 1, -1, -1): if list_actions[index] == 0: # Dump anything with action 0 (exclude). Keep anything with action 1 # (include) or -1 (no include or exclude seen for the item). excluded_list.insert(0, the_list[index]) del the_list[index] # If anything was excluded, put the excluded list into the_dict at # excluded_key. if len(excluded_list) > 0: the_dict[excluded_key] = excluded_list # Now recurse into subdicts and lists that may contain dicts. for key, value in the_dict.iteritems(): if isinstance(value, dict): ProcessListFiltersInDict(key, value) elif isinstance(value, list): ProcessListFiltersInList(key, value) def ProcessListFiltersInList(name, the_list): for item in the_list: if isinstance(item, dict): ProcessListFiltersInDict(name, item) elif isinstance(item, list): ProcessListFiltersInList(name, item) def ValidateRulesInTarget(target, target_dict, extra_sources_for_rules): """Ensures that the rules sections in target_dict are valid and consistent, and determines which sources they apply to. Arguments: target: string, name of target. target_dict: dict, target spec containing "rules" and "sources" lists. extra_sources_for_rules: a list of keys to scan for rule matches in addition to 'sources'. """ # Dicts to map between values found in rules' 'rule_name' and 'extension' # keys and the rule dicts themselves. rule_names = {} rule_extensions = {} rules = target_dict.get('rules', []) for rule in rules: # Make sure that there's no conflict among rule names and extensions. rule_name = rule['rule_name'] if rule_name in rule_names: raise KeyError, 'rule %s exists in duplicate, target %s' % \ (rule_name, target) rule_names[rule_name] = rule rule_extension = rule['extension'] if rule_extension in rule_extensions: raise KeyError, ('extension %s associated with multiple rules, ' + 'target %s rules %s and %s') % \ (rule_extension, target, rule_extensions[rule_extension]['rule_name'], rule_name) rule_extensions[rule_extension] = rule # Make sure rule_sources isn't already there. It's going to be # created below if needed. if 'rule_sources' in rule: raise KeyError, \ 'rule_sources must not exist in input, target %s rule %s' % \ (target, rule_name) extension = rule['extension'] rule_sources = [] source_keys = ['sources'] source_keys.extend(extra_sources_for_rules) for source_key in source_keys: for source in target_dict.get(source_key, []): (source_root, source_extension) = os.path.splitext(source) if source_extension.startswith('.'): source_extension = source_extension[1:] if source_extension == extension: rule_sources.append(source) if len(rule_sources) > 0: rule['rule_sources'] = rule_sources def ValidateActionsInTarget(target, target_dict, build_file): '''Validates the inputs to the actions in a target.''' target_name = target_dict.get('target_name') actions = target_dict.get('actions', []) for action in actions: action_name = action.get('action_name') if not action_name: raise Exception("Anonymous action in target %s. " "An action must have an 'action_name' field." % target_name) inputs = action.get('inputs', []) def ValidateRunAsInTarget(target, target_dict, build_file): target_name = target_dict.get('target_name') run_as = target_dict.get('run_as') if not run_as: return if not isinstance(run_as, dict): raise Exception("The 'run_as' in target %s from file %s should be a " "dictionary." % (target_name, build_file)) action = run_as.get('action') if not action: raise Exception("The 'run_as' in target %s from file %s must have an " "'action' section." % (target_name, build_file)) if not isinstance(action, list): raise Exception("The 'action' for 'run_as' in target %s from file %s " "must be a list." % (target_name, build_file)) working_directory = run_as.get('working_directory') if working_directory and not isinstance(working_directory, str): raise Exception("The 'working_directory' for 'run_as' in target %s " "in file %s should be a string." % (target_name, build_file)) environment = run_as.get('environment') if environment and not isinstance(environment, dict): raise Exception("The 'environment' for 'run_as' in target %s " "in file %s should be a dictionary." % (target_name, build_file)) def TurnIntIntoStrInDict(the_dict): """Given dict the_dict, recursively converts all integers into strings. """ # Use items instead of iteritems because there's no need to try to look at # reinserted keys and their associated values. for k, v in the_dict.items(): if isinstance(v, int): v = str(v) the_dict[k] = v elif isinstance(v, dict): TurnIntIntoStrInDict(v) elif isinstance(v, list): TurnIntIntoStrInList(v) if isinstance(k, int): the_dict[str(k)] = v del the_dict[k] def TurnIntIntoStrInList(the_list): """Given list the_list, recursively converts all integers into strings. """ for index in xrange(0, len(the_list)): item = the_list[index] if isinstance(item, int): the_list[index] = str(item) elif isinstance(item, dict): TurnIntIntoStrInDict(item) elif isinstance(item, list): TurnIntIntoStrInList(item) def Load(build_files, variables, includes, depth, generator_input_info, check): # Set up path_sections and non_configuration_keys with the default data plus # the generator-specifc data. global path_sections path_sections = base_path_sections[:] path_sections.extend(generator_input_info['path_sections']) global non_configuration_keys non_configuration_keys = base_non_configuration_keys[:] non_configuration_keys.extend(generator_input_info['non_configuration_keys']) # TODO(mark) handle variants if the generator doesn't want them directly. generator_handles_variants = \ generator_input_info['generator_handles_variants'] global absolute_build_file_paths absolute_build_file_paths = \ generator_input_info['generator_wants_absolute_build_file_paths'] global multiple_toolsets multiple_toolsets = generator_input_info[ 'generator_supports_multiple_toolsets'] # A generator can have other lists (in addition to sources) be processed # for rules. extra_sources_for_rules = generator_input_info['extra_sources_for_rules'] # Load build files. This loads every target-containing build file into # the |data| dictionary such that the keys to |data| are build file names, # and the values are the entire build file contents after "early" or "pre" # processing has been done and includes have been resolved. # NOTE: data contains both "target" files (.gyp) and "includes" (.gypi), as # well as meta-data (e.g. 'included_files' key). 'target_build_files' keeps # track of the keys corresponding to "target" files. data = {'target_build_files': set()} aux_data = {} for build_file in build_files: # Normalize paths everywhere. This is important because paths will be # used as keys to the data dict and for references between input files. build_file = os.path.normpath(build_file) try: LoadTargetBuildFile(build_file, data, aux_data, variables, includes, depth, check) except Exception, e: gyp.common.ExceptionAppend(e, 'while trying to load %s' % build_file) raise # Build a dict to access each target's subdict by qualified name. targets = BuildTargetsDict(data) # Fully qualify all dependency links. QualifyDependencies(targets) # Expand dependencies specified as build_file:*. ExpandWildcardDependencies(targets, data) [dependency_nodes, flat_list] = BuildDependencyList(targets) # Handle dependent settings of various types. for settings_type in ['all_dependent_settings', 'direct_dependent_settings', 'link_settings']: DoDependentSettings(settings_type, flat_list, targets, dependency_nodes) # Take out the dependent settings now that they've been published to all # of the targets that require them. for target in flat_list: if settings_type in targets[target]: del targets[target][settings_type] # Make sure static libraries don't declare dependencies on other static # libraries, but that linkables depend on all unlinked static libraries # that they need so that their link steps will be correct. AdjustStaticLibraryDependencies(flat_list, targets, dependency_nodes) # Apply "post"/"late"/"target" variable expansions and condition evaluations. for target in flat_list: target_dict = targets[target] build_file = gyp.common.BuildFile(target) ProcessVariablesAndConditionsInDict(target_dict, True, variables, build_file) # Move everything that can go into a "configurations" section into one. for target in flat_list: target_dict = targets[target] SetUpConfigurations(target, target_dict) # Apply exclude (!) and regex (/) list filters. for target in flat_list: target_dict = targets[target] ProcessListFiltersInDict(target, target_dict) # Make sure that the rules make sense, and build up rule_sources lists as # needed. Not all generators will need to use the rule_sources lists, but # some may, and it seems best to build the list in a common spot. # Also validate actions and run_as elements in targets. for target in flat_list: target_dict = targets[target] build_file = gyp.common.BuildFile(target) ValidateRulesInTarget(target, target_dict, extra_sources_for_rules) ValidateRunAsInTarget(target, target_dict, build_file) ValidateActionsInTarget(target, target_dict, build_file) # Generators might not expect ints. Turn them into strs. TurnIntIntoStrInDict(data) # TODO(mark): Return |data| for now because the generator needs a list of # build files that came in. In the future, maybe it should just accept # a list, and not the whole data dict. return [flat_list, targets, data]
bsd-3-clause
40223105/2015cd_midterm
static/Brython3.1.1-20150328-091302/Lib/markdown2.py
669
8143
import browser.html import re class URL: def __init__(self,src): elts = src.split(maxsplit=1) self.href = elts[0] self.alt = '' if len(elts)==2: alt = elts[1] if alt[0]=='"' and alt[-1]=='"':self.alt=alt[1:-1] elif alt[0]=="'" and alt[-1]=="'":self.alt=alt[1:-1] elif alt[0]=="(" and alt[-1]==")":self.alt=alt[1:-1] class CodeBlock: def __init__(self,line): self.lines = [line] def to_html(self): if self.lines[0].startswith("`"): self.lines.pop(0) res = escape('\n'.join(self.lines)) res = unmark(res) res = '<pre class="marked">%s</pre>\n' %res return res,[] class Marked: def __init__(self, line=''): self.line = line self.children = [] def to_html(self): return apply_markdown(self.line) # get references refs = {} ref_pattern = r"^\[(.*)\]:\s+(.*)" def mark(src): global refs refs = {} # split source in sections # sections can be : # - a block-level HTML element (markdown syntax will not be processed) # - a script # - a span-level HTML tag (markdown syntax will be processed) # - a code block # normalise line feeds src = src.replace('\r\n','\n') # lines followed by dashes src = re.sub(r'(.*?)\n=+\n', '\n# \\1\n', src) src = re.sub(r'(.*?)\n-+\n', '\n## \\1\n', src) lines = src.split('\n') i = bq = 0 ul = ol = 0 while i<len(lines): # enclose lines starting by > in a blockquote if lines[i].startswith('>'): nb = 1 while nb<len(lines[i]) and lines[i][nb]=='>': nb += 1 lines[i] = lines[i][nb:] if nb>bq: lines.insert(i,'<blockquote>'*(nb-bq)) i += 1 bq = nb elif nb<bq: lines.insert(i,'</blockquote>'*(bq-nb)) i += 1 bq = nb elif bq>0: lines.insert(i,'</blockquote>'*bq) i += 1 bq = 0 # unordered lists if lines[i].strip() and lines[i].lstrip()[0] in '-+*' \ and (i==0 or ul or not lines[i-1].strip()): print('is ul',lines[i]) # line indentation indicates nesting level nb = 1+len(lines[i])-len(lines[i].lstrip()) lines[i] = '<li>'+lines[i][1+nb:] if nb>ul: lines.insert(i,'<ul>'*(nb-ul)) i += 1 elif nb<ul: lines.insert(i,'</ul>'*(ul-nb)) i += 1 ul = nb elif ul: lines.insert(i,'</ul>'*ul) i += 1 ul = 0 # ordered lists mo = re.search(r'^(\d+\.)',lines[i]) if mo: if not ol: lines.insert(i,'<ol>') i += 1 lines[i] = '<li>'+lines[i][len(mo.groups()[0]):] ol = 1 elif ol: lines.insert(i,'</ol>') i += 1 ol = 0 i += 1 sections = [] scripts = [] section = Marked() i = 0 while i<len(lines): line = lines[i] if line.strip() and line.startswith(' '): if isinstance(section,Marked) and section.line: sections.append(section) section = CodeBlock(line[4:]) j = i+1 while j<len(lines) and lines[j].strip() \ and lines[j].startswith(' '): section.lines.append(lines[j][4:]) j += 1 sections.append(section) section = Marked() i = j continue elif line.lower().startswith('<script'): if isinstance(section,Marked) and section.line: sections.append(section) section = Marked() j = i+1 while j<len(lines): if lines[j].lower().startswith('</script>'): scripts.append('\n'.join(lines[i+1:j])) for k in range(i,j+1): lines[k] = '' break j += 1 i = j continue else: mo = re.search(ref_pattern,line) if mo is not None: if isinstance(section,Marked) and section.line: sections.append(section) section = Marked() key = mo.groups()[0] value = URL(mo.groups()[1]) refs[key.lower()] = value else: if line.strip(): if section.line: section.line += ' ' section.line += line else: sections.append(section) section = Marked() i += 1 res = '' for section in sections: mk,_scripts = section.to_html() res += '<p>'+mk+'\n' scripts += _scripts return res,scripts def escape(czone): czone = czone.replace('&','&amp;') czone = czone.replace('<','&lt;') czone = czone.replace('>','&gt;') return czone def s_escape(mo): # used in re.sub czone = mo.string[mo.start():mo.end()] return escape(czone) def unmark(code_zone): # convert _ to &#95; inside inline code code_zone = code_zone.replace('_','&#95;') return code_zone def s_unmark(mo): # convert _ to &#95; inside inline code code_zone = mo.string[mo.start():mo.end()] code_zone = code_zone.replace('_','&#95;') return code_zone def apply_markdown(src): scripts = [] # replace \` by &#96; src = re.sub(r'\\\`','&#96;',src) # escape < > & in inline code code_pattern = r'\`(\S.*?\S)\`' src = re.sub(code_pattern,s_escape,src) # also convert _ src = re.sub(code_pattern,s_unmark,src) # inline links link_pattern1 = r'\[(.+?)\]\s?\((.+?)\)' def repl(mo): g1,g2 = mo.groups() g2 = re.sub('_','&#95;',g2) return '<a href="%s">%s</a>' %(g2,g1) src = re.sub(link_pattern1,repl,src) # reference links link_pattern2 = r'\[(.+?)\]\s?\[(.*?)\]' while True: mo = re.search(link_pattern2,src) if mo is None:break text,key = mo.groups() print(text,key) if not key:key=text # implicit link name if key.lower() not in refs: raise KeyError('unknow reference %s' %key) url = refs[key.lower()] repl = '<a href="'+url.href+'"' if url.alt: repl += ' title="'+url.alt+'"' repl += '>%s</a>' %text src = re.sub(link_pattern2,repl,src,count=1) # emphasis # replace \* by &#42; src = re.sub(r'\\\*','&#42;',src) # replace \_ by &#95; src = re.sub(r'\\\_','&#95;',src) # _ and * surrounded by spaces are not markup src = re.sub(r' _ ',' &#95; ',src) src = re.sub(r' \* ',' &#42; ',src) strong_patterns = [('STRONG',r'\*\*(.*?)\*\*'),('B',r'__(.*?)__')] for tag,strong_pattern in strong_patterns: src = re.sub(strong_pattern,r'<%s>\1</%s>' %(tag,tag),src) em_patterns = [('EM',r'\*(.*?)\*'),('I',r'\_(.*?)\_')] for tag,em_pattern in em_patterns: src = re.sub(em_pattern,r'<%s>\1</%s>' %(tag,tag),src) # inline code # replace \` by &#96; src = re.sub(r'\\\`','&#96;',src) code_pattern = r'\`(.*?)\`' src = re.sub(code_pattern,r'<code>\1</code>',src) # ordered lists lines = src.split('\n') atx_header_pattern = '^(#+)(.*)(#*)' for i,line in enumerate(lines): print('line [%s]' %line, line.startswith('#')) mo = re.search(atx_header_pattern,line) if not mo:continue print('pattern matches') level = len(mo.groups()[0]) lines[i] = re.sub(atx_header_pattern, '<H%s>%s</H%s>\n' %(level,mo.groups()[1],level), line,count=1) src = '\n'.join(lines) src = re.sub('\n\n+','\n<p>',src)+'\n' return src,scripts
gpl-3.0
YongMan/Xen-4.3.1
tools/python/xen/xm/main.py
20
129659
# (C) Copyright IBM Corp. 2005 # Copyright (C) 2004 Mike Wray # Copyright (c) 2005-2006 XenSource Ltd. # # Authors: # Sean Dague <sean at dague dot net> # Mike Wray <mike dot wray at hp dot com> # # This library is free software; you can redistribute it and/or # modify it under the terms of version 2.1 of the GNU Lesser General Public # License as published by the Free Software Foundation. # # 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """Grand unified management application for Xen. """ import atexit import cmd import os import pprint import shlex import sys import re import getopt import socket import traceback import xmlrpclib import time import datetime from select import select import xml.dom.minidom from xen.util.blkif import blkdev_name_to_number from xen.util import vscsi_util from xen.util.pci import * from xen.util import vusb_util import warnings warnings.filterwarnings('ignore', category=FutureWarning) from xen.xend import PrettyPrint from xen.xend import sxp from xen.xend import XendClient from xen.xend.XendConstants import * from xen.xend.server.DevConstants import xenbusState from xen.xm.opts import OptionError, Opts, wrap, set_true from xen.xm import console from xen.util.xmlrpcclient import ServerProxy import xen.util.xsm.xsm as security from xen.util.xsm.xsm import XSMError from xen.util.acmpolicy import ACM_LABEL_UNLABELED_DISPLAY from xen.util.sxputils import sxp2map, map2sxp as map_to_sxp from xen.util import auxbin import XenAPI import inspect from xen.xend import XendOptions xoptions = XendOptions.instance() import signal signal.signal(signal.SIGINT, signal.SIG_DFL) # getopt.gnu_getopt is better, but only exists in Python 2.3+. Use # getopt.getopt if gnu_getopt is not available. This will mean that options # may only be specified before positional arguments. if not hasattr(getopt, 'gnu_getopt'): getopt.gnu_getopt = getopt.getopt XM_CONFIG_FILE_ENVVAR = 'XM_CONFIG_FILE' XM_CONFIG_FILE_DEFAULT = auxbin.xen_configdir() + '/xm-config.xml' # Supported types of server SERVER_LEGACY_XMLRPC = 'LegacyXMLRPC' SERVER_XEN_API = 'Xen-API' # General help message USAGE_HELP = "Usage: xm <subcommand> [args]\n\n" \ "Control, list, and manipulate Xen guest instances.\n" USAGE_FOOTER = '<Domain> can either be the Domain Name or Id.\n' \ 'For more help on \'xm\' see the xm(1) man page.\n' \ 'For more help on \'xm create\' see the xmdomain.cfg(5) '\ ' man page.\n' # Help strings are indexed by subcommand name in this way: # 'subcommand': (argstring, description) SUBCOMMAND_HELP = { # common commands 'shell' : ('', 'Launch an interactive shell.'), 'console' : ('[-q|--quiet] <Domain>', 'Attach to <Domain>\'s console.'), 'vncviewer' : ('[--[vncviewer-]autopass] <Domain>', 'Attach to <Domain>\'s VNC server.'), 'create' : ('<ConfigFile> [options] [vars]', 'Create a domain based on <ConfigFile>.'), 'destroy' : ('<Domain>', 'Terminate a domain immediately.'), 'help' : ('', 'Display this message.'), 'list' : ('[options] [Domain, ...]', 'List information about all/some domains.'), 'mem-max' : ('<Domain> <Mem>', 'Set the maximum amount reservation for a domain.'), 'mem-set' : ('<Domain> <Mem>', 'Set the current memory usage for a domain.'), 'migrate' : ('<Domain> <Host>', 'Migrate a domain to another machine.'), 'pause' : ('<Domain>', 'Pause execution of a domain.'), 'reboot' : ('<Domain> [-wa]', 'Reboot a domain.'), 'reset' : ('<Domain>', 'Reset a domain.'), 'restore' : ('<CheckpointFile> [-p]', 'Restore a domain from a saved state.'), 'save' : ('[-c] <Domain> <CheckpointFile>', 'Save a domain state to restore later.'), 'shutdown' : ('<Domain> [-waRH]', 'Shutdown a domain.'), 'top' : ('', 'Monitor a host and the domains in real time.'), 'unpause' : ('<Domain>', 'Unpause a paused domain.'), 'uptime' : ('[-s] [Domain, ...]', 'Print uptime for all/some domains.'), # Life cycle xm commands 'new' : ('<ConfigFile> [options] [vars]', 'Adds a domain to Xend domain management'), 'delete' : ('<DomainName>', 'Remove a domain from Xend domain management.'), 'start' : ('<DomainName>', 'Start a Xend managed domain'), 'resume' : ('<DomainName>', 'Resume a Xend managed domain'), 'suspend' : ('<DomainName>', 'Suspend a Xend managed domain'), # less used commands 'dmesg' : ('[-c|--clear]', 'Read and/or clear Xend\'s message buffer.'), 'domid' : ('<DomainName>', 'Convert a domain name to domain id.'), 'domname' : ('<DomId>', 'Convert a domain id to domain name.'), 'dump-core' : ('[-L|--live] [-C|--crash] [-R|--reset] <Domain> [Filename]', 'Dump core for a specific domain.'), 'info' : ('[-c|--config] [-n|--numa]', 'Get information about Xen host.'), 'log' : ('', 'Print Xend log'), 'rename' : ('<Domain> <NewDomainName>', 'Rename a domain.'), 'sched-sedf' : ('<Domain> [options]', 'Get/set EDF parameters.'), 'sched-credit': ('[-d <Domain> [-w[=WEIGHT]|-c[=CAP]]]', 'Get/set credit scheduler parameters.'), 'sched-credit2': ('[-d <Domain> [-w[=WEIGHT]]', 'Get/set credit2 scheduler parameters.'), 'sysrq' : ('<Domain> <letter>', 'Send a sysrq to a domain.'), 'debug-keys' : ('<Keys>', 'Send debug keys to Xen.'), 'trigger' : ('<Domain> <nmi|reset|init|s3resume|power> [<VCPU>]', 'Send a trigger to a domain.'), 'vcpu-list' : ('[Domain, ...]', 'List the VCPUs for all/some domains.'), 'vcpu-pin' : ('<Domain> <VCPU|all> <CPUs|all>', 'Set which CPUs a VCPU can use.'), 'vcpu-set' : ('<Domain> <vCPUs>', 'Set the number of active VCPUs allowed for the' ' domain.'), #usb 'usb-add' : ('<domain> <[host:bus.addr] [host:vendor_id:product_id]>','Add the usb device to FV VM.'), 'usb-del' : ('<domain> <[host:bus.addr] [host:vendor_id:product_id]>','Delete the usb device to FV VM.'), #domstate 'domstate' : ('<domain> ', 'get the state of a domain'), # device commands 'block-attach' : ('<Domain> <BackDev> <FrontDev> <Mode> [BackDomain]', 'Create a new virtual block device.'), 'block-configure': ('<Domain> <BackDev> <FrontDev> <Mode> [BackDomain]', 'Change block device configuration'), 'block-detach' : ('<Domain> <DevId> [-f|--force]', 'Destroy a domain\'s virtual block device.'), 'block-list' : ('<Domain> [--long]', 'List virtual block devices for a domain.'), 'network-attach': ('<Domain> [type=<type>] [mac=<mac>] [bridge=<bridge>] ' '[ip=<ip>] [script=<script>] [backend=<BackDomain>] ' '[vifname=<name>] [rate=<rate>] [model=<model>]' '[accel=<accel>]', 'Create a new virtual network device.'), 'network-detach': ('<Domain> <DevId|mac> [-f|--force]', 'Destroy a domain\'s virtual network device.'), 'network-list' : ('<Domain> [--long]', 'List virtual network interfaces for a domain.'), 'network2-attach': ('<Domain> [front_mac=<mac>] [back_mac=<mac>] ' '[backend=<BackDomain>] [trusted=<0|1>] ' '[back_trusted=<0|1>] [bridge=<bridge>] ' '[filter_mac=<0|1>] [front_filter_mac=<0|1>] ' '[pdev=<PDEV>] [max_bypasses=n]', 'Create a new version 2 virtual network device.'), 'network2-detach': ('<Domain> <DevId> [-f|--force]', 'Destroy a domain\'s version 2 virtual network device.'), 'network2-list' : ('<Domain> [--long]', 'List version 2 virtual network interfaces for a domain.'), 'vnet-create' : ('<ConfigFile>','Create a vnet from ConfigFile.'), 'vnet-delete' : ('<VnetId>', 'Delete a Vnet.'), 'vnet-list' : ('[-l|--long]', 'List Vnets.'), 'pci-attach' : ('[-o|--options=<opt>] <Domain> <domain:bus:slot.func> [virtual slot]', 'Insert a new pass-through pci device.'), 'pci-detach' : ('<Domain> <domain:bus:slot.func>', 'Remove a domain\'s pass-through pci device.'), 'pci-list' : ('<Domain>', 'List pass-through pci devices for a domain.'), 'pci-list-assignable-devices' : ('', 'List all the assignable pci devices'), 'scsi-attach' : ('<Domain> <PhysDevice> <VirtDevice> [BackDomain]', 'Attach a new SCSI device.'), 'scsi-detach' : ('<Domain> <VirtDevice>', 'Detach a specified SCSI device.'), 'scsi-list' : ('<Domain> [--long]', 'List all SCSI devices currently attached.'), 'usb-attach' : ('<Domain> <DevId> <PortNumber> <BusId>', 'Attach a new USB physical bus to domain\'s virtual port.'), 'usb-detach' : ('<Domain> <DevId> <PortNumber>', 'Detach a USB physical bus from domain\'s virtual port.'), 'usb-list' : ('<Domain>', 'List domain\'s attachment state of all virtual port .'), 'usb-list-assignable-devices' : ('', 'List all the assignable usb devices'), 'usb-hc-create' : ('<Domain> <USBSpecVer> <NumberOfPorts>', 'Create a domain\'s new virtual USB host controller.'), 'usb-hc-destroy' : ('<Domain> <DevId>', 'Destroy a domain\'s virtual USB host controller.'), # tmem 'tmem-list' : ('[-l|--long] [<Domain>|-a|--all]', 'List tmem pools.'), 'tmem-thaw' : ('[<Domain>|-a|--all]', 'Thaw tmem pools.'), 'tmem-freeze' : ('[<Domain>|-a|--all]', 'Freeze tmem pools.'), 'tmem-destroy' : ('[<Domain>|-a|--all]', 'Destroy tmem pools.'), 'tmem-set' : ('[<Domain>|-a|--all] [weight=<weight>] [cap=<cap>] ' '[compress=<compress>]', 'Change tmem settings.'), 'tmem-freeable' : ('', 'Print freeable tmem (in MiB).'), 'tmem-shared-auth' : ('[<Domain>|-a|--all] [--uuid=<uuid>] [--auth=<0|1>]', 'De/authenticate shared tmem pool.'), # # cpupool commands # 'cpupool-create' : ('<ConfigFile> [vars]', 'Create a CPU pool based an ConfigFile.'), 'cpupool-new' : ('<ConfigFile> [vars]', 'Adds a CPU pool to Xend CPU pool management'), 'cpupool-start' : ('<CPU Pool>', 'Starts a Xend CPU pool'), 'cpupool-list' : ('[<CPU Pool>] [-l|--long] [-c|--cpus]', 'List CPU pools on host'), 'cpupool-destroy' : ('<CPU Pool>', 'Deactivates a CPU pool'), 'cpupool-delete' : ('<CPU Pool>', 'Removes a CPU pool from Xend management'), 'cpupool-cpu-add' : ('<CPU Pool> <CPU nr>', 'Adds a CPU to a CPU pool'), 'cpupool-cpu-remove': ('<CPU Pool> <CPU nr>', 'Removes a CPU from a CPU pool'), 'cpupool-migrate' : ('<Domain> <CPU Pool>', 'Moves a domain into a CPU pool'), # security 'addlabel' : ('<label> {dom <ConfigFile>|res <resource>|mgt <managed domain>} [<policy>]', 'Add security label to domain.'), 'rmlabel' : ('{dom <ConfigFile>|res <Resource>|mgt<managed domain>}', 'Remove a security label from domain.'), 'getlabel' : ('{dom <ConfigFile>|res <Resource>|mgt <managed domain>}', 'Show security label for domain or resource.'), 'dry-run' : ('<ConfigFile>', 'Test if a domain can access its resources.'), 'resources' : ('', 'Show info for each labeled resource.'), 'dumppolicy' : ('', 'Print hypervisor ACM state information.'), 'setpolicy' : ('<policytype> <policyfile> [options]', 'Set the policy of the system.'), 'resetpolicy' : ('', 'Set the policy of the system to the default policy.'), 'getpolicy' : ('[options]', 'Get the policy of the system.'), 'labels' : ('[policy] [type=dom|res|any]', 'List <type> labels for (active) policy.'), 'serve' : ('', 'Proxy Xend XMLRPC over stdio.'), 'getenforce' : ('', 'Returns the current enforcing mode for the Flask XSM module (Enforcing,Permissive)'), 'setenforce' : ('[ (Enforcing|1) | (Permissive|0) ]', 'Modifies the current enforcing mode for the Flask XSM module'), } SUBCOMMAND_OPTIONS = { 'sched-sedf': ( ('-p [MS]', '--period[=MS]', 'Relative deadline(ms)'), ('-s [MS]', '--slice[=MS]' , 'Worst-case execution time(ms). (slice < period)'), ('-l [MS]', '--latency[=MS]', 'Scaled period (ms) when domain performs heavy I/O'), ('-e [FLAG]', '--extra[=FLAG]', 'Flag (0 or 1) controls if domain can run in extra time.'), ('-w [FLOAT]', '--weight[=FLOAT]', 'CPU Period/slice (do not set with --period/--slice)'), ), 'sched-credit': ( ('-d DOMAIN', '--domain=DOMAIN', 'Domain to modify'), ('-w WEIGHT', '--weight=WEIGHT', 'Weight (int)'), ('-c CAP', '--cap=CAP', 'Cap (int)'), ), 'sched-credit2': ( ('-d DOMAIN', '--domain=DOMAIN', 'Domain to modify'), ('-w WEIGHT', '--weight=WEIGHT', 'Weight (int)'), ), 'list': ( ('-l', '--long', 'Output all VM details in SXP'), ('', '--label', 'Include security labels'), ('', '--state=<state>', 'Select only VMs with the specified state'), ('', '--pool=<pool>', 'Select only VMs in specified cpu pool'), ), 'console': ( ('-q', '--quiet', 'Do not print an error message if the domain does not exist'), ), 'vncviewer': ( ('', '--autopass', 'Pass VNC password to viewer via stdin and -autopass'), ('', '--vncviewer-autopass', '(consistency alias for --autopass)'), ), 'dmesg': ( ('-c', '--clear', 'Clear dmesg buffer as well as printing it'), ), 'vnet-list': ( ('-l', '--long', 'List Vnets as SXP'), ), 'network-list': ( ('-l', '--long', 'List resources as SXP'), ), 'dump-core': ( ('-L', '--live', 'Dump core without pausing the domain'), ('-C', '--crash', 'Crash domain after dumping core'), ('-R', '--reset', 'Reset domain after dumping core'), ), 'start': ( ('-p', '--paused', 'Do not unpause domain after starting it'), ('-c', '--console_autoconnect', 'Connect to the console after the domain is created'), ('', '--vncviewer', 'Connect to display via VNC after the domain is created'), ('', '--vncviewer-autopass', 'Pass VNC password to viewer via stdin and -autopass'), ), 'resume': ( ('-p', '--paused', 'Do not unpause domain after resuming it'), ), 'save': ( ('-c', '--checkpoint', 'Leave domain running after creating snapshot'), ), 'restore': ( ('-p', '--paused', 'Do not unpause domain after restoring it'), ), 'info': ( ('-c', '--config', 'List Xend configuration parameters'), ('-n', '--numa', 'List host NUMA topology information'), ), 'tmem-list': ( ('-l', '--long', 'List tmem stats.'), ), 'tmem-thaw': ( ('-a', '--all', 'Thaw all tmem.'), ), 'tmem-freeze': ( ('-a', '--all', 'Freeze all tmem.'), ), 'tmem-destroy': ( ('-a', '--all', 'Destroy all tmem.'), ), 'tmem-set': ( ('-a', '--all', 'Operate on all tmem.'), ), 'tmem-shared-auth': ( ('-a', '--all', 'Authenticate for all tmem pools.'), ('-u', '--uuid', 'Specify uuid (abcdef01-2345-6789-01234567890abcdef).'), ('-A', '--auth', '0=auth,1=deauth'), ), 'cpupool-list': ( ('-l', '--long', 'Output all CPU pool details in SXP format'), ('-c', '--cpus', 'Output list of CPUs used by a pool'), ), } common_commands = [ "console", "vncviewer", "create", "new", "delete", "destroy", "dump-core", "help", "list", "mem-set", "migrate", "pause", "reboot", "reset", "restore", "resume", "save", "shell", "shutdown", "start", "suspend", "top", "unpause", "uptime", "usb-add", "usb-del", "domstate", "vcpu-set", ] domain_commands = [ "console", "vncviewer", "create", "new", "delete", "destroy", "domid", "domname", "dump-core", "list", "mem-max", "mem-set", "migrate", "pause", "reboot", "rename", "reset", "restore", "resume", "save", "shutdown", "start", "suspend", "sysrq", "trigger", "top", "unpause", "uptime", "usb-add", "usb-del", "domstate", "vcpu-list", "vcpu-pin", "vcpu-set", ] host_commands = [ "debug-keys", "dmesg", "info", "log", "serve", ] scheduler_commands = [ "sched-credit2", "sched-credit", "sched-sedf", ] device_commands = [ "block-attach", "block-detach", "block-list", "block-configure", "network-attach", "network-detach", "network-list", "network2-attach", "network2-detach", "network2-list", "pci-attach", "pci-detach", "pci-list", "pci-list-assignable-devices", "scsi-attach", "scsi-detach", "scsi-list", "usb-attach", "usb-detach", "usb-list", "usb-list-assignable-devices", "usb-hc-create", "usb-hc-destroy", ] vnet_commands = [ "vnet-list", "vnet-create", "vnet-delete", ] security_commands = [ "setpolicy", ] acm_commands = [ "labels", "addlabel", "rmlabel", "getlabel", "dry-run", "resources", "dumppolicy", "resetpolicy", "getpolicy", ] flask_commands = [ "getenforce", "setenforce", ] tmem_commands = [ "tmem-list", "tmem-thaw", "tmem-freeze", "tmem-destroy", "tmem-set", "tmem-shared-auth", ] cpupool_commands = [ "cpupool-create", "cpupool-new", "cpupool-start", "cpupool-list", "cpupool-destroy", "cpupool-delete", "cpupool-cpu-add", "cpupool-cpu-remove", "cpupool-migrate", ] all_commands = (domain_commands + host_commands + scheduler_commands + device_commands + vnet_commands + security_commands + acm_commands + flask_commands + tmem_commands + cpupool_commands + ['shell', 'event-monitor']) ## # Configuration File Parsing ## xmConfigFile = os.getenv(XM_CONFIG_FILE_ENVVAR, XM_CONFIG_FILE_DEFAULT) config = None if os.path.isfile(xmConfigFile): try: config = xml.dom.minidom.parse(xmConfigFile) except: print >>sys.stderr, ('Ignoring invalid configuration file %s.' % xmConfigFile) def parseServer(): if config: server = config.getElementsByTagName('server') if server: st = server[0].getAttribute('type') if st != SERVER_XEN_API and st != SERVER_LEGACY_XMLRPC: print >>sys.stderr, ('Invalid server type %s; using %s.' % (st, SERVER_LEGACY_XMLRPC)) st = SERVER_LEGACY_XMLRPC return (st, server[0].getAttribute('uri')) return SERVER_LEGACY_XMLRPC, XendClient.uri def parseAuthentication(): server = config.getElementsByTagName('server')[0] return (server.getAttribute('username'), server.getAttribute('password')) serverType, serverURI = parseServer() server = None #################################################################### # # Help/usage printing functions # #################################################################### def cmdHelp(cmd): """Print help for a specific subcommand.""" if not SUBCOMMAND_HELP.has_key(cmd): for fc in SUBCOMMAND_HELP.keys(): if fc[:len(cmd)] == cmd: cmd = fc break try: args, desc = SUBCOMMAND_HELP[cmd] except KeyError: shortHelp() return print 'Usage: xm %s %s' % (cmd, args) print print desc try: # If options help message is defined, print this. for shortopt, longopt, desc in SUBCOMMAND_OPTIONS[cmd]: if shortopt and longopt: optdesc = '%s, %s' % (shortopt, longopt) elif shortopt: optdesc = shortopt elif longopt: optdesc = longopt wrapped_desc = wrap(desc, 43) print ' %-30s %-43s' % (optdesc, wrapped_desc[0]) for line in wrapped_desc[1:]: print ' ' * 33 + line print except KeyError: # if the command is an external module, we grab usage help # from the module itself. if cmd in IMPORTED_COMMANDS: try: cmd_module = __import__(cmd, globals(), locals(), 'xen.xm') cmd_usage = getattr(cmd_module, "help", None) if cmd_usage: print cmd_usage() except ImportError: pass def shortHelp(): """Print out generic help when xm is called without subcommand.""" print USAGE_HELP print 'Common \'xm\' commands:\n' for command in common_commands: try: args, desc = SUBCOMMAND_HELP[command] except KeyError: continue wrapped_desc = wrap(desc, 50) print ' %-20s %-50s' % (command, wrapped_desc[0]) for line in wrapped_desc[1:]: print ' ' * 22 + line print print USAGE_FOOTER print 'For a complete list of subcommands run \'xm help\'.' def longHelp(): """Print out full help when xm is called with xm --help or xm help""" print USAGE_HELP print 'xm full list of subcommands:\n' for command in all_commands: try: args, desc = SUBCOMMAND_HELP[command] except KeyError: continue wrapped_desc = wrap(desc, 50) print ' %-20s %-50s' % (command, wrapped_desc[0]) for line in wrapped_desc[1:]: print ' ' * 22 + line print print USAGE_FOOTER def _usage(cmd): """ Print help usage information """ if cmd: cmdHelp(cmd) else: shortHelp() def usage(cmd = None): """ Print help usage information and exits """ _usage(cmd) sys.exit(1) #################################################################### # # Utility functions # #################################################################### def get_default_SR(): return [sr_ref for sr_ref in server.xenapi.SR.get_all() if server.xenapi.SR.get_type(sr_ref) == "local"][0] def get_default_Network(): return [network_ref for network_ref in server.xenapi.network.get_all()][0] class XenAPIUnsupportedException(Exception): pass def xenapi_unsupported(): if serverType == SERVER_XEN_API: raise XenAPIUnsupportedException, "This function is not supported by Xen-API" def xenapi_only(): if serverType != SERVER_XEN_API: raise XenAPIUnsupportedException, "This function is only supported by Xen-API" def map2sxp(m): return [[k, m[k]] for k in m.keys()] def arg_check(args, name, lo, hi = -1): n = len([i for i in args if i != '--']) if hi == -1: if n != lo: err("'xm %s' requires %d argument%s.\n" % (name, lo, lo == 1 and '' or 's')) usage(name) else: if n < lo or n > hi: err("'xm %s' requires between %d and %d arguments.\n" % (name, lo, hi)) usage(name) def unit(c): if not c.isalpha(): return 0 base = 1 if c == 'G' or c == 'g': base = 1024 * 1024 * 1024 elif c == 'M' or c == 'm': base = 1024 * 1024 elif c == 'K' or c == 'k': base = 1024 else: print 'ignoring unknown unit' return base def int_unit(str, dest): base = unit(str[-1]) if not base: return int(str) value = int(str[:-1]) dst_base = unit(dest) if dst_base == 0: dst_base = 1 if dst_base > base: return value / (dst_base / base) else: return value * (base / dst_base) def err(msg): print >>sys.stderr, "Error:", msg def get_single_vm(dom): if serverType == SERVER_XEN_API: uuids = server.xenapi.VM.get_by_name_label(dom) if len(uuids) > 0: return uuids[0] refs = [] try: domid = int(dom) refs = [vm_ref for vm_ref in server.xenapi.VM.get_all() if int(server.xenapi.VM.get_domid(vm_ref)) == domid] except: pass if len(refs) > 0: return refs[0] raise OptionError("Domain '%s' not found." % dom) else: dominfo = server.xend.domain(dom, False) return dominfo['uuid'] ## # # Xen-API Shell # ## class Shell(cmd.Cmd): def __init__(self): cmd.Cmd.__init__(self) self.prompt = "xm> " if serverType == SERVER_XEN_API: try: res = server.xenapi.host.list_methods() for f in res: setattr(Shell, 'do_' + f + ' ', self.default) except: pass def preloop(self): cmd.Cmd.preloop(self) try: import readline readline.set_completer_delims(' ') except ImportError: pass def default(self, line): words = shlex.split(line) if len(words) > 0 and words[0] == 'xm': words = words[1:] if len(words) > 0: cmd = xm_lookup_cmd(words[0]) if cmd: _run_cmd(cmd, words[0], words[1:]) elif serverType == SERVER_XEN_API: ok, res = _run_cmd(lambda x: server.xenapi_request(words[0], tuple(x)), words[0], words[1:]) if ok and res is not None and res != '': pprint.pprint(res) else: print '*** Unknown command: %s' % words[0] return False def completedefault(self, text, line, begidx, endidx): words = shlex.split(line[:begidx]) clas, func = words[0].split('.') if len(words) > 1 or \ func.startswith('get_by_') or \ func == 'get_all': return [] uuids = server.xenapi_request('%s.get_all' % clas, ()) return [u + " " for u in uuids if u.startswith(text)] def emptyline(self): pass def do_EOF(self, line): print sys.exit(0) def do_help(self, line): _usage(line) def xm_shell(args): Shell().cmdloop('The Xen Master. Type "help" for a list of functions.') def xm_event_monitor(args): if serverType == SERVER_XEN_API: while True: server.xenapi.event.register(args) events = server.xenapi.event.next() for e in events: print e else: err("Event monitoring not supported unless using Xen-API.") ######################################################################### # # Main xm functions # ######################################################################### def xm_save(args): arg_check(args, "save", 2, 3) try: (options, params) = getopt.gnu_getopt(args, 'c', ['checkpoint']) except getopt.GetoptError, opterr: err(opterr) usage('save') checkpoint = False for (k, v) in options: if k in ['-c', '--checkpoint']: checkpoint = True if len(params) != 2: err("Wrong number of parameters") usage('save') dom = params[0] savefile = os.path.abspath(params[1]) if not os.access(os.path.dirname(savefile), os.W_OK): err("xm save: Unable to create file %s" % savefile) sys.exit(1) if serverType == SERVER_XEN_API: server.xenapi.VM.save(get_single_vm(dom), savefile, checkpoint) else: server.xend.domain.save(dom, savefile, checkpoint) def xm_restore(args): arg_check(args, "restore", 1, 2) try: (options, params) = getopt.gnu_getopt(args, 'p', ['paused']) except getopt.GetoptError, opterr: err(opterr) usage('restore') paused = False for (k, v) in options: if k in ['-p', '--paused']: paused = True if len(params) != 1: err("Wrong number of parameters") usage('restore') savefile = os.path.abspath(params[0]) if not os.access(savefile, os.R_OK): err("xm restore: Unable to read file %s" % savefile) sys.exit(1) if serverType == SERVER_XEN_API: server.xenapi.VM.restore(savefile, paused) else: server.xend.domain.restore(savefile, paused) def datetime_to_secs(v): unwanted = ":-." for c in unwanted: v = str(v).replace(c, "") return time.mktime(time.strptime(v[0:14], '%Y%m%dT%H%M%S')) def getDomains(domain_names, state, full = 0, pool = None): if serverType == SERVER_XEN_API: doms_sxp = [] doms_dict = [] dom_recs = server.xenapi.VM.get_all_records() dom_metrics_recs = server.xenapi.VM_metrics.get_all_records() for dom_ref, dom_rec in dom_recs.items(): if pool and pool != dom_rec['pool_name']: continue dom_metrics_rec = dom_metrics_recs[dom_rec['metrics']] states = ('running', 'blocked', 'paused', 'shutdown', 'crashed', 'dying') def state_on_off(state): if state in dom_metrics_rec['state']: return state[0] else: return "-" state_str = "".join([state_on_off(state) for state in states]) dom_rec.update({'name': dom_rec['name_label'], 'memory_actual': int(dom_metrics_rec['memory_actual'])/1024, 'vcpus': dom_metrics_rec['VCPUs_number'], 'state': state_str, 'cpu_time': dom_metrics_rec['VCPUs_utilisation'], 'start_time': datetime_to_secs( dom_metrics_rec['start_time'])}) doms_sxp.append(['domain'] + map2sxp(dom_rec)) doms_dict.append(dom_rec) if domain_names: doms = [['domain'] + map2sxp(dom) for dom in doms_dict if dom["name"] in domain_names] if len(doms) > 0: return doms else: print "Error: no domain%s named %s" % \ (len(domain_names) > 1 and 's' or '', ', '.join(domain_names)) sys.exit(-1) else: return doms_sxp else: if domain_names: return [server.xend.domain(dom, full) for dom in domain_names] else: doms = server.xend.domains_with_state(True, state, full) if not pool: return doms else: doms_in_pool = [] for dom in doms: if sxp.child_value(dom, 'pool_name', '') == pool: doms_in_pool.append(dom) return doms_in_pool def xm_list(args): use_long = 0 show_vcpus = 0 show_labels = 0 state = 'all' pool = None try: (options, params) = getopt.gnu_getopt(args, 'lv', ['long','vcpus','label', 'state=','pool=']) except getopt.GetoptError, opterr: err(opterr) usage('list') for (k, v) in options: if k in ['-l', '--long']: use_long = 1 if k in ['-v', '--vcpus']: show_vcpus = 1 if k in ['--label']: show_labels = 1 if k in ['--state']: state = v if k in ['--pool']: pool = v if state != 'all' and len(params) > 0: raise OptionError( "You may specify either a state or a particular VM, but not both") if pool and len(params) > 0: raise OptionError( "You may specify either a pool or a particular VM, but not both") if show_vcpus: print >>sys.stderr, ( "xm list -v is deprecated. Please use xm vcpu-list.") xm_vcpu_list(params) return doms = getDomains(params, state, use_long, pool) if use_long: map(PrettyPrint.prettyprint, doms) elif show_labels: xm_label_list(doms) else: xm_brief_list(doms) def parse_doms_info(info): def get_info(n, t, d): return t(sxp.child_value(info, n, d)) def get_status(n, t, d): return DOM_STATES[t(sxp.child_value(info, n, d))] start_time = get_info('start_time', float, -1) if start_time == -1: up_time = float(-1) else: up_time = time.time() - start_time parsed_info = { 'domid' : get_info('domid', str, ''), 'name' : get_info('name', str, '??'), 'state' : get_info('state', str, ''), # VCPUs is the number online when the VM is up, or the number # configured otherwise. 'vcpus' : get_info('online_vcpus', int, get_info('vcpus', int, 0)), 'up_time' : up_time } security_label = get_info('security_label', str, '') parsed_info['seclabel'] = security.parse_security_label(security_label) if serverType == SERVER_XEN_API: parsed_info['mem'] = get_info('memory_actual', int, 0) / 1024 cpu_times = get_info('cpu_time', lambda x : (x), 0.0) if sum(cpu_times.values()) > 0: parsed_info['cpu_time'] = sum(cpu_times.values()) / float(len(cpu_times.values())) else: parsed_info['cpu_time'] = 0 else: parsed_info['mem'] = get_info('memory', int,0) parsed_info['cpu_time'] = get_info('cpu_time', float, 0.0) return parsed_info def check_sched_type(sched): if serverType == SERVER_XEN_API: current = server.xenapi.host.get_sched_policy( server.xenapi.session.get_this_host(server.getSession())) else: current = 'unknown' for x in server.xend.node.info()[1:]: if len(x) > 1 and x[0] == 'xen_scheduler': current = x[1] break if sched != current: err("Xen is running with the %s scheduler" % current) sys.exit(1) def parse_sedf_info(info): def get_info(n, t, d): return t(sxp.child_value(info, n, d)) return { 'domid' : get_info('domid', int, -1), 'period' : get_info('period', int, -1), 'slice' : get_info('slice', int, -1), 'latency' : get_info('latency', int, -1), 'extratime': get_info('extratime', int, -1), 'weight' : get_info('weight', int, -1), } def domid_match(domid, info): return domid is None or domid == info['name'] or \ domid == str(info['domid']) def xm_brief_list(doms): print '%-40s %5s %5s %5s %10s %9s' % \ ('Name', 'ID', 'Mem', 'VCPUs', 'State', 'Time(s)') format = "%(name)-40s %(domid)5s %(mem)5d %(vcpus)5d %(state)10s " \ "%(cpu_time)8.1f" for dom in doms: d = parse_doms_info(dom) print format % d def xm_label_list(doms): print '%-40s %5s %5s %5s %10s %9s %-10s' % \ ('Name', 'ID', 'Mem', 'VCPUs', 'State', 'Time(s)', 'Label') output = [] format = '%(name)-40s %(domid)5s %(mem)5d %(vcpus)5d %(state)10s ' \ '%(cpu_time)8.1f %(seclabel)10s' for dom in doms: d = parse_doms_info(dom) if d['seclabel'] == "" and serverType != SERVER_XEN_API: seclab = server.xend.security.get_domain_label(d['name']) if len(seclab) > 0 and seclab[0] == '\'': seclab = seclab[1:] d['seclabel'] = seclab output.append((format % d, d['seclabel'])) #sort by labels output.sort(lambda x,y: cmp( x[1].lower(), y[1].lower())) for line, label in output: print line def xm_vcpu_list(args): if serverType == SERVER_XEN_API: if args: vm_refs = map(get_single_vm, args) else: vm_refs = server.xenapi.VM.get_all() vm_records = dict(map(lambda vm_ref: (vm_ref, server.xenapi.VM.get_record( vm_ref)), vm_refs)) vm_metrics = dict(map(lambda (ref, record): (ref, server.xenapi.VM_metrics.get_record( record['metrics'])), vm_records.items())) dominfo = [] # vcpu_list doesn't list 'managed' domains # when they are not running, so filter them out vm_refs = [vm_ref for vm_ref in vm_refs if vm_records[vm_ref]["power_state"] != "Halted"] for vm_ref in vm_refs: info = ['domain', ['domid', vm_records[vm_ref]['domid']], ['name', vm_records[vm_ref]['name_label']], ['vcpu_count', vm_records[vm_ref]['VCPUs_max']]] for i in range(int(vm_records[vm_ref]['VCPUs_max'])): def chk_flag(flag): return flag in vm_metrics[vm_ref]['VCPUs_flags'][str(i)] \ and 1 or 0 vcpu_info = ['vcpu', ['number', i], ['online', chk_flag("online")], ['blocked', chk_flag("blocked")], ['running', chk_flag("running")], ['cpu_time', vm_metrics[vm_ref]['VCPUs_utilisation'][str(i)]], ['cpu', vm_metrics[vm_ref]['VCPUs_CPU'][str(i)]], ['cpumap', vm_metrics[vm_ref]['VCPUs_params']\ ['cpumap%i' % i].split(",")]] info.append(vcpu_info) dominfo.append(info) else: if args: dominfo = map(server.xend.domain.getVCPUInfo, args) else: doms = server.xend.domains_with_state(False, 'all', False) dominfo = map(server.xend.domain.getVCPUInfo, doms) print '%-32s %5s %5s %5s %5s %9s %s' % \ ('Name', 'ID', 'VCPU', 'CPU', 'State', 'Time(s)', 'CPU Affinity') format = '%(name)-32s %(domid)5s %(number)5d %(c)5s %(s)5s ' \ ' %(cpu_time)8.1f %(cpumap)s' for dom in dominfo: def get_info(n): return sxp.child_value(dom, n) # # convert a list of integers into a list of pairs indicating # continuous sequences in the list: # # [0,1,2,3] -> [(0,3)] # [1,2,4,5] -> [(1,2),(4,5)] # [0] -> [(0,0)] # [0,1,4,6,7] -> [(0,1),(4,4),(6,7)] # def list_to_rangepairs(cmap): cmap.sort() pairs = [] x = y = 0 for i in range(0,len(cmap)): try: if ((cmap[y+1] - cmap[i]) > 1): pairs.append((cmap[x],cmap[y])) x = y = i+1 else: y = y + 1 # if we go off the end, then just add x to y except IndexError: pairs.append((cmap[x],cmap[y])) return pairs # # Convert pairs to range string, e.g: [(1,2),(3,3),(5,7)] -> 1-2,3,5-7 # def format_pairs(pairs): if not pairs: return "no cpus" out = "" for f,s in pairs: if (f==s): out += '%d'%f else: out += '%d-%d'%(f,s) out += ',' # trim trailing ',' return out[:-1] def format_cpumap(cpumap): cpumap = map(lambda x: int(x), cpumap) cpumap.sort() if serverType == SERVER_XEN_API: nr_cpus = len(server.xenapi.host.get_host_CPUs( server.xenapi.session.get_this_host(server.getSession()))) else: for x in server.xend.node.info()[1:]: if len(x) > 1 and x[0] == 'nr_cpus': nr_cpus = int(x[1]) # normalize cpumap by modulus nr_cpus, and drop duplicates cpumap = dict.fromkeys( filter(lambda x: x < nr_cpus, cpumap)).keys() if len(cpumap) == nr_cpus: return "any cpu" return format_pairs(list_to_rangepairs(cpumap)) name = get_info('name') domid = get_info('domid') if domid is not None: domid = str(domid) else: domid = '' for vcpu in sxp.children(dom, 'vcpu'): def vinfo(n, t): return t(sxp.child_value(vcpu, n)) number = vinfo('number', int) cpu = vinfo('cpu', int) cpumap = format_cpumap(vinfo('cpumap', list)) online = vinfo('online', int) cpu_time = vinfo('cpu_time', float) running = vinfo('running', int) blocked = vinfo('blocked', int) if cpu < 0: c = '' s = '' elif online: c = str(cpu) if running: s = 'r' else: s = '-' if blocked: s += 'b' else: s += '-' s += '-' else: c = '-' s = '--p' print format % locals() def start_do_console(domain_name): cpid = os.fork() if cpid != 0: for i in range(10): # Catch failure of the create process time.sleep(1) (p, rv) = os.waitpid(cpid, os.WNOHANG) if os.WIFEXITED(rv): if os.WEXITSTATUS(rv) != 0: sys.exit(os.WEXITSTATUS(rv)) try: # Acquire the console of the created dom if serverType == SERVER_XEN_API: domid = server.xenapi.VM.get_domid( get_single_vm(domain_name)) else: dom = server.xend.domain(domain_name) domid = int(sxp.child_value(dom, 'domid', '-1')) console.execConsole(domid) except: pass print("Could not start console\n"); sys.exit(0) def xm_start(args): paused = False console_autoconnect = False vncviewer = False vncviewer_autopass = False try: (options, params) = getopt.gnu_getopt(args, 'cp', ['console_autoconnect','paused','vncviewer','vncviewer-autopass']) for (k, v) in options: if k in ('-p', '--paused'): paused = True if k in ('-c', '--console_autoconnect'): console_autoconnect = True if k in ('--vncviewer'): vncviewer = True if k in ('--vncviewer-autopass'): vncviewer_autopass = True if len(params) != 1: raise OptionError("Expects 1 argument") except getopt.GetoptError, opterr: err(opterr) usage('start') dom = params[0] if console_autoconnect: start_do_console(dom) try: if serverType == SERVER_XEN_API: server.xenapi.VM.start(get_single_vm(dom), paused) domid = int(server.xenapi.VM.get_domid(get_single_vm(dom))) else: server.xend.domain.start(dom, paused) info = server.xend.domain(dom) domid = int(sxp.child_value(info, 'domid', '-1')) except: raise if domid == -1: raise xmlrpclib.Fault(0, "Domain '%s' is not started" % dom) if vncviewer: console.runVncViewer(domid, vncviewer_autopass, True) def xm_delete(args): arg_check(args, "delete", 1) dom = args[0] if serverType == SERVER_XEN_API: server.xenapi.VM.destroy(get_single_vm(dom)) else: server.xend.domain.delete(dom) def xm_suspend(args): arg_check(args, "suspend", 1) dom = args[0] if serverType == SERVER_XEN_API: server.xenapi.VM.suspend(get_single_vm(dom)) else: server.xend.domain.suspend(dom) def xm_resume(args): arg_check(args, "resume", 1, 2) try: (options, params) = getopt.gnu_getopt(args, 'p', ['paused']) except getopt.GetoptError, opterr: err(opterr) usage('resume') paused = False for (k, v) in options: if k in ['-p', '--paused']: paused = True if len(params) != 1: err("Wrong number of parameters") usage('resume') dom = params[0] if serverType == SERVER_XEN_API: server.xenapi.VM.resume(get_single_vm(dom), paused) else: server.xend.domain.resume(dom, paused) def xm_reboot(args): arg_check(args, "reboot", 1, 3) from xen.xm import shutdown shutdown.main(["shutdown", "-R"] + args) def xm_shutdown(args): arg_check(args, "shutdown", 1, 4) from xen.xm import shutdown shutdown.main(["shutdown"] + args) def xm_reset(args): arg_check(args, "reset", 1) dom = args[0] if serverType == SERVER_XEN_API: server.xenapi.VM.hard_reboot(get_single_vm(dom)) else: server.xend.domain.reset(dom) def xm_pause(args): arg_check(args, "pause", 1) dom = args[0] if serverType == SERVER_XEN_API: server.xenapi.VM.pause(get_single_vm(dom)) server.xenapi.VM.set_pauseflag(get_single_vm(dom), True) else: server.xend.domain.pause(dom) server.xend.domain.setpauseflag(dom, True) def xm_unpause(args): arg_check(args, "unpause", 1) dom = args[0] if serverType == SERVER_XEN_API: server.xenapi.VM.unpause(get_single_vm(dom)) server.xenapi.VM.set_pauseflag(get_single_vm(dom), False) else: server.xend.domain.unpause(dom) server.xend.domain.setpauseflag(dom, False) def xm_dump_core(args): live = False crash = False reset = False try: (options, params) = getopt.gnu_getopt(args, 'LCR', ['live', 'crash', 'reset']) for (k, v) in options: if k in ('-L', '--live'): live = True elif k in ('-C', '--crash'): crash = True elif k in ('-R', '--reset'): reset = True if crash and reset: raise OptionError("You may not specify more than one '-CR' option") if len(params) not in (1, 2): raise OptionError("Expects 1 or 2 argument(s)") except getopt.GetoptError, e: raise OptionError(str(e)) dom = params[0] if len(params) == 2: filename = os.path.abspath(params[1]) else: filename = None print "Dumping core of domain: %s ..." % str(dom) server.xend.domain.dump(dom, filename, live, crash, reset) def xm_rename(args): arg_check(args, "rename", 2) if serverType == SERVER_XEN_API: server.xenapi.VM.set_name_label(get_single_vm(args[0]), args[1]) else: server.xend.domain.setName(args[0], args[1]) def xm_importcommand(command, args): cmd = __import__(command, globals(), locals(), 'xen.xm') cmd.main([command] + args) ############################################################# def xm_vcpu_pin(args): arg_check(args, "vcpu-pin", 3) def cpu_make_map(cpulist): cpus = [] for c in cpulist.split(','): if c == '': continue if c.find('-') != -1: (x,y) = c.split('-') for i in range(int(x),int(y)+1): cpus.append(int(i)) else: # remove this element from the list if c[0] == '^': cpus = [x for x in cpus if x != int(c[1:])] else: cpus.append(int(c)) cpus.sort() return ",".join(map(str, cpus)) dom = args[0] vcpu = args[1] if args[2] == 'all': cpumap = cpu_make_map('0-63') else: cpumap = cpu_make_map(args[2]) if serverType == SERVER_XEN_API: server.xenapi.VM.add_to_VCPUs_params_live( get_single_vm(dom), "cpumap%i" % int(vcpu), cpumap) else: server.xend.domain.pincpu(dom, vcpu, cpumap) def xm_mem_max(args): arg_check(args, "mem-max", 2) dom = args[0] if serverType == SERVER_XEN_API: mem = int_unit(args[1], 'k') * 1024 server.xenapi.VM.set_memory_static_max(get_single_vm(dom), mem) else: mem = int_unit(args[1], 'm') server.xend.domain.maxmem_set(dom, mem) def xm_mem_set(args): arg_check(args, "mem-set", 2) dom = args[0] if serverType == SERVER_XEN_API: mem_target = int_unit(args[1], 'm') * 1024 * 1024 server.xenapi.VM.set_memory_dynamic_max_live(get_single_vm(dom), mem_target) server.xenapi.VM.set_memory_dynamic_min_live(get_single_vm(dom), mem_target) else: mem_target = int_unit(args[1], 'm') server.xend.domain.setMemoryTarget(dom, mem_target) def xm_usb_add(args): arg_check(args, "usb-add", 2) server.xend.domain.usb_add(args[0],args[1]) def xm_domstate(args): arg_check(args, "domstate", 1) (opitons, params) = getopt.gnu_getopt(args, 's', ['domname=']) doms = getDomains(params, 'all') d = parse_doms_info(doms[0]) state = d['state'] if state: if state.find('s') > 0: print 'shutoff' elif state.find('b') > 0: print 'idle' elif state.find('d') > 0: print 'shutdown' elif state.find('r') > 0: print 'running' elif state.find('c') > 0: print 'crashed' elif state.find('p') > 0: if server.xend.domain.getpauseflag(args[0]): print 'paused by admin' else: print 'paused' else: print 'shutoff' return def xm_usb_del(args): arg_check(args, "usb-del", 2) server.xend.domain.usb_del(args[0],args[1]) def xm_vcpu_set(args): arg_check(args, "vcpu-set", 2) dom = args[0] vcpus = int(args[1]) if serverType == SERVER_XEN_API: server.xenapi.VM.set_VCPUs_number_live(get_single_vm(dom), vcpus) else: server.xend.domain.setVCpuCount(dom, vcpus) def xm_destroy(args): arg_check(args, "destroy", 1) dom = args[0] if serverType == SERVER_XEN_API: server.xenapi.VM.hard_shutdown(get_single_vm(dom)) else: server.xend.domain.destroy(dom) def xm_domid(args): arg_check(args, "domid", 1) name = args[0] if serverType == SERVER_XEN_API: print server.xenapi.VM.get_domid(get_single_vm(name)) else: dom = server.xend.domain(name) print sxp.child_value(dom, 'domid') def xm_domname(args): arg_check(args, "domname", 1) name = args[0] if serverType == SERVER_XEN_API: print server.xenapi.VM.get_name_label(get_single_vm(name)) else: dom = server.xend.domain(name) print sxp.child_value(dom, 'name') def xm_sched_sedf(args): xenapi_unsupported() def ns_to_ms(val): return float(val) * 0.000001 def ms_to_ns(val): return (float(val) / 0.000001) def print_sedf(info): info['period'] = ns_to_ms(info['period']) info['slice'] = ns_to_ms(info['slice']) info['latency'] = ns_to_ms(info['latency']) print( ("%(name)-32s %(domid)5d %(period)9.1f %(slice)9.1f" + " %(latency)7.1f %(extratime)6d %(weight)6d") % info) check_sched_type('sedf') # we want to just display current info if no parameters are passed if len(args) == 0: domid = None else: # we expect at least a domain id (name or number) # and at most a domid up to 5 options with values arg_check(args, "sched-sedf", 1, 11) domid = args[0] # drop domid from args since get_opt doesn't recognize it args = args[1:] opts = {} try: (options, params) = getopt.gnu_getopt(args, 'p:s:l:e:w:', ['period=', 'slice=', 'latency=', 'extratime=', 'weight=']) except getopt.GetoptError, opterr: err(opterr) usage('sched-sedf') # convert to nanoseconds if needed for (k, v) in options: if k in ['-p', '--period']: opts['period'] = ms_to_ns(v) elif k in ['-s', '--slice']: opts['slice'] = ms_to_ns(v) elif k in ['-l', '--latency']: opts['latency'] = ms_to_ns(v) elif k in ['-e', '--extratime']: opts['extratime'] = v elif k in ['-w', '--weight']: opts['weight'] = v doms = filter(lambda x : domid_match(domid, x), [parse_doms_info(dom) for dom in getDomains(None, 'running')]) if domid is not None and doms == []: err("Domain '%s' does not exist." % domid) usage('sched-sedf') # print header if we aren't setting any parameters if len(opts.keys()) == 0: print '%-33s %4s %-4s %-4s %-7s %-5s %-6s' % \ ('Name','ID','Period(ms)', 'Slice(ms)', 'Lat(ms)', 'Extra','Weight') for d in doms: # fetch current values so as not to clobber them try: sedf_raw = server.xend.domain.cpu_sedf_get(d['domid']) except xmlrpclib.Fault: # domain does not support sched-sedf? sedf_raw = {} sedf_info = parse_sedf_info(sedf_raw) sedf_info['name'] = d['name'] # update values in case of call to set if len(opts.keys()) > 0: for k in opts.keys(): sedf_info[k]=opts[k] # send the update, converting user input v = map(int, [sedf_info['period'], sedf_info['slice'], sedf_info['latency'],sedf_info['extratime'], sedf_info['weight']]) rv = server.xend.domain.cpu_sedf_set(d['domid'], *v) if int(rv) != 0: err("Failed to set sedf parameters (rv=%d)."%(rv)) # not setting values, display info else: print_sedf(sedf_info) def xm_sched_credit(args): """Get/Set options for Credit Scheduler.""" check_sched_type('credit') try: opts, params = getopt.getopt(args, "d:w:c:", ["domain=", "weight=", "cap="]) except getopt.GetoptError, opterr: err(opterr) usage('sched-credit') domid = None weight = None cap = None for o, a in opts: if o in ["-d", "--domain"]: domid = a elif o in ["-w", "--weight"]: weight = int(a) elif o in ["-c", "--cap"]: cap = int(a); doms = filter(lambda x : domid_match(domid, x), [parse_doms_info(dom) for dom in getDomains(None, 'all')]) if weight is None and cap is None: if domid is not None and doms == []: err("Domain '%s' does not exist." % domid) usage('sched-credit') # print header if we aren't setting any parameters print '%-33s %4s %6s %4s' % ('Name','ID','Weight','Cap') for d in doms: try: if serverType == SERVER_XEN_API: info = server.xenapi.VM_metrics.get_VCPUs_params( server.xenapi.VM.get_metrics( get_single_vm(d['name']))) else: info = server.xend.domain.sched_credit_get(d['name']) except xmlrpclib.Fault: pass if 'weight' not in info or 'cap' not in info: # domain does not support sched-credit? info = {'weight': -1, 'cap': -1} info['weight'] = int(info['weight']) info['cap'] = int(info['cap']) info['name'] = d['name'] info['domid'] = str(d['domid']) print( ("%(name)-32s %(domid)5s %(weight)6d %(cap)4d") % info) else: if domid is None: # place holder for system-wide scheduler parameters err("No domain given.") usage('sched-credit') if serverType == SERVER_XEN_API: if doms[0]['domid']: server.xenapi.VM.add_to_VCPUs_params_live( get_single_vm(domid), "weight", weight) server.xenapi.VM.add_to_VCPUs_params_live( get_single_vm(domid), "cap", cap) else: server.xenapi.VM.add_to_VCPUs_params( get_single_vm(domid), "weight", weight) server.xenapi.VM.add_to_VCPUs_params( get_single_vm(domid), "cap", cap) else: result = server.xend.domain.sched_credit_set(domid, weight, cap) if result != 0: err(str(result)) def xm_sched_credit2(args): """Get/Set options for Credit2 Scheduler.""" check_sched_type('credit2') try: opts, params = getopt.getopt(args, "d:w:", ["domain=", "weight="]) except getopt.GetoptError, opterr: err(opterr) usage('sched-credit2') domid = None weight = None for o, a in opts: if o in ["-d", "--domain"]: domid = a elif o in ["-w", "--weight"]: weight = int(a) doms = filter(lambda x : domid_match(domid, x), [parse_doms_info(dom) for dom in getDomains(None, 'all')]) if weight is None: if domid is not None and doms == []: err("Domain '%s' does not exist." % domid) usage('sched-credit2') # print header if we aren't setting any parameters print '%-33s %4s %6s' % ('Name','ID','Weight') for d in doms: try: if serverType == SERVER_XEN_API: info = server.xenapi.VM_metrics.get_VCPUs_params( server.xenapi.VM.get_metrics( get_single_vm(d['name']))) else: info = server.xend.domain.sched_credit2_get(d['name']) except xmlrpclib.Fault: pass if 'weight' not in info: # domain does not support sched-credit2? info = {'weight': -1} info['weight'] = int(info['weight']) info['name'] = d['name'] info['domid'] = str(d['domid']) print( ("%(name)-32s %(domid)5s %(weight)6d") % info) else: if domid is None: # place holder for system-wide scheduler parameters err("No domain given.") usage('sched-credit2') if serverType == SERVER_XEN_API: if doms[0]['domid']: server.xenapi.VM.add_to_VCPUs_params_live( get_single_vm(domid), "weight", weight) else: server.xenapi.VM.add_to_VCPUs_params( get_single_vm(domid), "weight", weight) else: result = server.xend.domain.sched_credit2_set(domid, weight) if result != 0: err(str(result)) def xm_info(args): arg_check(args, "info", 0, 1) try: (options, params) = getopt.gnu_getopt(args, 'cn', ['config','numa']) except getopt.GetoptError, opterr: err(opterr) usage('info') show_xend_config = 0 show_numa_topology = 0 for (k, v) in options: if k in ['-c', '--config']: show_xend_config = 1 if k in ['-n', '--numa']: show_numa_topology = 1 if show_xend_config: for name, obj in inspect.getmembers(xoptions): if not inspect.ismethod(obj): if name == "config": for x in obj[1:]: if len(x) < 2: print "%-38s: (none)" % x[0] else: print "%-38s:" % x[0], x[1] else: print "%-38s:" % name, obj return if serverType == SERVER_XEN_API: # Need to fake out old style xm info as people rely on parsing it host_record = server.xenapi.host.get_record( server.xenapi.session.get_this_host(server.getSession())) host_cpu_records = map(server.xenapi.host_cpu.get_record, host_record["host_CPUs"]) host_metrics_record = server.xenapi.host_metrics.get_record(host_record["metrics"]) def getVal(keys, default=""): data = host_record for key in keys: if key in data: data = data[key] else: return default return data def getCpuMhz(): cpu_speeds = [int(host_cpu_record["speed"]) for host_cpu_record in host_cpu_records if "speed" in host_cpu_record] if len(cpu_speeds) > 0: return sum(cpu_speeds) / len(cpu_speeds) else: return 0 getCpuMhz() def getCpuFeatures(): if len(host_cpu_records) > 0: return host_cpu_records[0].get("features", "") else: return "" def getFreeCpuCount(): cnt = 0 for host_cpu_record in host_cpu_records: if len(host_cpu_record.get("cpu_pool", [])) == 0: cnt += 1 return cnt info = { "host": getVal(["name_label"]), "release": getVal(["software_version", "release"]), "version": getVal(["software_version", "version"]), "machine": getVal(["software_version", "machine"]), "nr_cpus": getVal(["cpu_configuration", "nr_cpus"]), "nr_nodes": getVal(["cpu_configuration", "nr_nodes"]), "cores_per_socket": getVal(["cpu_configuration", "cores_per_socket"]), "threads_per_core": getVal(["cpu_configuration", "threads_per_core"]), "cpu_mhz": getCpuMhz(), "hw_caps": getCpuFeatures(), "free_cpus": getFreeCpuCount(), "total_memory": int(host_metrics_record["memory_total"])/1024/1024, "free_memory": int(host_metrics_record["memory_free"])/1024/1024, "xen_major": getVal(["software_version", "xen_major"]), "xen_minor": getVal(["software_version", "xen_minor"]), "xen_extra": getVal(["software_version", "xen_extra"]), "xen_caps": " ".join(getVal(["capabilities"], [])), "xen_scheduler": getVal(["sched_policy"]), "xen_pagesize": getVal(["other_config", "xen_pagesize"]), "platform_params": getVal(["other_config", "platform_params"]), "xen_commandline": getVal(["other_config", "xen_commandline"]), "xen_changeset": getVal(["software_version", "xen_changeset"]), "cc_compiler": getVal(["software_version", "cc_compiler"]), "cc_compile_by": getVal(["software_version", "cc_compile_by"]), "cc_compile_domain": getVal(["software_version", "cc_compile_domain"]), "cc_compile_date": getVal(["software_version", "cc_compile_date"]), "xend_config_format":getVal(["software_version", "xend_config_format"]) } sorted = info.items() sorted.sort(lambda (x1,y1), (x2,y2): -cmp(x1,x2)) for (k, v) in sorted: print "%-23s:" % k, v else: info = server.xend.node.info(show_numa_topology) for x in info[1:]: if len(x) < 2: print "%-23s: (none)" % x[0] else: print "%-23s:" % x[0], x[1] def xm_console(args): arg_check(args, "console", 1, 3) num = 0 quiet = False; try: (options, params) = getopt.gnu_getopt(args, 'qn:', ['quiet', 'num']) except getopt.GetoptError, opterr: err(opterr) usage('console') for (k, v) in options: if k in ['-q', '--quiet']: quiet = True elif k in ['-n', '--num']: num = int(v[0]) else: assert False if len(params) != 1: err('No domain given') usage('console') dom = params[0] try: if serverType == SERVER_XEN_API: domid = int(server.xenapi.VM.get_domid(get_single_vm(dom))) else: info = server.xend.domain(dom) domid = int(sxp.child_value(info, 'domid', '-1')) except: if quiet: sys.exit(1) else: raise if domid == -1: if quiet: sys.exit(1) else: raise xmlrpclib.Fault(0, "Domain '%s' is not started" % dom) console.execConsole(domid, num) def domain_name_to_domid(domain_name): if serverType == SERVER_XEN_API: domid = server.xenapi.VM.get_domid( get_single_vm(domain_name)) else: dom = server.xend.domain(domain_name) domid = int(sxp.child_value(dom, 'domid', '-1')) return int(domid) def xm_vncviewer(args): autopass = False; try: (options, params) = getopt.gnu_getopt(args, '', ['autopass','vncviewer-autopass']) except getopt.GetoptError, opterr: err(opterr) usage('vncviewer') for (k, v) in options: if k in ['--autopass','--vncviewer-autopass']: autopass = True else: assert False if len(params) != 1: err('No domain given (or several parameters specified)') usage('vncviewer') dom = params[0] domid = domain_name_to_domid(dom) console.runVncViewer(domid, autopass) def xm_uptime(args): short_mode = 0 try: (options, params) = getopt.gnu_getopt(args, 's', ['short']) except getopt.GetoptError, opterr: err(opterr) usage('uptime') for (k, v) in options: if k in ['-s', '--short']: short_mode = 1 doms = getDomains(params, 'all') if short_mode == 0: print '%-33s %4s %s ' % ('Name','ID','Uptime') for dom in doms: d = parse_doms_info(dom) if d['domid'] == '': uptime = 0 elif int(d['domid']) > 0: uptime = int(round(d['up_time'])) else: f=open('/proc/uptime', 'r') upfile = f.read() uptime = int(round(float(upfile.split(' ')[0]))) f.close() days = int(uptime / 86400) uptime -= (days * 86400) hours = int(uptime / 3600) uptime -= (hours * 3600) minutes = int(uptime / 60) uptime -= (minutes * 60) seconds = uptime upstring = "" if days > 0: upstring += str(days) + " day" if days > 1: upstring += "s" upstring += ", " upstring += '%(hours)2d:%(minutes)02d' % vars() if short_mode: now = datetime.datetime.now() upstring = now.strftime(" %H:%M:%S") + " up " + upstring upstring += ", " + d['name'] + " (" + d['domid'] + ")" else: upstring += ':%(seconds)02d' % vars() upstring = ("%(name)-32s %(domid)5s " % d) + upstring print upstring def xm_sysrq(args): arg_check(args, "sysrq", 2) dom = args[0] req = args[1] if serverType == SERVER_XEN_API: server.xenapi.VM.send_sysrq(get_single_vm(dom), req) else: server.xend.domain.send_sysrq(dom, req) def xm_trigger(args): vcpu = 0 arg_check(args, "trigger", 2, 3) dom = args[0] trigger = args[1] if len(args) == 3: vcpu = int(args[2]) if serverType == SERVER_XEN_API: server.xenapi.VM.send_trigger(get_single_vm(dom), trigger, vcpu) else: server.xend.domain.send_trigger(dom, trigger, vcpu) def xm_debug_keys(args): arg_check(args, "debug-keys", 1) keys = str(args[0]) if serverType == SERVER_XEN_API: server.xenapi.host.send_debug_keys( server.xenapi.session.get_this_host(server.getSession()), keys) else: server.xend.node.send_debug_keys(keys) def xm_top(args): arg_check(args, "top", 0) os.system('xentop') def xm_dmesg(args): arg_check(args, "dmesg", 0, 1) try: (options, params) = getopt.gnu_getopt(args, 'c', ['clear']) except getopt.GetoptError, opterr: err(opterr) usage('dmesg') use_clear = 0 for (k, v) in options: if k in ['-c', '--clear']: use_clear = 1 if len(params) : err("No parameter required") usage('dmesg') if serverType == SERVER_XEN_API: host = server.xenapi.session.get_this_host(server.getSession()) if use_clear: print server.xenapi.host.dmesg_clear(host), else: print server.xenapi.host.dmesg(host), else: if not use_clear: print server.xend.node.dmesg.info(), else: print server.xend.node.dmesg.clear(), def xm_log(args): arg_check(args, "log", 0) if serverType == SERVER_XEN_API: print server.xenapi.host.get_log( server.xenapi.session.get_this_host(server.getSession())) else: print server.xend.node.log() def xm_serve(args): if serverType == SERVER_XEN_API: print "Not supported with XenAPI" sys.exit(-1) arg_check(args, "serve", 0) from fcntl import fcntl, F_SETFL s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) s.connect(XendClient.XML_RPC_SOCKET) fcntl(sys.stdin, F_SETFL, os.O_NONBLOCK) while True: iwtd, owtd, ewtd = select([sys.stdin, s], [], []) if s in iwtd: data = s.recv(4096) if len(data) > 0: sys.stdout.write(data) sys.stdout.flush() else: break if sys.stdin in iwtd: data = sys.stdin.read(4096) if len(data) > 0: s.sendall(data) else: break s.close() def parse_dev_info(info): def get_info(n, t, d): i = 0 while i < len(info): if (info[i][0] == n): return t(info[i][1]) i = i + 1 return t(d) return { #common 'backend-id' : get_info('backend-id', int, -1), 'handle' : get_info('handle', int, 0), 'state' : get_info('state', int, -1), 'be-path' : get_info('backend', str, '??'), 'event-ch' : get_info('event-channel',int, -1), #network specific 'virtual-device' : get_info('virtual-device', str, '??'), 'tx-ring-ref': get_info('tx-ring-ref', int, -1), 'rx-ring-ref': get_info('rx-ring-ref', int, -1), 'mac' : get_info('mac', str, '??'), #block-device specific 'ring-ref' : get_info('ring-ref', int, -1), #vscsi specific 'feature-host' : get_info('feature-host', int, -1), } def arg_check_for_resource_list(args, name): use_long = 0 try: (options, params) = getopt.gnu_getopt(args, 'l', ['long']) except getopt.GetoptError, opterr: err(opterr) usage(name) for (k, v) in options: if k in ['-l', '--long']: use_long = 1 if len(params) == 0: print 'No domain parameter given' usage(name) if len(params) > 1: print 'No multiple domain parameters allowed' usage(name) return (use_long, params) def xm_network_list(args): (use_long, params) = arg_check_for_resource_list(args, "network-list") dom = params[0] if serverType == SERVER_XEN_API: vif_refs = server.xenapi.VM.get_VIFs(get_single_vm(dom)) vif_properties = [] for vif_ref in vif_refs: vif_property = server.xenapi.VIF.get_runtime_properties(vif_ref) vif_property['mac'] = server.xenapi.VIF.get_MAC(vif_ref) vif_properties.append(vif_property) devs = map(lambda (handle, properties): [handle, map2sxp(properties)], zip(range(len(vif_properties)), vif_properties)) else: devs = server.xend.domain.getDeviceSxprs(dom, 'vif') if use_long: map(PrettyPrint.prettyprint, devs) else: hdr = 0 for x in devs: if hdr == 0: print 'Idx BE MAC Addr. handle state evt-ch tx-/rx-ring-ref BE-path' hdr = 1 ni = parse_dev_info(x[1]) ni['idx'] = int(x[0]) print ("%(idx)-3d " "%(backend-id)-3d" "%(mac)-17s " "%(handle)-3d " "%(state)-3d " "%(event-ch)-3d " "%(tx-ring-ref)-5d/%(rx-ring-ref)-5d " "%(be-path)-30s " % ni) def xm_block_list(args): (use_long, params) = arg_check_for_resource_list(args, "block-list") dom = params[0] if serverType == SERVER_XEN_API: vbd_refs = server.xenapi.VM.get_VBDs(get_single_vm(dom)) vbd_properties = \ map(server.xenapi.VBD.get_runtime_properties, vbd_refs) vbd_devs = \ map(server.xenapi.VBD.get_device, vbd_refs) vbd_devids = [blkdev_name_to_number(x)[1] for x in vbd_devs] devs = map(lambda (devid, prop): [devid, map2sxp(prop)], zip(vbd_devids, vbd_properties)) else: devs = server.xend.domain.getDeviceSxprs(dom, 'vbd') if use_long: map(PrettyPrint.prettyprint, devs) else: hdr = 0 for x in devs: if hdr == 0: print 'Vdev BE handle state evt-ch ring-ref BE-path' hdr = 1 ni = parse_dev_info(x[1]) ni['idx'] = int(x[0]) print ("%(idx)-5d " "%(backend-id)-3d " "%(handle)-3d " "%(state)-3d " "%(event-ch)-3d " "%(ring-ref)-5d " "%(be-path)-30s " % ni) def attached_pci_dict_bin(dom): devs = [] if serverType == SERVER_XEN_API: for dpci_ref in server.xenapi.VM.get_DPCIs(get_single_vm(dom)): ppci_ref = server.xenapi.DPCI.get_PPCI(dpci_ref) ppci_record = server.xenapi.PPCI.get_record(ppci_ref) dev = { 'domain': int(ppci_record['domain']), 'bus': int(ppci_record['bus']), 'slot': int(ppci_record['slot']), 'func': int(ppci_record['func']), 'vdevfn': int(server.xenapi.DPCI.get_hotplug_slot(dpci_ref)), 'key': server.xenapi.DPCI.get_key(dpci_ref) } devs.append(dev) else: for x in server.xend.domain.getDeviceSxprs(dom, 'pci'): dev = { 'domain': int(x['domain'], 16), 'bus': int(x['bus'], 16), 'slot': int(x['slot'], 16), 'func': int(x['func'], 16), 'vdevfn': int(x['vdevfn'], 16), 'key': x['key'] } devs.append(dev) return devs def pci_dict_bin_to_str(pci_dev): new_dev = pci_dev.copy() new_dev['domain'] = '0x%04x' % pci_dev['domain'] new_dev['bus'] = '0x%02x' % pci_dev['bus'] new_dev['slot'] = '0x%02x' % pci_dev['slot'] new_dev['func'] = '0x%x' % pci_dev['func'] new_dev['vdevfn'] = '0x%02x' % pci_dev['vdevfn'] return new_dev def attached_pci_dict(dom): return map(pci_dict_bin_to_str, attached_pci_dict_bin(dom)) def xm_pci_list(args): (use_long, params) = arg_check_for_resource_list(args, "pci-list") devs = attached_pci_dict_bin(params[0]) if len(devs) == 0: return devs.sort(None, lambda x: (x['vdevfn'] - PCI_FUNC(x['vdevfn'])) << 32 | PCI_BDF(x['domain'], x['bus'], x['slot'], x['func'])) has_vdevfn = False for x in devs: if x['vdevfn'] & AUTO_PHP_SLOT: x['show_vdevfn'] = '-' else: x['show_vdevfn'] = "%02x.%01x" % (PCI_SLOT(x['vdevfn']), PCI_FUNC(x['vdevfn'])) has_vdevfn = True hdr_str = 'Device' fmt_str = '%(domain)04x:%(bus)02x:%(slot)02x.%(func)x' if has_vdevfn: hdr_str = 'Vdev ' + hdr_str fmt_str = '%(show_vdevfn)-4s ' + fmt_str print hdr_str for x in devs: print fmt_str % x def parse_pci_info(info): def get_info(n, t, d): return t(sxp.child_value(info, n, d)) return { 'domain' : get_info('domain', parse_hex, 0), 'bus' : get_info('bus', parse_hex, -1), 'slot' : get_info('slot', parse_hex, -1), 'func' : get_info('func', parse_hex, -1) } def xm_pci_list_assignable_devices(args): xenapi_unsupported() arg_check(args, "pci-list-assignable-devices", 0) devs = server.xend.node.pciinfo() if devs is None: print "Error: pciback/pci-stub not loaded?" return fmt_str = "%(domain)04x:%(bus)02x:%(slot)02x.%(func)01x" for x in devs: pci = parse_pci_info(x) print fmt_str % pci def vscsi_sort(devs): def sort_hctl(ds, l): s = [] for d1 in ds: for d2 in d1: v_dev = sxp.child_value(d2, 'v-dev') n = int(v_dev.split(':')[l]) try: j = s[n] except IndexError: j = [] s.extend([ [] for _ in range(len(s), n+1) ]) j.append(d2) s[n] = j return s for i in range(len(devs)): ds1 = [ devs[i][1][0][1] ] ds1 = sort_hctl(ds1, 3) ds1 = sort_hctl(ds1, 2) ds1 = sort_hctl(ds1, 1) ds2 = [] for d in ds1: ds2.extend(d) devs[i][1][0][1] = ds2 return devs def vscsi_convert_sxp_to_dict(dev_sxp): dev_dict = {} for opt_val in dev_sxp[1:]: try: opt, val = opt_val dev_dict[opt] = val except TypeError: pass return dev_dict def xm_scsi_list(args): (use_long, params) = arg_check_for_resource_list(args, "scsi-list") dom = params[0] devs = [] if serverType == SERVER_XEN_API: dscsi_refs = server.xenapi.VM.get_DSCSIs(get_single_vm(dom)) dscsi_properties = \ map(server.xenapi.DSCSI.get_runtime_properties, dscsi_refs) dscsi_dict = {} for dscsi_property in dscsi_properties: devid = int(dscsi_property['dev']['devid']) try: dscsi_sxp = dscsi_dict[devid] except: dscsi_sxp = [['devs', []]] for key, value in dscsi_property.items(): if key != 'dev': dscsi_sxp.append([key, value]) dev_sxp = ['dev'] dev_sxp.extend(map2sxp(dscsi_property['dev'])) dscsi_sxp[0][1].append(dev_sxp) dscsi_dict[devid] = dscsi_sxp devs = map2sxp(dscsi_dict) else: devs = server.xend.domain.getDeviceSxprs(dom, 'vscsi') # Sort devs by virtual HCTL. devs = vscsi_sort(devs) if use_long: map(PrettyPrint.prettyprint, devs) else: hdr = 0 for x in devs: if hdr == 0: print "%-3s %-3s %-5s %-4s %-10s %-5s %-10s %-4s" \ % ('Idx', 'BE', 'state', 'host', 'phy-hctl', 'phy', 'vir-hctl', 'devstate') hdr = 1 ni = parse_dev_info(x[1]) ni['idx'] = int(x[0]) for dev in x[1][0][1]: mi = vscsi_convert_sxp_to_dict(dev) print "%(idx)-3d %(backend-id)-3d %(state)-5d %(feature-host)-4d " % ni, print "%(p-dev)-10s %(p-devname)-5s %(v-dev)-10s %(frontstate)-4s" % mi def xm_usb_list(args): xenapi_unsupported() arg_check(args, 'usb-list', 1) dom = args[0] devs = server.xend.domain.getDeviceSxprs(dom, 'vusb') for x in devs: print "%-3s %-3s %-5s %-7s %-30s" \ % ('Idx', 'BE', 'state', 'usb-ver', 'BE-path') ni = parse_dev_info(x[1]) ni['idx'] = int(x[0]) usbver = sxp.child_value(x[1], 'usb-ver') if int(usbver) == 1: ni['usb-ver'] = 'USB1.1' else: ni['usb-ver'] = 'USB2.0' print "%(idx)-3d %(backend-id)-3d %(state)-5d %(usb-ver)-7s %(be-path)-30s " % ni ports = sxp.child(x[1], 'port') for port in ports[1:]: try: num, bus = port if bus != "" and vusb_util.usb_device_is_connected(bus): idvendor = vusb_util.get_usb_idvendor(bus) idproduct = vusb_util.get_usb_idproduct(bus) prodinfo = vusb_util.get_usbdevice_info(bus) print "port %i: %s [ID %-4s:%-4s %s]" \ % (int(num), str(bus), idvendor, idproduct, prodinfo) else: print "port %i: " % int(num) + str(bus) except TypeError: pass def xm_usb_list_assignable_devices(args): xenapi_unsupported() arg_check(args, 'usb-list-assignable-devices', 0) usb_devs = vusb_util.get_usb_devices() buses = vusb_util.get_assigned_buses() for x in buses: try: usb_devs.remove(x) except ValueError: pass for dev in usb_devs: idvendor = vusb_util.get_usb_idvendor(dev) idproduct = vusb_util.get_usb_idproduct(dev) prodinfo = vusb_util.get_usbdevice_info(dev) print "%-13s: ID %-4s:%-4s %s" \ % (dev, idvendor, idproduct, prodinfo) def parse_block_configuration(args): dom = args[0] if args[1].startswith('tap2:'): cls = 'tap2' elif args[1].startswith('tap:'): cls = 'tap' else: cls = 'vbd' vbd = [cls, ['uname', args[1]], ['dev', args[2]], ['mode', args[3]]] if len(args) == 5: vbd.append(['backend', args[4]]) return (dom, vbd) def xm_block_attach(args): arg_check(args, 'block-attach', 4, 5) if serverType == SERVER_XEN_API: dom = args[0] uname = args[1] dev = args[2] mode = args[3] # First create new VDI vdi_record = { "name_label": "vdi" + str(uname.__hash__()), "name_description": "", "SR": get_default_SR(), "virtual_size": 0, "sector_size": 512, "type": "system", "sharable": False, "read_only": mode!="w", "other_config": {"location": uname} } vdi_ref = server.xenapi.VDI.create(vdi_record) # Now create new VBD vbd_record = { "VM": get_single_vm(dom), "VDI": vdi_ref, "device": dev, "bootable": True, "mode": mode=="w" and "RW" or "RO", "type": "Disk", "qos_algorithm_type": "", "qos_algorithm_params": {} } server.xenapi.VBD.create(vbd_record) else: (dom, vbd) = parse_block_configuration(args) server.xend.domain.device_create(dom, vbd) def xm_block_configure(args): arg_check(args, 'block-configure', 4, 5) (dom, vbd) = parse_block_configuration(args) server.xend.domain.device_configure(dom, vbd) def xm_network2_attach(args): xenapi_unsupported() arg_check(args, 'network2-attach', 1, 11) dom = args[0] vif = ['vif2'] vif_params = ['front_mac', 'back_mac', 'backend', 'trusted', 'back_trusted', "front_filter_mac", "filter_mac", 'bridge', 'pdev', "max_bypasses" ] for a in args[1:]: vif_param = a.split("=") if len(vif_param) != 2 or vif_param[1] == "" or \ vif_param[0] not in vif_params: err("Invalid argument: %s" % a) usage("network2-attach") vif.append(vif_param) server.xend.domain.device_create(dom, vif) def xm_network2_detach(args): xenapi_unsupported() arg_check(args, "network2-detach", 2, 3) detach(args, "vif2") def xm_network2_list(args): xenapi_unsupported() (use_long, params) = arg_check_for_resource_list(args, "network2-list") dom = params[0] devs = server.xend.domain.getDeviceSxprs(dom, 'vif2') map(PrettyPrint.prettyprint, devs) def xm_network_attach(args): arg_check(args, 'network-attach', 1, 11) dom = args[0] vif = ['vif'] vif_params = ['type', 'mac', 'bridge', 'ip', 'script', \ 'backend', 'vifname', 'rate', 'model', 'accel'] if serverType == SERVER_XEN_API: vif_record = { "device": "eth0", "network": get_default_Network(), "VM": get_single_vm(dom), "MAC": "", "MTU": "", "qos_algorithm_type": "", "qos_algorithm_params": {}, "other_config": {} } def set(keys, val): record = vif_record for key in keys[:-1]: record = record[key] record[keys[-1]] = val def get_net_from_bridge(bridge): # In OSS, we just assert network.name_label == bridge name networks = dict([(record['name_label'], ref) for ref, record in server.xenapi.network .get_all_records().items()]) if bridge not in networks.keys(): raise ValueError("Unknown bridge name!") return networks[bridge] vif_conv = { 'type': lambda x: None, 'mac': lambda x: set(['MAC'], x), 'bridge': lambda x: set(['network'], get_net_from_bridge(x)), 'ip': lambda x: set(['other_config', 'ip'], x), 'script': lambda x: set(['other_config', 'script'], x), 'backend': lambda x: set(['other_config', 'backend'], x), 'vifname': lambda x: set(['device'], x), 'rate': lambda x: set(['qos_algorithm_params', 'rate'], x), 'model': lambda x: None, 'accel': lambda x: set(['other_config', 'accel'], x) } for a in args[1:]: vif_param = a.split("=") if len(vif_param) != 2 or vif_param[1] == '' or \ vif_param[0] not in vif_params: err("Invalid argument: %s" % a) usage('network-attach') else: vif_conv[vif_param[0]](vif_param[1]) server.xenapi.VIF.create(vif_record) else: for a in args[1:]: vif_param = a.split("=") if len(vif_param) != 2 or vif_param[1] == '' or \ vif_param[0] not in vif_params: err("Invalid argument: %s" % a) usage('network-attach') vif.append(vif_param) server.xend.domain.device_create(dom, vif) def parse_pci_configuration(args, opts = ''): dom = args[0] pci_dev_str = args[1] if len(args) == 3: pci_dev_str += '@' + args[2] if len(opts) > 0: pci_dev_str += ',' + serialise_pci_opts(opts) try: pci_dev = parse_pci_name_extended(pci_dev_str) except PciDeviceParseError, ex: raise OptionError(str(ex)) return (dom, pci_dev) def xm_pci_attach(args): config_pci_opts = [] (options, params) = getopt.gnu_getopt(args, 'o:', ['options=']) for (k, v) in options: if k in ('-o', '--options'): if len(v.split('=')) != 2: err("Invalid pci attach option: %s" % v) usage('pci-attach') config_pci_opts.append(v.split('=')) n = len([i for i in params if i != '--']) if n < 2 or n > 3: err("Invalid argument for 'xm pci-attach'") usage('pci-attach') (dom, dev) = parse_pci_configuration(params, config_pci_opts) attached = attached_pci_dict(dom) attached_dev = map(lambda x: find_attached(attached, x, False), dev) head_dev = dev.pop(0) xm_pci_attach_one(dom, head_dev) # That is all for single-function virtual devices if len(dev) == 0: return # If the slot wasn't spefified in the args then use the slot # assigned to the head by qemu-xen for the rest of the functions if int(head_dev['vdevfn'], 16) & AUTO_PHP_SLOT: vdevfn = int(find_attached_devfn(attached_pci_dict(dom), head_dev), 16) if not vdevfn & AUTO_PHP_SLOT: vslot = PCI_SLOT(vdevfn) for i in dev: i['vdevfn'] = '0x%02x' % \ PCI_DEVFN(vslot, PCI_FUNC(int(i['vdevfn'], 16))) for i in dev: xm_pci_attach_one(dom, i) def xm_pci_attach_one(dom, pci_dev): if serverType == SERVER_XEN_API: name = pci_dict_to_bdf_str(pci_dev) target_ref = None for ppci_ref in server.xenapi.PPCI.get_all(): if name == server.xenapi.PPCI.get_name(ppci_ref): target_ref = ppci_ref break if target_ref is None: raise OptionError("Device %s not found" % name) dpci_record = { "VM": get_single_vm(dom), "PPCI": target_ref, "hotplug_slot": int(pci_dev['vdevfn'], 16), "options": dict(pci_dev.get('opts', [])), "key": pci_dev['key'] } server.xenapi.DPCI.create(dpci_record) else: pci = pci_convert_dict_to_sxp(pci_dev, 'Initialising') server.xend.domain.device_configure(dom, pci) def parse_scsi_configuration(p_scsi, v_hctl, state): def get_devid(hctl): return int(hctl.split(':')[0]) host_mode = 0 scsi_devices = None if p_scsi is not None: # xm scsi-attach if v_hctl == "host": host_mode = 1 scsi_devices = vscsi_util.vscsi_get_scsidevices() elif len(v_hctl.split(':')) != 4: raise OptionError("Invalid argument: %s" % v_hctl) (p_hctl, devname) = \ vscsi_util.vscsi_get_hctl_and_devname_by(p_scsi, scsi_devices) if p_hctl is None: raise OptionError("Cannot find device '%s'" % p_scsi) if host_mode: scsi_info = [] devid = get_devid(p_hctl) for pHCTL, devname, _, _ in scsi_devices: if get_devid(pHCTL) == devid: scsi_info.append([devid, pHCTL, devname, pHCTL]) else: scsi_info = [[get_devid(v_hctl), p_hctl, devname, v_hctl]] else: # xm scsi-detach if len(v_hctl.split(':')) != 4: raise OptionError("Invalid argument: %s" % v_hctl) scsi_info = [[get_devid(v_hctl), None, None, v_hctl]] scsi = ['vscsi', ['feature-host', host_mode]] for devid, pHCTL, devname, vHCTL in scsi_info: scsi.append(['dev', \ ['state', state], \ ['devid', devid], \ ['p-dev', pHCTL], \ ['p-devname', devname], \ ['v-dev', vHCTL] \ ]) return scsi def xm_scsi_attach(args): arg_check(args, 'scsi-attach', 3, 4) dom = args[0] p_scsi = args[1] v_hctl = args[2] scsi = parse_scsi_configuration(p_scsi, v_hctl, xenbusState['Initialising']) if serverType == SERVER_XEN_API: scsi_dev = sxp.children(scsi, 'dev')[0] if sxp.child_value(scsi, 'feature-host'): p_host = sxp.child_value(scsi_dev, 'devid') target_ref = None for pscsi_ref in server.xenapi.PSCSI_HBA.get_all(): if p_host == int(server.xenapi.PSCSI_HBA.get_physical_host(pscsi_ref)): target_ref = pscsi_ref break if target_ref is None: raise OptionError("Cannot find device '%s'" % p_scsi) dscsi_record = { "VM": get_single_vm(dom), "PSCSI_HBA": target_ref, "assignment_mode": "HOST" } server.xenapi.DSCSI_HBA.create(dscsi_record) else: p_hctl = sxp.child_value(scsi_dev, 'p-dev') target_ref = None for pscsi_ref in server.xenapi.PSCSI.get_all(): if p_hctl == server.xenapi.PSCSI.get_physical_HCTL(pscsi_ref): target_ref = pscsi_ref break if target_ref is None: raise OptionError("Cannot find device '%s'" % p_scsi) dscsi_record = { "VM": get_single_vm(dom), "PSCSI": target_ref, "virtual_HCTL": v_hctl } server.xenapi.DSCSI.create(dscsi_record) else: if len(args) == 4: scsi.append(['backend', args[3]]) server.xend.domain.device_configure(dom, scsi) def xm_usb_attach(args): xenapi_unsupported() arg_check(args, 'usb-attach', 4) dom = args[0] dev = args[1] port = args[2] bus = args[3] dev_exist = 0 num_ports = 0 devs = server.xend.domain.getDeviceSxprs(dom, 'vusb') for x in devs: if int(x[0]) == int(dev): dev_exist = 1 num_ports = sxp.child_value(x[1], 'num-ports') if dev_exist == 0: print "Cannot find device '%s' in domain '%s'" % (dev,dom) return False if int(port) < 1 or int(port) > int(num_ports): print "Invalid Port Number '%s'" % port return False bus_match = re.match(r"(^(?P<bus>[0-9]{1,2})[-,])" + \ r"(?P<root_port>[0-9]{1,2})" + \ r"(?P<port>([\.,]{1}[0-9]{1,2}){0,5})$", bus) if bus_match is None: print "Invalid Busid '%s'" % bus return False if vusb_util.bus_is_assigned(bus): print "Cannot assign already attached bus '%s', detach first." % bus return False prev_bus = vusb_util.get_assigned_bus(domain_name_to_domid(dom), dev, port) if not prev_bus == "": print "Cannot override already attached port '%s', detach first." % port return False usb = ['vusb', ['port', [port, str(bus)]]] server.xend.domain.device_configure(dom, usb, dev) def xm_usb_hc_create(args): xenapi_unsupported() arg_check(args, 'usb-hc-create', 3) dom = args[0] ver = args[1] num = args[2] vusb_config = ['vusb'] vusb_config.append(['usb-ver', str(ver)]) vusb_config.append(['num-ports', str(num)]) port_config = ['port'] for i in range(1, int(num) + 1): port_config.append(['%i' % i, ""]) vusb_config.append(port_config) server.xend.domain.device_create(dom, vusb_config) def detach(args, deviceClass): rm_cfg = True dom = args[0] dev = args[1] try: force = args[2] if (force != "--force") and (force != "-f"): print "Ignoring option %s"%(force) force = None except IndexError: force = None server.xend.domain.destroyDevice(dom, deviceClass, dev, force, rm_cfg) def xm_block_detach(args): if serverType == SERVER_XEN_API: arg_check(args, "block-detach", 2, 3) dom = args[0] dev = args[1] vbd_refs = server.xenapi.VM.get_VBDs(get_single_vm(dom)) vbd_refs = [vbd_ref for vbd_ref in vbd_refs if server.xenapi.VBD.get_device(vbd_ref) == dev] if len(vbd_refs) > 0: vbd_ref = vbd_refs[0] vdi_ref = server.xenapi.VBD.get_VDI(vbd_ref) server.xenapi.VBD.destroy(vbd_ref) if len(server.xenapi.VDI.get_VBDs(vdi_ref)) <= 0: server.xenapi.VDI.destroy(vdi_ref) else: raise OptionError("Cannot find device '%s' in domain '%s'" % (dev,dom)) else: arg_check(args, 'block-detach', 2, 3) dom = args[0] dev = args[1] dc = server.xend.domain.getBlockDeviceClass(dom, dev) if dc == "tap2": detach(args, 'tap2') elif dc == "tap": detach(args, 'tap') else: detach(args, 'vbd') def xm_network_detach(args): arg_check(args, "network-detach", 2, 3) dom = args[0] devid = args[1] if serverType == SERVER_XEN_API: vif_refs = server.xenapi.VM.get_VIFs(get_single_vm(dom)) if len(devid.split(":")) == 6: mac = devid.lower() vif_refs = [vif_ref for vif_ref in vif_refs if server.xenapi.VIF.\ get_record(vif_ref)["MAC"].lower() == mac] else: vif_refs = [vif_ref for vif_ref in vif_refs if server.xenapi.VIF.\ get_runtime_properties(vif_ref)["handle"] == devid] if len(vif_refs) > 0: vif_ref = vif_refs[0] server.xenapi.VIF.destroy(vif_ref) else: raise OptionError("Cannot find device '%s' in domain '%s'" % (devid, dom)) else: if len(devid.split(":")) == 6: mac = devid.lower() vifs = server.xend.domain.getDeviceSxprs(dom, "vif") devids = [vif[0] for vif in vifs if parse_dev_info(vif[1])["mac"].lower() == mac] if len(devids) > 0: devid = str(devids[0]) else: raise OptionError("Cannot find device '%s' in domain '%s'" % (devid, dom)) vif_args = [dom, devid] try: vif_args.append(args[2]) except IndexError: pass detach(vif_args, 'vif') def find_attached(attached, key, detaching): l = filter(lambda dev: pci_dict_cmp(dev, key), attached) if detaching: if len(l) == 0: raise OptionError("pci: device %s is not attached!" %\ pci_dict_to_bdf_str(key)) # There shouldn't ever be more than one match, # but perhaps an exception should be thrown if there is return l[0] else: if len(l) == 1: raise OptionError("pci: device %s has been attached! " %\ pci_dict_to_bdf_str(key)) return None def find_attached_devfn(attached, key): pci_dev = find_attached(attached, key, True) return pci_dev['vdevfn'] def xm_pci_detach(args): arg_check(args, 'pci-detach', 2) (dom, dev) = parse_pci_configuration(args) attached = attached_pci_dict(dom) attached_dev = map(lambda x: find_attached(attached, x, True), dev) def f(pci_dev): vdevfn = int(pci_dev['vdevfn'], 16) return PCI_SLOT(vdevfn) | (vdevfn & AUTO_PHP_SLOT) vdevfns = map(f, attached_dev) if len(set(vdevfns)) > 1: err_str = map(lambda x: "\t%s is in slot 0x%02x\n" % (pci_dict_to_bdf_str(x), PCI_SLOT(int(x['vdevfn'], 16))), dev) raise OptionError("More than one slot used by specified devices\n" + ''.join(err_str)) attached_to_slot = filter(lambda x: f(x) == vdevfns[0] and attached_dev[0]["key"] == x["key"], attached_dev) if len(attached_to_slot) != len(dev): err_str_ = map(lambda x: '\t%s\n' % pci_dict_to_bdf_str(x), dev) err_str = "Requested:\n" + ''.join(err_str_) err_str_ = map(lambda x: '\t%s (%s)\n' % (pci_dict_to_bdf_str(x), x['key']), attached_to_slot) err_str += "Present:\n" + ''.join(err_str_) raise OptionError(("Not all functions in slot 0x%02x have had " "detachment requested.\n" % vdevfns[0]) + err_str) for i in dev: xm_pci_detach_one(dom, i) def xm_pci_detach_one(dom, pci_dev): if serverType == SERVER_XEN_API: name = pci_dict_to_bdf_str(pci_dev) target_ref = None for dpci_ref in server.xenapi.VM.get_DPCIs(get_single_vm(dom)): ppci_ref = server.xenapi.DPCI.get_PPCI(dpci_ref) if name == server.xenapi.PPCI.get_name(ppci_ref): target_ref = ppci_ref server.xenapi.DPCI.destroy(dpci_ref) break if target_ref is None: raise OptionError("Device %s not assigned" % name) else: pci = pci_convert_dict_to_sxp(pci_dev, 'Closing') server.xend.domain.device_configure(dom, pci) def xm_scsi_detach(args): arg_check(args, 'scsi-detach', 2) dom = args[0] v_hctl = args[1] scsi = parse_scsi_configuration(None, v_hctl, xenbusState['Closing']) if serverType == SERVER_XEN_API: target_ref = None for dscsi_ref in server.xenapi.VM.get_DSCSIs(get_single_vm(dom)): if v_hctl == server.xenapi.DSCSI.get_virtual_HCTL(dscsi_ref): target_ref = dscsi_ref break if target_ref is None: raise OptionError("Device %s not assigned" % v_hctl) target_HBA_ref = server.xenapi.DSCSI.get_HBA(target_ref) if server.xenapi.DSCSI_HBA.get_assignment_mode(target_HBA_ref) == "HOST": server.xenapi.DSCSI_HBA.destroy(target_HBA_ref) else: server.xenapi.DSCSI.destroy(target_ref) else: server.xend.domain.device_configure(dom, scsi) def xm_usb_detach(args): xenapi_unsupported() arg_check(args, 'usb-detach', 3) dom = args[0] dev = args[1] port = args[2] usb = ['vusb', ['port', [port, '']]] server.xend.domain.device_configure(dom, usb, dev) def xm_usb_hc_destroy(args): xenapi_unsupported() arg_check(args, 'usb-hc-destroy', 2) dom = args[0] dev = args[1] server.xend.domain.destroyDevice(dom, 'vusb', dev) def xm_vnet_list(args): xenapi_unsupported() try: (options, params) = getopt.gnu_getopt(args, 'l', ['long']) except getopt.GetoptError, opterr: err(opterr) usage('vnet-list') use_long = 0 for (k, v) in options: if k in ['-l', '--long']: use_long = 1 if params: use_long = 1 vnets = params else: vnets = server.xend_vnets() for vnet in vnets: try: if use_long: info = server.xend_vnet(vnet) PrettyPrint.prettyprint(info) else: print vnet except Exception, ex: print vnet, ex def xm_vnet_create(args): xenapi_unsupported() arg_check(args, "vnet-create", 1) conf = args[0] if not os.access(conf, os.R_OK): print "File not found: %s" % conf sys.exit(1) server.xend_vnet_create(conf) def xm_vnet_delete(args): xenapi_unsupported() arg_check(args, "vnet-delete", 1) vnet = args[0] server.xend_vnet_delete(vnet) def xm_network_new(args): xenapi_only() arg_check(args, "network-new", 1) network = args[0] record = { "name_label": network, "name_description": "", "other_config": {}, "default_gateway": "", "default_netmask": "" } server.xenapi.network.create(record) def xm_network_del(args): xenapi_only() arg_check(args, "network-del", 1) network = args[0] networks = dict([(record['name_label'], ref) for ref, record in server.xenapi.network.get_all_records().items()]) if network not in networks.keys(): raise ValueError("'%s' is not a valid network name" % network) server.xenapi.network.destroy(networks[network]) def xm_network_show(args): xenapi_only() arg_check(args, "network-show", 0) networks = server.xenapi.network.get_all_records() pifs = server.xenapi.PIF.get_all_records() vifs = server.xenapi.VIF.get_all_records() print '%-20s %-40s %-10s' % \ ('Name', 'VIFs', 'PIFs') format2 = "%(name_label)-20s %(vif)-40s %(pif)-10s" for network_ref, network in networks.items(): for i in range(max(len(network['PIFs']), len(network['VIFs']), 1)): if i < len(network['PIFs']): pif_uuid = network['PIFs'][i] else: pif_uuid = None if i < len(network['VIFs']): vif_uuid = network['VIFs'][i] else: vif_uuid = None pif = pifs.get(pif_uuid, None) vif = vifs.get(vif_uuid, None) if vif: dom_name = server.xenapi.VM.get_name_label(vif['VM']) vif = "%s.%s" % (dom_name, vif['device']) else: vif = '' if pif: if int(pif['VLAN']) > -1: pif = '%s.%s' % (pif['device'], pif['VLAN']) else: pif = pif['device'] else: pif = '' if i == 0: r = {'name_label':network['name_label'], 'vif':vif, 'pif':pif} else: r = {'name_label':'', 'vif':vif, 'pif':pif} print format2 % r def xm_tmem_list(args): try: (options, params) = getopt.gnu_getopt(args, 'la', ['long','all']) except getopt.GetoptError, opterr: err(opterr) usage('tmem-list') use_long = False for (k, v) in options: if k in ['-l', '--long']: use_long = True all = False for (k, v) in options: if k in ['-a', '--all']: all = True if not all and len(params) == 0: err('You must specify -a or --all or a domain id.') usage('tmem-list') if all: domid = -1 else: try: domid = int(params[0]) params = params[1:] except: err('Unrecognized domain id: %s' % params[0]) usage('tmem-list') if serverType == SERVER_XEN_API: print server.xenapi.host.tmem_list(domid,use_long) else: print server.xend.node.tmem_list(domid,use_long) def parse_tmem_args(args, name): try: (options, params) = getopt.gnu_getopt(args, 'a', ['all']) except getopt.GetoptError, opterr: err(opterr) usage(name) all = False for (k, v) in options: if k in ['-a', '--all']: all = True if not all and len(params) == 0: err('You must specify -a or --all or a domain id.') usage(name) if all: domid = -1 else: try: domid = int(params[0]) params = params[1:] except: err('Unrecognized domain id: %s' % params[0]) usage(name) return domid, params def xm_tmem_destroy(args): (domid, _) = parse_tmem_args(args, 'tmem-destroy') if serverType == SERVER_XEN_API: server.xenapi.host.tmem_destroy(domid) else: server.xend.node.tmem_destroy(domid) def xm_tmem_thaw(args): (domid, _) = parse_tmem_args(args, 'tmem-thaw') if serverType == SERVER_XEN_API: server.xenapi.host.tmem_thaw(domid) else: server.xend.node.tmem_thaw(domid) def xm_tmem_freeze(args): (domid, _) = parse_tmem_args(args, 'tmem-freeze') if serverType == SERVER_XEN_API: server.xenapi.host.tmem_freeze(domid) else: server.xend.node.tmem_freeze(domid) def xm_tmem_flush(args): try: (options, params) = getopt.gnu_getopt(args, 'a', ['all']) except getopt.GetoptError, opterr: err(opterr) usage(name) all = False for (k, v) in options: if k in ['-a', '--all']: all = True if not all and len(params) == 0: err('You must specify -a or --all or a domain id.') usage('tmem-flush') if all: domid = -1 else: try: domid = int(params[0]) params = params[1:] except: err('Unrecognized domain id: %s' % params[0]) usage('tmem-flush') pages = -1 for (k, v) in options: if k in ['-p', '--pages']: pages = v if serverType == SERVER_XEN_API: server.xenapi.host.tmem_flush(domid,pages) else: server.xend.node.tmem_flush(domid,pages) def xm_tmem_set(args): try: (options, params) = getopt.gnu_getopt(args, 'a', ['all']) except getopt.GetoptError, opterr: err(opterr) usage(name) all = False for (k, v) in options: if k in ['-a', '--all']: all = True if not all and len(params) == 0: err('You must specify -a or --all or a domain id.') usage('tmem-set') if all: domid = -1 else: try: domid = int(params[0]) params = params[1:] except: err('Unrecognized domain id: %s' % params[0]) usage('tmem-set') weight = None cap = None compress = None for item in params: if item.startswith('weight='): try: weight = int(item[7:]) except: err('weight should be a integer') usage('tmem-set') if item.startswith('cap='): cap = int(item[4:]) if item.startswith('compress='): compress = int(item[9:]) if weight is None and cap is None and compress is None: err('Unrecognized tmem configuration option: %s' % item) usage('tmem-set') if serverType == SERVER_XEN_API: if weight is not None: server.xenapi.host.tmem_set_weight(domid, weight) if cap is not None: server.xenapi.host.tmem_set_cap(domid, cap) if compress is not None: server.xenapi.host.tmem_set_compress(domid, compress) else: if weight is not None: server.xend.node.tmem_set_weight(domid, weight) if cap is not None: server.xend.node.tmem_set_cap(domid, cap) if compress is not None: server.xend.node.tmem_set_compress(domid, compress) def xm_tmem_freeable_mb(args): if serverType == SERVER_XEN_API: print server.xenapi.host.tmem_query_freeable_mb() else: print server.xend.node.tmem_query_freeable_mb() def xm_tmem_shared_auth(args): try: (options, params) = getopt.gnu_getopt(args, 'au:A:', ['all','uuid=','auth=']) except getopt.GetoptError, opterr: err(opterr) usage('tmem-shared-auth') all = False for (k, v) in options: if k in ['-a', '--all']: all = True if not all and len(params) == 0: err('You must specify -a or --all or a domain id.') usage('tmem-shared-auth') if all: domid = -1 else: try: domid = int(params[0]) params = params[1:] except: err('Unrecognized domain id: %s' % params[0]) usage('tmem-shared-auth') for (k, v) in options: if k in ['-u', '--uuid']: uuid_str = v auth = 0 for (k, v) in options: if k in ['-A', '--auth']: auth = v if serverType == SERVER_XEN_API: return server.xenapi.host.tmem_shared_auth(domid,uuid_str,auth) else: return server.xend.node.tmem_shared_auth(domid,uuid_str,auth) def get_cpupool_ref(name): refs = server.xenapi.cpu_pool.get_by_name_label(name) if len(refs) > 0: return refs[0] else: err('unknown pool name') sys.exit(1) def xm_cpupool_start(args): arg_check(args, "cpupool-start", 1) if serverType == SERVER_XEN_API: ref = get_cpupool_ref(args[0]) server.xenapi.cpu_pool.activate(ref) else: server.xend.cpu_pool.start(args[0]) def brief_cpupool_list(sxprs): format_str = "%-16s %3s %8s %s %s" for sxpr in sxprs: if sxpr == sxprs[0]: print "Name CPUs Sched Active Domain count" record = sxp2map(sxpr) name = record['name_label'] sched_policy = record['sched_policy'] if record['activated']: cpus = record.get('host_CPU_numbers', []) vms = record.get('started_VM_names', []) if not isinstance(cpus, types.ListType): cpus = [cpus] if not isinstance(vms, types.ListType): vms = [vms] cpu_count = len(cpus) vm_count = len(vms) active = 'y' else: cpu_count = record['ncpu'] vm_count = 0 active = 'n' print format_str % (name, cpu_count, sched_policy, active, vm_count) def brief_cpupool_list_cpus(sxprs): format_str = "%-16s %s" for sxpr in sxprs: if sxpr == sxprs[0]: print format_str % ("Name", "CPU list") record = sxp2map(sxpr) name = record['name_label'] cpus = "" if record['activated']: cpus = record.get('host_CPU_numbers', []) if isinstance(cpus, types.ListType): cpus.sort() cpus = reduce(lambda x,y: x + "%s," % y, cpus, "") cpus = cpus[0:len(cpus)-1] else: cpus = str(cpus) if len(cpus) == 0: cpus = "-" print format_str % (name, cpus) def xm_cpupool_list(args): arg_check(args, "cpupool-list", 0, 2) try: (options, params) = getopt.gnu_getopt(args, 'lc', ['long','cpus']) except getopt.GetoptError, opterr: err(opterr) usage('cpupool-list') if len(params) > 1: err("Only one cpupool name for selection allowed") usage('cpupool-list') use_long = False show_cpus = False for (k, _) in options: if k in ['-l', '--long']: use_long = True if k in ['-c', '--cpus']: show_cpus = True if serverType == SERVER_XEN_API: pools = server.xenapi.cpu_pool.get_all_records() cpu_recs = server.xenapi.host_cpu.get_all_records() sxprs = [] for pool in pools.values(): if pool['name_label'] in params or len(params) == 0: started_VM_names = [['started_VM_names'] + [ server.xenapi.VM.get_name_label(started_VM) for started_VM in pool['started_VMs'] ] ] host_CPU_numbers = [['host_CPU_numbers'] + [ cpu_recs[cpu_ref]['number'] for cpu_ref in pool['host_CPUs'] ] ] sxpr = [ pool['uuid'] ] + map_to_sxp(pool) + \ host_CPU_numbers + started_VM_names sxprs.append(sxpr) else: sxprs = server.xend.cpu_pool.list(params) if len(params) > 0 and len(sxprs) == 0: # pool not found err("Pool '%s' does not exist." % params[0]) if use_long: for sxpr in sxprs: PrettyPrint.prettyprint(sxpr) elif show_cpus: brief_cpupool_list_cpus(sxprs) else: brief_cpupool_list(sxprs) def xm_cpupool_destroy(args): arg_check(args, "cpupool-destroy", 1) if serverType == SERVER_XEN_API: ref = get_cpupool_ref(args[0]) server.xenapi.cpu_pool.deactivate(ref) else: server.xend.cpu_pool.destroy(args[0]) def xm_cpupool_delete(args): arg_check(args, "cpupool-delete", 1) if serverType == SERVER_XEN_API: ref = get_cpupool_ref(args[0]) server.xenapi.cpu_pool.destroy(ref) else: server.xend.cpu_pool.delete(args[0]) def xm_cpupool_cpu_add(args): arg_check(args, "cpupool-cpu-add", 2) if serverType == SERVER_XEN_API: ref = get_cpupool_ref(args[0]) cpu_ref_list = server.xenapi.host_cpu.get_all_records() cpu_ref = [ c_rec['uuid'] for c_rec in cpu_ref_list.values() if c_rec['number'] == args[1] ] if len(cpu_ref) == 0: err('cpu number unknown') else: server.xenapi.cpu_pool.add_host_CPU_live(ref, cpu_ref[0]) else: server.xend.cpu_pool.cpu_add(args[0], args[1]) def xm_cpupool_cpu_remove(args): arg_check(args, "cpupool-cpu-remove", 2) if serverType == SERVER_XEN_API: ref = get_cpupool_ref(args[0]) cpu_ref_list = server.xenapi.host_cpu.get_all_records() cpu_ref = [ c_rec['uuid'] for c_rec in cpu_ref_list.values() if c_rec['number'] == args[1] ] if len(cpu_ref) == 0: err('cpu number unknown') else: server.xenapi.cpu_pool.remove_host_CPU_live(ref, cpu_ref[0]) else: server.xend.cpu_pool.cpu_remove(args[0], args[1]) def xm_cpupool_migrate(args): arg_check(args, "cpupool-migrate", 2) domname = args[0] poolname = args[1] if serverType == SERVER_XEN_API: pool_ref = get_cpupool_ref(poolname) server.xenapi.VM.cpu_pool_migrate(get_single_vm(domname), pool_ref) else: server.xend.cpu_pool.migrate(domname, poolname) commands = { "shell": xm_shell, "event-monitor": xm_event_monitor, # console commands "console": xm_console, "vncviewer": xm_vncviewer, # xenstat commands "top": xm_top, # domain commands "delete": xm_delete, "destroy": xm_destroy, "domid": xm_domid, "domname": xm_domname, "dump-core": xm_dump_core, "reboot": xm_reboot, "rename": xm_rename, "reset": xm_reset, "restore": xm_restore, "resume": xm_resume, "save": xm_save, "shutdown": xm_shutdown, "start": xm_start, "sysrq": xm_sysrq, "trigger": xm_trigger, "uptime": xm_uptime, "suspend": xm_suspend, "list": xm_list, # memory commands "mem-max": xm_mem_max, "mem-set": xm_mem_set, # cpu commands "vcpu-pin": xm_vcpu_pin, "vcpu-list": xm_vcpu_list, "vcpu-set": xm_vcpu_set, # special "pause": xm_pause, "unpause": xm_unpause, # host commands "debug-keys": xm_debug_keys, "dmesg": xm_dmesg, "info": xm_info, "log": xm_log, "serve": xm_serve, # scheduler "sched-sedf": xm_sched_sedf, "sched-credit": xm_sched_credit, "sched-credit2": xm_sched_credit2, # block "block-attach": xm_block_attach, "block-detach": xm_block_detach, "block-list": xm_block_list, "block-configure": xm_block_configure, # network (AKA vifs) "network-attach": xm_network_attach, "network-detach": xm_network_detach, "network-list": xm_network_list, "network2-attach": xm_network2_attach, "network2-detach": xm_network2_detach, "network2-list": xm_network2_list, # network (as in XenAPI) "network-new": xm_network_new, "network-del": xm_network_del, "network-show": xm_network_show, # vnet "vnet-list": xm_vnet_list, "vnet-create": xm_vnet_create, "vnet-delete": xm_vnet_delete, #pci "pci-attach": xm_pci_attach, "pci-detach": xm_pci_detach, "pci-list": xm_pci_list, "pci-list-assignable-devices": xm_pci_list_assignable_devices, # vscsi "scsi-attach": xm_scsi_attach, "scsi-detach": xm_scsi_detach, "scsi-list": xm_scsi_list, # vusb "usb-attach": xm_usb_attach, "usb-detach": xm_usb_detach, "usb-list": xm_usb_list, "usb-list-assignable-devices": xm_usb_list_assignable_devices, "usb-hc-create": xm_usb_hc_create, "usb-hc-destroy": xm_usb_hc_destroy, # cpupool "cpupool-start": xm_cpupool_start, "cpupool-list": xm_cpupool_list, "cpupool-destroy": xm_cpupool_destroy, "cpupool-delete": xm_cpupool_delete, "cpupool-cpu-add": xm_cpupool_cpu_add, "cpupool-cpu-remove": xm_cpupool_cpu_remove, "cpupool-migrate": xm_cpupool_migrate, # tmem "tmem-thaw": xm_tmem_thaw, "tmem-freeze": xm_tmem_freeze, "tmem-flush": xm_tmem_flush, "tmem-destroy": xm_tmem_destroy, "tmem-list": xm_tmem_list, "tmem-set": xm_tmem_set, "tmem-freeable": xm_tmem_freeable_mb, "tmem-shared-auth": xm_tmem_shared_auth, #usb "usb-add": xm_usb_add, "usb-del": xm_usb_del, #domstate "domstate": xm_domstate, } ## The commands supported by a separate argument parser in xend.xm. IMPORTED_COMMANDS = [ 'create', 'new', 'migrate', 'labels', 'dumppolicy', 'addlabel', 'rmlabel', 'getlabel', 'dry-run', 'resources', 'getpolicy', 'setpolicy', 'resetpolicy', 'getenforce', 'setenforce', 'cpupool-create', 'cpupool-new', ] for c in IMPORTED_COMMANDS: commands[c] = eval('lambda args: xm_importcommand("%s", args)' % c) aliases = { "balloon": "mem-set", "pool-create": "cpupool-create", "pool-new": "cpupool-new", "pool-start": "cpupool-start", "pool-list": "cpupool-list", "pool-destroy": "cpupool-destroy", "pool-delete": "cpupool-delete", "pool-cpu-add": "cpupool-cpu-add", "pool-cpu-remove": "cpupool-cpu-remove", "pool-migrate": "cpupool-migrate", "set-vcpus": "vcpu-set", "vif-list": "network-list", "vbd-create": "block-attach", "vbd-destroy": "block-detach", "vbd-list": "block-list", } def xm_lookup_cmd(cmd): if commands.has_key(cmd): return commands[cmd] elif aliases.has_key(cmd): deprecated(cmd,aliases[cmd]) return commands[aliases[cmd]] elif cmd == 'help': longHelp() sys.exit(0) else: # simulate getopt's prefix matching behaviour if len(cmd) > 1: same_prefix_cmds = [commands[c] for c in commands.keys() \ if c[:len(cmd)] == cmd] # only execute if there is only 1 match if len(same_prefix_cmds) == 1: return same_prefix_cmds[0] return None def deprecated(old,new): print >>sys.stderr, ( "Command %s is deprecated. Please use xm %s instead." % (old, new)) def main(argv=sys.argv): if len(argv) < 2: usage() # intercept --help(-h) and output our own help for help in ['--help', '-h']: if help in argv[1:]: if help == argv[1]: longHelp() sys.exit(0) else: usage(argv[1]) cmd_name = argv[1] cmd = xm_lookup_cmd(cmd_name) if cmd: # strip off prog name and subcmd args = argv[2:] _, rc = _run_cmd(cmd, cmd_name, args) sys.exit(rc) else: err('Subcommand %s not found!' % cmd_name) usage() def _run_cmd(cmd, cmd_name, args): global server try: if server is None: if serverType == SERVER_XEN_API: server = XenAPI.Session(serverURI) username, password = parseAuthentication() server.login_with_password(username, password) def logout(): try: server.xenapi.session.logout() except: pass atexit.register(logout) else: server = ServerProxy(serverURI) return True, cmd(args) except socket.error, ex: if os.geteuid() != 0: err("Most commands need root access. Please try again as root.") else: err("Unable to connect to xend: %s. Is xend running?" % ex[1]) except KeyboardInterrupt: print "Interrupted." return True, '' except IOError, ex: if os.geteuid() != 0: err("Most commands need root access. Please try again as root.") else: err("Unable to connect to xend: %s." % ex[1]) except SystemExit, code: return code == 0, code except XenAPI.Failure, exn: for line in [''] + wrap(str(exn), 80) + ['']: print >>sys.stderr, line except xmlrpclib.Fault, ex: if ex.faultCode == XendClient.ERROR_INVALID_DOMAIN: err("Domain '%s' does not exist." % ex.faultString) return False, ex.faultCode else: err(ex.faultString) _usage(cmd_name) except xmlrpclib.ProtocolError, ex: if ex.errcode == -1: print >>sys.stderr, ( "Xend has probably crashed! Invalid or missing HTTP " "status code.") else: print >>sys.stderr, ( "Xend has probably crashed! ProtocolError(%d, %s)." % (ex.errcode, ex.errmsg)) except (ValueError, OverflowError): err("Invalid argument.") _usage(cmd_name) except OptionError, e: err(str(e)) _usage(cmd_name) print e.usage except XenAPIUnsupportedException, e: err(str(e)) except XSMError, e: err(str(e)) except Exception, e: if serverType != SERVER_XEN_API: import xen.util.xsm.xsm as security if isinstance(e, security.XSMError): err(str(e)) return False, 1 print "Unexpected error:", sys.exc_info()[0] print print "Please report to xen-devel@lists.xen.org" raise return False, 1 if __name__ == "__main__": main()
gpl-2.0
kyoshino/bedrock
bedrock/releasenotes/utils.py
10
1271
from django.conf import settings from django.core.cache import caches from memoize import Memoizer from bedrock.utils.git import GitRepo def get_data_version(): """Add the git ref from the repo to the cache keys. This will ensure that the cache is invalidated when the repo is updated. """ repo = GitRepo(settings.RELEASE_NOTES_PATH, settings.RELEASE_NOTES_REPO, branch_name=settings.RELEASE_NOTES_BRANCH) git_ref = repo.get_db_latest() if git_ref is None: git_ref = 'default' return git_ref class ReleaseMemoizer(Memoizer): """A memoizer class that uses the git hash as the version""" def __init__(self, version_timeout=300): self.version_timeout = version_timeout return super(ReleaseMemoizer, self).__init__(cache=caches['release-notes']) def _memoize_make_version_hash(self): return get_data_version() def _memoize_version(self, f, args=None, reset=False, delete=False, timeout=None): """Use a shorter timeout for the version so that we can refresh based on git hash""" return super(ReleaseMemoizer, self)._memoize_version(f, args, reset, delete, self.version_timeout) memoizer = ReleaseMemoizer() memoize = memoizer.memoize
mpl-2.0
daspecster/google-cloud-python
storage/google/cloud/storage/batch.py
2
11055
# Copyright 2014 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Batch updates / deletes of storage buckets / blobs. See: https://cloud.google.com/storage/docs/json_api/v1/how-tos/batch """ from email.encoders import encode_noop from email.generator import Generator from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.parser import Parser import io import json import httplib2 import six from google.cloud.exceptions import make_exception from google.cloud.storage._http import Connection class MIMEApplicationHTTP(MIMEApplication): """MIME type for ``application/http``. Constructs payload from headers and body :type method: str :param method: HTTP method :type uri: str :param uri: URI for HTTP request :type headers: dict :param headers: HTTP headers :type body: str :param body: (Optional) HTTP payload """ def __init__(self, method, uri, headers, body): if isinstance(body, dict): body = json.dumps(body) headers['Content-Type'] = 'application/json' headers['Content-Length'] = len(body) if body is None: body = '' lines = ['%s %s HTTP/1.1' % (method, uri)] lines.extend(['%s: %s' % (key, value) for key, value in sorted(headers.items())]) lines.append('') lines.append(body) payload = '\r\n'.join(lines) if six.PY2: # email.message.Message is an old-style class, so we # cannot use 'super()'. MIMEApplication.__init__(self, payload, 'http', encode_noop) else: # pragma: NO COVER Python3 super_init = super(MIMEApplicationHTTP, self).__init__ super_init(payload, 'http', encode_noop) class NoContent(object): """Emulate an HTTP '204 No Content' response.""" status = 204 class _FutureDict(object): """Class to hold a future value for a deferred request. Used by for requests that get sent in a :class:`Batch`. """ @staticmethod def get(key, default=None): """Stand-in for dict.get. :type key: object :param key: Hashable dictionary key. :type default: object :param default: Fallback value to dict.get. :raises: :class:`KeyError` always since the future is intended to fail as a dictionary. """ raise KeyError('Cannot get(%r, default=%r) on a future' % ( key, default)) def __getitem__(self, key): """Stand-in for dict[key]. :type key: object :param key: Hashable dictionary key. :raises: :class:`KeyError` always since the future is intended to fail as a dictionary. """ raise KeyError('Cannot get item %r from a future' % (key,)) def __setitem__(self, key, value): """Stand-in for dict[key] = value. :type key: object :param key: Hashable dictionary key. :type value: object :param value: Dictionary value. :raises: :class:`KeyError` always since the future is intended to fail as a dictionary. """ raise KeyError('Cannot set %r -> %r on a future' % (key, value)) class Batch(Connection): """Proxy an underlying connection, batching up change operations. :type client: :class:`google.cloud.storage.client.Client` :param client: The client to use for making connections. """ _MAX_BATCH_SIZE = 1000 def __init__(self, client): super(Batch, self).__init__(client) self._requests = [] self._target_objects = [] def _do_request(self, method, url, headers, data, target_object): """Override Connection: defer actual HTTP request. Only allow up to ``_MAX_BATCH_SIZE`` requests to be deferred. :type method: str :param method: The HTTP method to use in the request. :type url: str :param url: The URL to send the request to. :type headers: dict :param headers: A dictionary of HTTP headers to send with the request. :type data: str :param data: The data to send as the body of the request. :type target_object: object :param target_object: (Optional) This allows us to enable custom behavior in our batch connection. Here we defer an HTTP request and complete initialization of the object at a later time. :rtype: tuple of ``response`` (a dictionary of sorts) and ``content`` (a string). :returns: The HTTP response object and the content of the response. """ if len(self._requests) >= self._MAX_BATCH_SIZE: raise ValueError("Too many deferred requests (max %d)" % self._MAX_BATCH_SIZE) self._requests.append((method, url, headers, data)) result = _FutureDict() self._target_objects.append(target_object) if target_object is not None: target_object._properties = result return NoContent(), result def _prepare_batch_request(self): """Prepares headers and body for a batch request. :rtype: tuple (dict, str) :returns: The pair of headers and body of the batch request to be sent. :raises: :class:`ValueError` if no requests have been deferred. """ if len(self._requests) == 0: raise ValueError("No deferred requests") multi = MIMEMultipart() for method, uri, headers, body in self._requests: subrequest = MIMEApplicationHTTP(method, uri, headers, body) multi.attach(subrequest) # The `email` package expects to deal with "native" strings if six.PY3: # pragma: NO COVER Python3 buf = io.StringIO() else: buf = io.BytesIO() generator = Generator(buf, False, 0) generator.flatten(multi) payload = buf.getvalue() # Strip off redundant header text _, body = payload.split('\n\n', 1) return dict(multi._headers), body def _finish_futures(self, responses): """Apply all the batch responses to the futures created. :type responses: list of (headers, payload) tuples. :param responses: List of headers and payloads from each response in the batch. :raises: :class:`ValueError` if no requests have been deferred. """ # If a bad status occurs, we track it, but don't raise an exception # until all futures have been populated. exception_args = None if len(self._target_objects) != len(responses): raise ValueError('Expected a response for every request.') for target_object, sub_response in zip(self._target_objects, responses): resp_headers, sub_payload = sub_response if not 200 <= resp_headers.status < 300: exception_args = exception_args or (resp_headers, sub_payload) elif target_object is not None: target_object._properties = sub_payload if exception_args is not None: raise make_exception(*exception_args) def finish(self): """Submit a single `multipart/mixed` request with deferred requests. :rtype: list of tuples :returns: one ``(headers, payload)`` tuple per deferred request. """ headers, body = self._prepare_batch_request() url = '%s/batch' % self.API_BASE_URL # Use the private ``_base_connection`` rather than the property # ``_connection``, since the property may be this # current batch. response, content = self._client._base_connection._make_request( 'POST', url, data=body, headers=headers) responses = list(_unpack_batch_response(response, content)) self._finish_futures(responses) return responses def current(self): """Return the topmost batch, or None.""" return self._client.current_batch def __enter__(self): self._client._push_batch(self) return self def __exit__(self, exc_type, exc_val, exc_tb): try: if exc_type is None: self.finish() finally: self._client._pop_batch() def _generate_faux_mime_message(parser, response, content): """Convert response, content -> (multipart) email.message. Helper for _unpack_batch_response. """ # We coerce to bytes to get consistent concat across # Py2 and Py3. Percent formatting is insufficient since # it includes the b in Py3. if not isinstance(content, six.binary_type): content = content.encode('utf-8') content_type = response['content-type'] if not isinstance(content_type, six.binary_type): content_type = content_type.encode('utf-8') faux_message = b''.join([ b'Content-Type: ', content_type, b'\nMIME-Version: 1.0\n\n', content, ]) if six.PY2: return parser.parsestr(faux_message) else: # pragma: NO COVER Python3 return parser.parsestr(faux_message.decode('utf-8')) def _unpack_batch_response(response, content): """Convert response, content -> [(headers, payload)]. Creates a generator of tuples of emulating the responses to :meth:`httplib2.Http.request` (a pair of headers and payload). :type response: :class:`httplib2.Response` :param response: HTTP response / headers from a request. :type content: str :param content: Response payload with a batch response. """ parser = Parser() message = _generate_faux_mime_message(parser, response, content) if not isinstance(message._payload, list): raise ValueError('Bad response: not multi-part') for subrequest in message._payload: status_line, rest = subrequest._payload.split('\n', 1) _, status, _ = status_line.split(' ', 2) sub_message = parser.parsestr(rest) payload = sub_message._payload ctype = sub_message['Content-Type'] msg_headers = dict(sub_message._headers) msg_headers['status'] = status headers = httplib2.Response(msg_headers) if ctype and ctype.startswith('application/json'): payload = json.loads(payload) yield headers, payload
apache-2.0
nomuus/sineloco
ms-passwdcheck/passwdcheck.py
1
2530
from math import floor, log # Python port of: # https://www.microsoft.com/security/pc-security/assets/scripts/passwdcheck.js # # Main Page: # https://www.microsoft.com/security/pc-security/password-checker.aspx ############################################################################### __version__ = "1.0" __author__ = "nomuus" __copyright__ = "Microsoft" __email__ = "mu*nre*txemusu*da"[::-1].replace('*', '') + "!@#$%^&*()"[1] + "nomuus" + "+..com"[2:] __company__ = "www.nomuus.com" __description__ = "Python Port of Microsoft Password Checker" ############################################################################### alpha = "abcdefghijklmnopqrstuvwxyz" upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" punct = "~`!@#$%^&*()-_+=" digit = "1234567890" total_chars = 0x7f - 0x20 alpha_chars = len(alpha) upper_chars = len(upper) digit_chars = len(digit) upper_punct = len(punct) other_chars = total_chars - (alpha_chars + upper_chars + upper_punct + digit_chars) strength_labels = ["None", "Weak", "Medium", "Strong", "Best"] ############################################################################### def calculate_bits(password): len_pwd = len(password) if len_pwd < 1: return 0 b_alpha = False b_upper = False b_digit = False b_punct = False b_other = False charset = 0 for c in password: if alpha.find(c) != -1: b_alpha = True elif upper.find(c) != -1: b_upper = True elif digit.find(c) != -1: b_digit = True elif punct.find(c) != -1: b_punct = True else: b_other = True if b_alpha: charset += alpha_chars if b_upper: charset += upper_chars if b_digit: charset += digit_chars if b_punct: charset += upper_punct if b_other: charset += other_chars bits = log(charset) * (len_pwd / log(2)) return floor(bits) ############################################################################### def eval_strength(password): bits = calculate_bits(password) if bits >= 128: display_strength(4) elif bits < 128 and bits >= 64: display_strength(3) elif bits < 64 and bits >= 56: display_strength(2) elif bits < 56: display_strength(1) else: display_strength(0) ############################################################################### def display_strength(index): print strength_labels[index] ############################################################################### ############################################################################### if __name__ == "__main__": x = raw_input("Enter a password: ") eval_strength(x)
bsd-3-clause
cyx1231st/nova
nova/tests/unit/fake_crypto.py
78
7211
# Copyright 2012 Nebula, 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. def ensure_ca_filesystem(): pass def fetch_ca(project_id=None): rootca = """-----BEGIN CERTIFICATE----- MIICyzCCAjSgAwIBAgIJAIJ/UoFWKoOUMA0GCSqGSIb3DQEBBAUAME4xEjAQBgNV BAoTCU5PVkEgUk9PVDEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzETMBEGA1UECBMK Q2FsaWZvcm5pYTELMAkGA1UEBhMCVVMwHhcNMTIxMDAyMTg1NzQ1WhcNMTMxMDAy MTg1NzQ1WjBOMRIwEAYDVQQKEwlOT1ZBIFJPT1QxFjAUBgNVBAcTDU1vdW50YWlu IFZpZXcxEzARBgNVBAgTCkNhbGlmb3JuaWExCzAJBgNVBAYTAlVTMIGfMA0GCSqG SIb3DQEBAQUAA4GNADCBiQKBgQCg0Bn8WSqbJF3QNTZUxo1TzmFBxuqvhjZLKbnQ IiShdVIWUK7RC8frq8FJI7dgJNmvkIBn9njABWDoZmurQRCzD65yCSbUc4R2ea5H IK4wQIui0CJykvMBNjAe3bzztVVs8/ccDTsjtqq3F/KeQkKzQVfSWBrJSmYtG5tO G+dOSwIDAQABo4GwMIGtMAwGA1UdEwQFMAMBAf8wHQYDVR0OBBYEFCljRfaNOsA/ 9mHuq0io7Lt83FtaMH4GA1UdIwR3MHWAFCljRfaNOsA/9mHuq0io7Lt83FtaoVKk UDBOMRIwEAYDVQQKEwlOT1ZBIFJPT1QxFjAUBgNVBAcTDU1vdW50YWluIFZpZXcx EzARBgNVBAgTCkNhbGlmb3JuaWExCzAJBgNVBAYTAlVTggkAgn9SgVYqg5QwDQYJ KoZIhvcNAQEEBQADgYEAEbpJOOlpKCh5omwfAwAfFg1ml4h/FJiCH3PETmOCc+3l CtWTBd4MG8AoH7A3PU2JKAGVQ5XWo6+ihpW1RgfQpCnloI6vIeGcws+rSLnlzULt IvfCJpRg7iQdR3jZGt3295behtP1GsCqipJEulOkOaEIs8iLlXgSOG94Mkwlb4Q= -----END CERTIFICATE----- """ return rootca def generate_x509_cert(user_id, project_id, bits=1024): pk = """-----BEGIN RSA PRIVATE KEY----- MIICXAIBAAKBgQC4h2d63ijt9l0fIBRY37D3Yj2FYajCMUlftSoHNA4lEw0uTXnH Jjbd0j7HNlSADWeAMuaoSDNp7CIsXMt6iA/ASN5nFFTZlLRqIzYoI0RHiiSJjvSG d1n4Yrar1eC8tK3Rld1Zo6rj6tOuIxfFVJajJVZykCAHjGNNvulgfhBXFwIDAQAB AoGBAIjfxx4YU/vO1lwUC4OwyS92q3OYcPk6XdakJryZHDTb4NcLmNzjt6bqIK7b 2enyB2fMWdNRWvGiueZ2HmiRLDyOGsAVdEsHvL4qbr9EZGTqC8Qxx+zTevWWf6pB F1zxzbXNQDFZDf9kVsSLCkbMHITnW1k4MrM++9gfCO3WrfehAkEA4nd8TyCCZazq KMOQwFLTNaiVLeTXCtvGopl4ZNiKYZ1qI3KDXb2wbAyArFuERlotxFlylXpwtlMo SlI/C/sYqwJBANCX1sdfRJq8DpdP44ThWqOkWFLB9rBiwyyBt8746fX8amwr8eyz H44/z5GT/Vyp8qFsjkuDzeP93eeDnr2qE0UCP1zipRnPO6x4P5J4o+Y+EmLvwkAQ nCLYAaCvUbILHrbq2Z2wWjEYnEO03RHUd2xjkGH4TgcBMTmW4e+ZzEIduwJACnIw LVfWBbG5QVac3EC021EVoz9XbUnk4Eu2usS4Yrs7USN6QBJQWD1V1cKFg6h3ICJh leKJ4wsJm9h5kKH9yQJBAN8CaX223MlTSuBOVuIOwNA+09iLfx4UCLiH1fGMKDpe xVcmkM3qCnTqNxrAPSFdT9IyB3IXiaLWbvzl7MfiOwQ= -----END RSA PRIVATE KEY----- """ csr = """Certificate: Data: Version: 1 (0x0) Serial Number: 23 (0x17) Signature Algorithm: md5WithRSAEncryption Issuer: O=NOVA ROOT, L=Mountain View, ST=California, C=US Validity Not Before: Oct 2 19:31:45 2012 GMT Not After : Oct 2 19:31:45 2013 GMT Subject: C=US, ST=California, O=OpenStack, OU=NovaDev, """ """CN=openstack-fake-2012-10-02T19:31:45Z Subject Public Key Info: Public Key Algorithm: rsaEncryption RSA Public Key: (1024 bit) Modulus (1024 bit): 00:b8:87:67:7a:de:28:ed:f6:5d:1f:20:14:58:df: b0:f7:62:3d:85:61:a8:c2:31:49:5f:b5:2a:07:34: 0e:25:13:0d:2e:4d:79:c7:26:36:dd:d2:3e:c7:36: 54:80:0d:67:80:32:e6:a8:48:33:69:ec:22:2c:5c: cb:7a:88:0f:c0:48:de:67:14:54:d9:94:b4:6a:23: 36:28:23:44:47:8a:24:89:8e:f4:86:77:59:f8:62: b6:ab:d5:e0:bc:b4:ad:d1:95:dd:59:a3:aa:e3:ea: d3:ae:23:17:c5:54:96:a3:25:56:72:90:20:07:8c: 63:4d:be:e9:60:7e:10:57:17 Exponent: 65537 (0x10001) Signature Algorithm: md5WithRSAEncryption 32:82:ff:8b:92:0e:8d:9c:6b:ce:7e:fe:34:16:2a:4c:47:4f: c7:28:a2:33:1e:48:56:2e:4b:e8:e8:e3:48:b1:3d:a3:43:21: ef:83:e7:df:e2:10:91:7e:9a:c0:4d:1e:96:68:2b:b9:f7:84: 7f:ec:84:8a:bf:bc:5e:50:05:d9:ce:4a:1a:bf:d2:bf:0c:d1: 7e:ec:64:c3:a5:37:78:a3:a6:2b:a1:b7:1c:cc:c8:b9:78:61: 98:50:3c:e6:28:34:f1:0e:62:bb:b5:d7:a1:dd:1f:38:c6:0d: 58:9f:81:67:ff:9c:32:fc:52:7e:6d:8c:91:43:49:fe:e3:48: bb:40 -----BEGIN CERTIFICATE----- MIICMzCCAZwCARcwDQYJKoZIhvcNAQEEBQAwTjESMBAGA1UEChMJTk9WQSBST09U MRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRMwEQYDVQQIEwpDYWxpZm9ybmlhMQsw CQYDVQQGEwJVUzAeFw0xMjEwMDIxOTMxNDVaFw0xMzEwMDIxOTMxNDVaMHYxCzAJ BgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRIwEAYDVQQKEwlPcGVuU3Rh Y2sxEDAOBgNVBAsTB05vdmFEZXYxLDAqBgNVBAMTI29wZW5zdGFjay1mYWtlLTIw MTItMTAtMDJUMTk6MzE6NDVaMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4 h2d63ijt9l0fIBRY37D3Yj2FYajCMUlftSoHNA4lEw0uTXnHJjbd0j7HNlSADWeA MuaoSDNp7CIsXMt6iA/ASN5nFFTZlLRqIzYoI0RHiiSJjvSGd1n4Yrar1eC8tK3R ld1Zo6rj6tOuIxfFVJajJVZykCAHjGNNvulgfhBXFwIDAQABMA0GCSqGSIb3DQEB BAUAA4GBADKC/4uSDo2ca85+/jQWKkxHT8coojMeSFYuS+jo40ixPaNDIe+D59/i EJF+msBNHpZoK7n3hH/shIq/vF5QBdnOShq/0r8M0X7sZMOlN3ijpiuhtxzMyLl4 YZhQPOYoNPEOYru116HdHzjGDVifgWf/nDL8Un5tjJFDSf7jSLtA -----END CERTIFICATE----- """ return pk, csr def get_x509_cert_and_fingerprint(): fingerprint = "a1:6f:6d:ea:a6:36:d0:3a:c6:eb:b6:ee:07:94:3e:2a:90:98:2b:c9" certif = ( "-----BEGIN CERTIFICATE-----\n" "MIIDIjCCAgqgAwIBAgIJAIE8EtWfZhhFMA0GCSqGSIb3DQEBCwUAMCQxIjAgBgNV\n" "BAMTGWNsb3VkYmFzZS1pbml0LXVzZXItMTM1NTkwHhcNMTUwMTI5MTgyMzE4WhcN\n" "MjUwMTI2MTgyMzE4WjAkMSIwIAYDVQQDExljbG91ZGJhc2UtaW5pdC11c2VyLTEz\n" "NTU5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv4lv95ofkXLIbALU\n" "UEb1f949TYNMUvMGNnLyLgGOY+D61TNG7RZn85cRg9GVJ7KDjSLN3e3LwH5rgv5q\n" "pU+nM/idSMhG0CQ1lZeExTsMEJVT3bG7LoU5uJ2fJSf5+hA0oih2M7/Kap5ggHgF\n" "h+h8MWvDC9Ih8x1aadkk/OEmJsTrziYm0C/V/FXPHEuXfZn8uDNKZ/tbyfI6hwEj\n" "nLz5Zjgg29n6tIPYMrnLNDHScCwtNZOcnixmWzsxCt1bxsAEA/y9gXUT7xWUf52t\n" "2+DGQbLYxo0PHjnPf3YnFXNavfTt+4c7ZdHhOQ6ZA8FGQ2LJHDHM1r2/8lK4ld2V\n" "qgNTcQIDAQABo1cwVTATBgNVHSUEDDAKBggrBgEFBQcDAjA+BgNVHREENzA1oDMG\n" "CisGAQQBgjcUAgOgJQwjY2xvdWRiYXNlLWluaXQtdXNlci0xMzU1OUBsb2NhbGhv\n" "c3QwDQYJKoZIhvcNAQELBQADggEBAHHX/ZUOMR0ZggQnfXuXLIHWlffVxxLOV/bE\n" "7JC/dtedHqi9iw6sRT5R6G1pJo0xKWr2yJVDH6nC7pfxCFkby0WgVuTjiu6iNRg2\n" "4zNJd8TGrTU+Mst+PPJFgsxrAY6vjwiaUtvZ/k8PsphHXu4ON+oLurtVDVgog7Vm\n" "fQCShx434OeJj1u8pb7o2WyYS5nDVrHBhlCAqVf2JPKu9zY+i9gOG2kimJwH7fJD\n" "xXpMIwAQ+flwlHR7OrE0L8TNcWwKPRAY4EPcXrT+cWo1k6aTqZDSK54ygW2iWtni\n" "ZBcstxwcB4GIwnp1DrPW9L2gw5eLe1Sl6wdz443TW8K/KPV9rWQ=\n" "-----END CERTIFICATE-----\n") return certif, fingerprint def get_ssh_public_key(): public_key = ("ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDx8nkQv/zgGg" "B4rMYmIf+6A4l6Rr+o/6lHBQdW5aYd44bd8JttDCE/F/pNRr0l" "RE+PiqSPO8nDPHw0010JeMH9gYgnnFlyY3/OcJ02RhIPyyxYpv" "9FhY+2YiUkpwFOcLImyrxEsYXpD/0d3ac30bNH6Sw9JD9UZHYc" "pSxsIbECHw== Generated-by-Nova") return public_key
apache-2.0
ChemiKhazi/Sprytile
rx/backpressure/windowedobservable.py
2
2159
import logging from rx.core import ObserverBase, ObservableBase from rx.concurrency import current_thread_scheduler, timeout_scheduler from rx.disposables import CompositeDisposable log = logging.getLogger('Rx') class WindowedObserver(ObserverBase): def __init__(self, observer, observable, cancel, scheduler): self.observer = observer self.observable = observable self.cancel = cancel self.scheduler = scheduler self.received = 0 self.schedule_disposable = None super(WindowedObserver, self).__init__() def _on_completed_core(self): self.observer.on_completed() self.dispose() def _on_error_core(self, error): self.observer.on_error(error) self.dispose() def _on_next_core(self, value): def inner_schedule_method(s, state): return self.observable.source.request(self.observable.window_size) self.observer.on_next(value) self.received = (self.received + 1) % self.observable.window_size if self.received == 0: self.schedule_disposable = self.scheduler.schedule(inner_schedule_method) def dispose(self): self.observer = None if self.cancel: self.cancel.dispose() self.cancel = None if self.schedule_disposable: self.schedule_disposable.dispose() self.schedule_disposable = None super(WindowedObserver, self).dispose() class WindowedObservable(ObservableBase): def __init__(self, source, window_size, scheduler=None): super(WindowedObservable, self).__init__() self.source = source self.window_size = window_size self.scheduler = scheduler or current_thread_scheduler self.subscription = None def _subscribe_core(self, observer): observer = WindowedObserver(observer, self, self.subscription, self.scheduler) self.subscription = self.source.subscribe(observer) def action(scheduler, state): self.source.request(self.window_size) return CompositeDisposable(self.subscription, self.scheduler.schedule(action))
mit
minhphung171093/GreenERP
openerp/addons/payment_ogone/tests/test_ogone.py
430
9309
# -*- coding: utf-8 -*- from lxml import objectify import time import urlparse from openerp.addons.payment.models.payment_acquirer import ValidationError from openerp.addons.payment.tests.common import PaymentAcquirerCommon from openerp.addons.payment_ogone.controllers.main import OgoneController from openerp.tools import mute_logger class OgonePayment(PaymentAcquirerCommon): def setUp(self): super(OgonePayment, self).setUp() cr, uid = self.cr, self.uid self.base_url = self.registry('ir.config_parameter').get_param(cr, uid, 'web.base.url') # get the adyen account model, self.ogone_id = self.registry('ir.model.data').get_object_reference(cr, uid, 'payment_ogone', 'payment_acquirer_ogone') def test_10_ogone_form_render(self): cr, uid, context = self.cr, self.uid, {} # be sure not to do stupid thing ogone = self.payment_acquirer.browse(self.cr, self.uid, self.ogone_id, None) self.assertEqual(ogone.environment, 'test', 'test without test environment') # ---------------------------------------- # Test: button direct rendering + shasign # ---------------------------------------- form_values = { 'PSPID': 'dummy', 'ORDERID': 'test_ref0', 'AMOUNT': '1', 'CURRENCY': 'EUR', 'LANGUAGE': 'en_US', 'CN': 'Norbert Buyer', 'EMAIL': 'norbert.buyer@example.com', 'OWNERZIP': '1000', 'OWNERADDRESS': 'Huge Street 2/543', 'OWNERCTY': 'Belgium', 'OWNERTOWN': 'Sin City', 'OWNERTELNO': '0032 12 34 56 78', 'SHASIGN': '815f67b8ff70d234ffcf437c13a9fa7f807044cc', 'ACCEPTURL': '%s' % urlparse.urljoin(self.base_url, OgoneController._accept_url), 'DECLINEURL': '%s' % urlparse.urljoin(self.base_url, OgoneController._decline_url), 'EXCEPTIONURL': '%s' % urlparse.urljoin(self.base_url, OgoneController._exception_url), 'CANCELURL': '%s' % urlparse.urljoin(self.base_url, OgoneController._cancel_url), } # render the button res = self.payment_acquirer.render( cr, uid, self.ogone_id, 'test_ref0', 0.01, self.currency_euro_id, partner_id=None, partner_values=self.buyer_values, context=context) # check form result tree = objectify.fromstring(res) self.assertEqual(tree.get('action'), 'https://secure.ogone.com/ncol/test/orderstandard.asp', 'ogone: wrong form POST url') for form_input in tree.input: if form_input.get('name') in ['submit']: continue self.assertEqual( form_input.get('value'), form_values[form_input.get('name')], 'ogone: wrong value for input %s: received %s instead of %s' % (form_input.get('name'), form_input.get('value'), form_values[form_input.get('name')]) ) # ---------------------------------------- # Test2: button using tx + validation # ---------------------------------------- # create a new draft tx tx_id = self.payment_transaction.create( cr, uid, { 'amount': 0.01, 'acquirer_id': self.ogone_id, 'currency_id': self.currency_euro_id, 'reference': 'test_ref0', 'partner_id': self.buyer_id, }, context=context ) # render the button res = self.payment_acquirer.render( cr, uid, self.ogone_id, 'should_be_erased', 0.01, self.currency_euro, tx_id=tx_id, partner_id=None, partner_values=self.buyer_values, context=context) # check form result tree = objectify.fromstring(res) self.assertEqual(tree.get('action'), 'https://secure.ogone.com/ncol/test/orderstandard.asp', 'ogone: wrong form POST url') for form_input in tree.input: if form_input.get('name') in ['submit']: continue self.assertEqual( form_input.get('value'), form_values[form_input.get('name')], 'ogone: wrong value for form input %s: received %s instead of %s' % (form_input.get('name'), form_input.get('value'), form_values[form_input.get('name')]) ) @mute_logger('openerp.addons.payment_ogone.models.ogone', 'ValidationError') def test_20_ogone_form_management(self): cr, uid, context = self.cr, self.uid, {} # be sure not to do stupid thing ogone = self.payment_acquirer.browse(self.cr, self.uid, self.ogone_id, None) self.assertEqual(ogone.environment, 'test', 'test without test environment') # typical data posted by ogone after client has successfully paid ogone_post_data = { 'orderID': u'test_ref_2', 'STATUS': u'9', 'CARDNO': u'XXXXXXXXXXXX0002', 'PAYID': u'25381582', 'CN': u'Norbert Buyer', 'NCERROR': u'0', 'TRXDATE': u'11/15/13', 'IP': u'85.201.233.72', 'BRAND': u'VISA', 'ACCEPTANCE': u'test123', 'currency': u'EUR', 'amount': u'1.95', 'SHASIGN': u'7B7B0ED9CBC4A85543A9073374589033A62A05A5', 'ED': u'0315', 'PM': u'CreditCard' } # should raise error about unknown tx with self.assertRaises(ValidationError): self.payment_transaction.ogone_form_feedback(cr, uid, ogone_post_data, context=context) # create tx tx_id = self.payment_transaction.create( cr, uid, { 'amount': 1.95, 'acquirer_id': self.ogone_id, 'currency_id': self.currency_euro_id, 'reference': 'test_ref_2', 'partner_name': 'Norbert Buyer', 'partner_country_id': self.country_france_id, }, context=context ) # validate it self.payment_transaction.ogone_form_feedback(cr, uid, ogone_post_data, context=context) # check state tx = self.payment_transaction.browse(cr, uid, tx_id, context=context) self.assertEqual(tx.state, 'done', 'ogone: validation did not put tx into done state') self.assertEqual(tx.ogone_payid, ogone_post_data.get('PAYID'), 'ogone: validation did not update tx payid') # reset tx tx.write({'state': 'draft', 'date_validate': False, 'ogone_payid': False}) # now ogone post is ok: try to modify the SHASIGN ogone_post_data['SHASIGN'] = 'a4c16bae286317b82edb49188d3399249a784691' with self.assertRaises(ValidationError): self.payment_transaction.ogone_form_feedback(cr, uid, ogone_post_data, context=context) # simulate an error ogone_post_data['STATUS'] = 2 ogone_post_data['SHASIGN'] = 'a4c16bae286317b82edb49188d3399249a784691' self.payment_transaction.ogone_form_feedback(cr, uid, ogone_post_data, context=context) # check state tx = self.payment_transaction.browse(cr, uid, tx_id, context=context) self.assertEqual(tx.state, 'error', 'ogone: erroneous validation did not put tx into error state') def test_30_ogone_s2s(self): test_ref = 'test_ref_%.15f' % time.time() cr, uid, context = self.cr, self.uid, {} # be sure not to do stupid thing ogone = self.payment_acquirer.browse(self.cr, self.uid, self.ogone_id, None) self.assertEqual(ogone.environment, 'test', 'test without test environment') # create a new draft tx tx_id = self.payment_transaction.create( cr, uid, { 'amount': 0.01, 'acquirer_id': self.ogone_id, 'currency_id': self.currency_euro_id, 'reference': test_ref, 'partner_id': self.buyer_id, 'type': 'server2server', }, context=context ) # create an alias res = self.payment_transaction.ogone_s2s_create_alias( cr, uid, tx_id, { 'expiry_date_mm': '01', 'expiry_date_yy': '2015', 'holder_name': 'Norbert Poilu', 'number': '4000000000000002', 'brand': 'VISA', }, context=context) # check an alias is set, containing at least OPENERP tx = self.payment_transaction.browse(cr, uid, tx_id, context=context) self.assertIn('OPENERP', tx.partner_reference, 'ogone: wrong partner reference after creating an alias') res = self.payment_transaction.ogone_s2s_execute(cr, uid, tx_id, {}, context=context) # print res # { # 'orderID': u'reference', # 'STATUS': u'9', # 'CARDNO': u'XXXXXXXXXXXX0002', # 'PAYID': u'24998692', # 'CN': u'Norbert Poilu', # 'NCERROR': u'0', # 'TRXDATE': u'11/05/13', # 'IP': u'85.201.233.72', # 'BRAND': u'VISA', # 'ACCEPTANCE': u'test123', # 'currency': u'EUR', # 'amount': u'1.95', # 'SHASIGN': u'EFDC56879EF7DE72CCF4B397076B5C9A844CB0FA', # 'ED': u'0314', # 'PM': u'CreditCard' # }
gpl-3.0
sankhesh/VTK
Rendering/Volume/Testing/Python/VolumePicker.py
16
9122
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' ========================================================================= Program: Visualization Toolkit Module: TestNamedColorsIntegration.py Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. ========================================================================= ''' import vtk import vtk.test.Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() class VolumePicker(vtk.test.Testing.vtkTest): def testVolumePicker(self): # volume render a medical data set # renderer and interactor ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin) # read the volume v16 = vtk.vtkVolume16Reader() v16.SetDataDimensions(64, 64) v16.SetImageRange(1, 93) v16.SetDataByteOrderToLittleEndian() v16.SetFilePrefix(VTK_DATA_ROOT + "/Data/headsq/quarter") v16.SetDataSpacing(3.2, 3.2, 1.5) #--------------------------------------------------------- # set up the volume rendering rayCastFunction = vtk.vtkVolumeRayCastCompositeFunction() volumeMapper = vtk.vtkVolumeRayCastMapper() volumeMapper.SetInputConnection(v16.GetOutputPort()) volumeMapper.SetVolumeRayCastFunction(rayCastFunction) volumeColor = vtk.vtkColorTransferFunction() volumeColor.AddRGBPoint(0, 0.0, 0.0, 0.0) volumeColor.AddRGBPoint(180, 0.3, 0.1, 0.2) volumeColor.AddRGBPoint(1000, 1.0, 0.7, 0.6) volumeColor.AddRGBPoint(2000, 1.0, 1.0, 0.9) volumeScalarOpacity = vtk.vtkPiecewiseFunction() volumeScalarOpacity.AddPoint(0, 0.0) volumeScalarOpacity.AddPoint(180, 0.0) volumeScalarOpacity.AddPoint(1000, 0.2) volumeScalarOpacity.AddPoint(2000, 0.8) volumeGradientOpacity = vtk.vtkPiecewiseFunction() volumeGradientOpacity.AddPoint(0, 0.0) volumeGradientOpacity.AddPoint(90, 0.5) volumeGradientOpacity.AddPoint(100, 1.0) volumeProperty = vtk.vtkVolumeProperty() volumeProperty.SetColor(volumeColor) volumeProperty.SetScalarOpacity(volumeScalarOpacity) volumeProperty.SetGradientOpacity(volumeGradientOpacity) volumeProperty.SetInterpolationTypeToLinear() volumeProperty.ShadeOn() volumeProperty.SetAmbient(0.6) volumeProperty.SetDiffuse(0.6) volumeProperty.SetSpecular(0.1) volume = vtk.vtkVolume() volume.SetMapper(volumeMapper) volume.SetProperty(volumeProperty) #--------------------------------------------------------- # Do the surface rendering boneExtractor = vtk.vtkMarchingCubes() boneExtractor.SetInputConnection(v16.GetOutputPort()) boneExtractor.SetValue(0, 1150) boneNormals = vtk.vtkPolyDataNormals() boneNormals.SetInputConnection(boneExtractor.GetOutputPort()) boneNormals.SetFeatureAngle(60.0) boneStripper = vtk.vtkStripper() boneStripper.SetInputConnection(boneNormals.GetOutputPort()) boneMapper = vtk.vtkPolyDataMapper() boneMapper.SetInputConnection(boneStripper.GetOutputPort()) boneMapper.ScalarVisibilityOff() boneProperty = vtk.vtkProperty() boneProperty.SetColor(1.0, 1.0, 0.9) bone = vtk.vtkActor() bone.SetMapper(boneMapper) bone.SetProperty(boneProperty) #--------------------------------------------------------- # Create an image actor table = vtk.vtkLookupTable() table.SetRange(0, 2000) table.SetRampToLinear() table.SetValueRange(0, 1) table.SetHueRange(0, 0) table.SetSaturationRange(0, 0) mapToColors = vtk.vtkImageMapToColors() mapToColors.SetInputConnection(v16.GetOutputPort()) mapToColors.SetLookupTable(table) imageActor = vtk.vtkImageActor() imageActor.GetMapper().SetInputConnection(mapToColors.GetOutputPort()) imageActor.SetDisplayExtent(32, 32, 0, 63, 0, 92) #--------------------------------------------------------- # make a transform and some clipping planes transform = vtk.vtkTransform() transform.RotateWXYZ(-20, 0.0, -0.7, 0.7) volume.SetUserTransform(transform) bone.SetUserTransform(transform) imageActor.SetUserTransform(transform) c = volume.GetCenter() volumeClip = vtk.vtkPlane() volumeClip.SetNormal(0, 1, 0) volumeClip.SetOrigin(c) boneClip = vtk.vtkPlane() boneClip.SetNormal(0, 0, 1) boneClip.SetOrigin(c) volumeMapper.AddClippingPlane(volumeClip) boneMapper.AddClippingPlane(boneClip) #--------------------------------------------------------- ren.AddViewProp(volume) ren.AddViewProp(bone) ren.AddViewProp(imageActor) camera = ren.GetActiveCamera() camera.SetFocalPoint(c) camera.SetPosition(c[0] + 500, c[1] - 100, c[2] - 100) camera.SetViewUp(0, 0, -1) ren.ResetCameraClippingRange() renWin.Render() #--------------------------------------------------------- # the cone should point along the Z axis coneSource = vtk.vtkConeSource() coneSource.CappingOn() coneSource.SetHeight(12) coneSource.SetRadius(5) coneSource.SetResolution(31) coneSource.SetCenter(6, 0, 0) coneSource.SetDirection(-1, 0, 0) #--------------------------------------------------------- picker = vtk.vtkVolumePicker() picker.SetTolerance(1.0e-6) picker.SetVolumeOpacityIsovalue(0.01) # This should usually be left alone, but is used here to increase coverage picker.UseVolumeGradientOpacityOn() # A function to point an actor along a vector def PointCone(actor, n): if n[0] < 0.0: actor.RotateWXYZ(180, 0, 1, 0) actor.RotateWXYZ(180, (n[0] - 1.0) * 0.5, n[1] * 0.5, n[2] * 0.5) else: actor.RotateWXYZ(180, (n[0] + 1.0) * 0.5, n[1] * 0.5, n[2] * 0.5) # Pick the actor picker.Pick(192, 103, 0, ren) #print picker p = picker.GetPickPosition() n = picker.GetPickNormal() coneActor1 = vtk.vtkActor() coneActor1.PickableOff() coneMapper1 = vtk.vtkDataSetMapper() coneMapper1.SetInputConnection(coneSource.GetOutputPort()) coneActor1.SetMapper(coneMapper1) coneActor1.GetProperty().SetColor(1, 0, 0) coneActor1.SetPosition(p) PointCone(coneActor1, n) ren.AddViewProp(coneActor1) # Pick the volume picker.Pick(90, 180, 0, ren) p = picker.GetPickPosition() n = picker.GetPickNormal() coneActor2 = vtk.vtkActor() coneActor2.PickableOff() coneMapper2 = vtk.vtkDataSetMapper() coneMapper2.SetInputConnection(coneSource.GetOutputPort()) coneActor2.SetMapper(coneMapper2) coneActor2.GetProperty().SetColor(1, 0, 0) coneActor2.SetPosition(p) PointCone(coneActor2, n) ren.AddViewProp(coneActor2) # Pick the image picker.Pick(200, 200, 0, ren) p = picker.GetPickPosition() n = picker.GetPickNormal() coneActor3 = vtk.vtkActor() coneActor3.PickableOff() coneMapper3 = vtk.vtkDataSetMapper() coneMapper3.SetInputConnection(coneSource.GetOutputPort()) coneActor3.SetMapper(coneMapper3) coneActor3.GetProperty().SetColor(1, 0, 0) coneActor3.SetPosition(p) PointCone(coneActor3, n) ren.AddViewProp(coneActor3) # Pick a clipping plane picker.PickClippingPlanesOn() picker.Pick(145, 160, 0, ren) p = picker.GetPickPosition() n = picker.GetPickNormal() coneActor4 = vtk.vtkActor() coneActor4.PickableOff() coneMapper4 = vtk.vtkDataSetMapper() coneMapper4.SetInputConnection(coneSource.GetOutputPort()) coneActor4.SetMapper(coneMapper4) coneActor4.GetProperty().SetColor(1, 0, 0) coneActor4.SetPosition(p) PointCone(coneActor4, n) ren.AddViewProp(coneActor4) ren.ResetCameraClippingRange() # render and interact with data renWin.Render() img_file = "VolumePicker.png" vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact() if __name__ == "__main__": vtk.test.Testing.main([(VolumePicker, 'test')])
bsd-3-clause
pmarques/ansible
test/lib/ansible_test/_internal/commands/sanity/ignores.py
13
2973
"""Sanity test for the sanity ignore file.""" from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os from . import ( SanityFailure, SanityIgnoreParser, SanityVersionNeutral, SanitySuccess, SanityMessage, ) from ...test import ( calculate_confidence, calculate_best_confidence, ) from ...config import ( SanityConfig, ) class IgnoresTest(SanityVersionNeutral): """Sanity test for sanity test ignore entries.""" @property def can_ignore(self): # type: () -> bool """True if the test supports ignore entries.""" return False @property def no_targets(self): # type: () -> bool """True if the test does not use test targets. Mutually exclusive with all_targets.""" return True # noinspection PyUnusedLocal def test(self, args, targets): # pylint: disable=locally-disabled, unused-argument """ :type args: SanityConfig :type targets: SanityTargets :rtype: TestResult """ sanity_ignore = SanityIgnoreParser.load(args) messages = [] # parse errors messages.extend(SanityMessage( message=message, path=sanity_ignore.relative_path, line=line, column=column, confidence=calculate_confidence(sanity_ignore.path, line, args.metadata) if args.metadata.changes else None, ) for line, column, message in sanity_ignore.parse_errors) # file not found errors messages.extend(SanityMessage( message="%s '%s' does not exist" % ("Directory" if path.endswith(os.path.sep) else "File", path), path=sanity_ignore.relative_path, line=line, column=1, confidence=calculate_best_confidence(((sanity_ignore.path, line), (path, 0)), args.metadata) if args.metadata.changes else None, ) for line, path in sanity_ignore.file_not_found_errors) # conflicting ignores and skips for test_name, ignores in sanity_ignore.ignores.items(): for ignore_path, ignore_entry in ignores.items(): skip_line_no = sanity_ignore.skips.get(test_name, {}).get(ignore_path) if not skip_line_no: continue for ignore_line_no in ignore_entry.values(): messages.append(SanityMessage( message="Ignoring '%s' is unnecessary due to skip entry on line %d" % (ignore_path, skip_line_no), path=sanity_ignore.relative_path, line=ignore_line_no, column=1, confidence=calculate_confidence(sanity_ignore.path, ignore_line_no, args.metadata) if args.metadata.changes else None, )) if messages: return SanityFailure(self.name, messages=messages) return SanitySuccess(self.name)
gpl-3.0
Nick-OpusVL/odoo
addons/l10n_be/wizard/__init__.py
438
1145
# -*- 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 l10n_be_partner_vat_listing import l10n_be_vat_intra import l10n_be_account_vat_declaration # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
hsiaoyi0504/scikit-learn
sklearn/utils/tests/test_murmurhash.py
261
2836
# Author: Olivier Grisel <olivier.grisel@ensta.org> # # License: BSD 3 clause import numpy as np from sklearn.externals.six import b, u from sklearn.utils.murmurhash import murmurhash3_32 from numpy.testing import assert_array_almost_equal from numpy.testing import assert_array_equal from nose.tools import assert_equal, assert_true def test_mmhash3_int(): assert_equal(murmurhash3_32(3), 847579505) assert_equal(murmurhash3_32(3, seed=0), 847579505) assert_equal(murmurhash3_32(3, seed=42), -1823081949) assert_equal(murmurhash3_32(3, positive=False), 847579505) assert_equal(murmurhash3_32(3, seed=0, positive=False), 847579505) assert_equal(murmurhash3_32(3, seed=42, positive=False), -1823081949) assert_equal(murmurhash3_32(3, positive=True), 847579505) assert_equal(murmurhash3_32(3, seed=0, positive=True), 847579505) assert_equal(murmurhash3_32(3, seed=42, positive=True), 2471885347) def test_mmhash3_int_array(): rng = np.random.RandomState(42) keys = rng.randint(-5342534, 345345, size=3 * 2 * 1).astype(np.int32) keys = keys.reshape((3, 2, 1)) for seed in [0, 42]: expected = np.array([murmurhash3_32(int(k), seed) for k in keys.flat]) expected = expected.reshape(keys.shape) assert_array_equal(murmurhash3_32(keys, seed), expected) for seed in [0, 42]: expected = np.array([murmurhash3_32(k, seed, positive=True) for k in keys.flat]) expected = expected.reshape(keys.shape) assert_array_equal(murmurhash3_32(keys, seed, positive=True), expected) def test_mmhash3_bytes(): assert_equal(murmurhash3_32(b('foo'), 0), -156908512) assert_equal(murmurhash3_32(b('foo'), 42), -1322301282) assert_equal(murmurhash3_32(b('foo'), 0, positive=True), 4138058784) assert_equal(murmurhash3_32(b('foo'), 42, positive=True), 2972666014) def test_mmhash3_unicode(): assert_equal(murmurhash3_32(u('foo'), 0), -156908512) assert_equal(murmurhash3_32(u('foo'), 42), -1322301282) assert_equal(murmurhash3_32(u('foo'), 0, positive=True), 4138058784) assert_equal(murmurhash3_32(u('foo'), 42, positive=True), 2972666014) def test_no_collision_on_byte_range(): previous_hashes = set() for i in range(100): h = murmurhash3_32(' ' * i, 0) assert_true(h not in previous_hashes, "Found collision on growing empty string") def test_uniform_distribution(): n_bins, n_samples = 10, 100000 bins = np.zeros(n_bins, dtype=np.float) for i in range(n_samples): bins[murmurhash3_32(i, positive=True) % n_bins] += 1 means = bins / n_samples expected = np.ones(n_bins) / n_bins assert_array_almost_equal(means / expected, np.ones(n_bins), 2)
bsd-3-clause
agconti/django-rest-framework
rest_framework/status.py
11
2027
""" Descriptive HTTP status codes, for code readability. See RFC 2616 - http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html And RFC 6585 - http://tools.ietf.org/html/rfc6585 """ from __future__ import unicode_literals def is_informational(code): return code >= 100 and code <= 199 def is_success(code): return code >= 200 and code <= 299 def is_redirect(code): return code >= 300 and code <= 399 def is_client_error(code): return code >= 400 and code <= 499 def is_server_error(code): return code >= 500 and code <= 599 HTTP_100_CONTINUE = 100 HTTP_101_SWITCHING_PROTOCOLS = 101 HTTP_200_OK = 200 HTTP_201_CREATED = 201 HTTP_202_ACCEPTED = 202 HTTP_203_NON_AUTHORITATIVE_INFORMATION = 203 HTTP_204_NO_CONTENT = 204 HTTP_205_RESET_CONTENT = 205 HTTP_206_PARTIAL_CONTENT = 206 HTTP_300_MULTIPLE_CHOICES = 300 HTTP_301_MOVED_PERMANENTLY = 301 HTTP_302_FOUND = 302 HTTP_303_SEE_OTHER = 303 HTTP_304_NOT_MODIFIED = 304 HTTP_305_USE_PROXY = 305 HTTP_306_RESERVED = 306 HTTP_307_TEMPORARY_REDIRECT = 307 HTTP_400_BAD_REQUEST = 400 HTTP_401_UNAUTHORIZED = 401 HTTP_402_PAYMENT_REQUIRED = 402 HTTP_403_FORBIDDEN = 403 HTTP_404_NOT_FOUND = 404 HTTP_405_METHOD_NOT_ALLOWED = 405 HTTP_406_NOT_ACCEPTABLE = 406 HTTP_407_PROXY_AUTHENTICATION_REQUIRED = 407 HTTP_408_REQUEST_TIMEOUT = 408 HTTP_409_CONFLICT = 409 HTTP_410_GONE = 410 HTTP_411_LENGTH_REQUIRED = 411 HTTP_412_PRECONDITION_FAILED = 412 HTTP_413_REQUEST_ENTITY_TOO_LARGE = 413 HTTP_414_REQUEST_URI_TOO_LONG = 414 HTTP_415_UNSUPPORTED_MEDIA_TYPE = 415 HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE = 416 HTTP_417_EXPECTATION_FAILED = 417 HTTP_428_PRECONDITION_REQUIRED = 428 HTTP_429_TOO_MANY_REQUESTS = 429 HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE = 431 HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS = 451 HTTP_500_INTERNAL_SERVER_ERROR = 500 HTTP_501_NOT_IMPLEMENTED = 501 HTTP_502_BAD_GATEWAY = 502 HTTP_503_SERVICE_UNAVAILABLE = 503 HTTP_504_GATEWAY_TIMEOUT = 504 HTTP_505_HTTP_VERSION_NOT_SUPPORTED = 505 HTTP_511_NETWORK_AUTHENTICATION_REQUIRED = 511
bsd-2-clause
aselle/tensorflow
tensorflow/python/tools/api/generator/create_python_api.py
3
16087
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= """Generates and prints out imports and constants for new TensorFlow python api. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import collections import importlib import os import sys from tensorflow.python.tools.api.generator import doc_srcs from tensorflow.python.util import tf_decorator from tensorflow.python.util import tf_export API_ATTRS = tf_export.API_ATTRS API_ATTRS_V1 = tf_export.API_ATTRS_V1 _DEFAULT_PACKAGE = 'tensorflow.python' _GENFILES_DIR_SUFFIX = 'genfiles/' _SYMBOLS_TO_SKIP_EXPLICITLY = { # Overrides __getattr__, so that unwrapping tf_decorator # would have side effects. 'tensorflow.python.platform.flags.FLAGS' } _GENERATED_FILE_HEADER = """# This file is MACHINE GENERATED! Do not edit. # Generated by: tensorflow/python/tools/api/generator/create_python_api.py script. \"\"\"%s \"\"\" from __future__ import print_function """ _GENERATED_FILE_FOOTER = '\n\ndel print_function\n' class SymbolExposedTwiceError(Exception): """Raised when different symbols are exported with the same name.""" pass def format_import(source_module_name, source_name, dest_name): """Formats import statement. Args: source_module_name: (string) Source module to import from. source_name: (string) Source symbol name to import. dest_name: (string) Destination alias name. Returns: An import statement string. """ if source_module_name: if source_name == dest_name: return 'from %s import %s' % (source_module_name, source_name) else: return 'from %s import %s as %s' % ( source_module_name, source_name, dest_name) else: if source_name == dest_name: return 'import %s' % source_name else: return 'import %s as %s' % (source_name, dest_name) class _ModuleInitCodeBuilder(object): """Builds a map from module name to imports included in that module.""" def __init__(self): self.module_imports = collections.defaultdict( lambda: collections.defaultdict(set)) self._dest_import_to_id = collections.defaultdict(int) # Names that start with underscore in the root module. self._underscore_names_in_root = [] def add_import( self, symbol_id, dest_module_name, source_module_name, source_name, dest_name): """Adds this import to module_imports. Args: symbol_id: (number) Unique identifier of the symbol to import. dest_module_name: (string) Module name to add import to. source_module_name: (string) Module to import from. source_name: (string) Name of the symbol to import. dest_name: (string) Import the symbol using this name. Raises: SymbolExposedTwiceError: Raised when an import with the same dest_name has already been added to dest_module_name. """ import_str = format_import(source_module_name, source_name, dest_name) # Check if we are trying to expose two different symbols with same name. full_api_name = dest_name if dest_module_name: full_api_name = dest_module_name + '.' + full_api_name if (full_api_name in self._dest_import_to_id and symbol_id != self._dest_import_to_id[full_api_name] and symbol_id != -1): raise SymbolExposedTwiceError( 'Trying to export multiple symbols with same name: %s.' % full_api_name) self._dest_import_to_id[full_api_name] = symbol_id if not dest_module_name and dest_name.startswith('_'): self._underscore_names_in_root.append(dest_name) # The same symbol can be available in multiple modules. # We store all possible ways of importing this symbol and later pick just # one. self.module_imports[dest_module_name][full_api_name].add(import_str) def build(self): """Get a map from destination module to __init__.py code for that module. Returns: A dictionary where key: (string) destination module (for e.g. tf or tf.consts). value: (string) text that should be in __init__.py files for corresponding modules. """ module_text_map = {} for dest_module, dest_name_to_imports in self.module_imports.items(): # Sort all possible imports for a symbol and pick the first one. imports_list = [ sorted(imports)[0] for _, imports in dest_name_to_imports.items()] module_text_map[dest_module] = '\n'.join(sorted(imports_list)) # Expose exported symbols with underscores in root module # since we import from it using * import. underscore_names_str = ', '.join( '\'%s\'' % name for name in self._underscore_names_in_root) # We will always generate a root __init__.py file to let us handle * # imports consistently. Be sure to have a root __init__.py file listed in # the script outputs. module_text_map[''] = module_text_map.get('', '') + ''' _names_with_underscore = [%s] __all__ = [_s for _s in dir() if not _s.startswith('_')] __all__.extend([_s for _s in _names_with_underscore]) __all__.remove('print_function') ''' % underscore_names_str return module_text_map def get_api_init_text(package, output_package, api_name, api_version): """Get a map from destination module to __init__.py code for that module. Args: package: Base python package containing python with target tf_export decorators. output_package: Base output python package where generated API will be added. api_name: API you want to generate (e.g. `tensorflow` or `estimator`). api_version: API version you want to generate (`v1` or `v2`). Returns: A dictionary where key: (string) destination module (for e.g. tf or tf.consts). value: (string) text that should be in __init__.py files for corresponding modules. """ if api_version == 1: names_attr = API_ATTRS_V1[api_name].names constants_attr = API_ATTRS_V1[api_name].constants else: names_attr = API_ATTRS[api_name].names constants_attr = API_ATTRS[api_name].constants module_code_builder = _ModuleInitCodeBuilder() # Traverse over everything imported above. Specifically, # we want to traverse over TensorFlow Python modules. for module in list(sys.modules.values()): # Only look at tensorflow modules. if (not module or not hasattr(module, '__name__') or module.__name__ is None or package not in module.__name__): continue # Do not generate __init__.py files for contrib modules for now. if '.contrib.' in module.__name__ or module.__name__.endswith('.contrib'): continue for module_contents_name in dir(module): if (module.__name__ + '.' + module_contents_name in _SYMBOLS_TO_SKIP_EXPLICITLY): continue attr = getattr(module, module_contents_name) # If attr is _tf_api_constants attribute, then add the constants. if module_contents_name == constants_attr: for exports, value in attr: for export in exports: names = export.split('.') dest_module = '.'.join(names[:-1]) module_code_builder.add_import( -1, dest_module, module.__name__, value, names[-1]) continue _, attr = tf_decorator.unwrap(attr) # If attr is a symbol with _tf_api_names attribute, then # add import for it. if (hasattr(attr, '__dict__') and names_attr in attr.__dict__): for export in getattr(attr, names_attr): # pylint: disable=protected-access names = export.split('.') dest_module = '.'.join(names[:-1]) module_code_builder.add_import( id(attr), dest_module, module.__name__, module_contents_name, names[-1]) # Import all required modules in their parent modules. # For e.g. if we import 'foo.bar.Value'. Then, we also # import 'bar' in 'foo'. imported_modules = set(module_code_builder.module_imports.keys()) for module in imported_modules: if not module: continue module_split = module.split('.') parent_module = '' # we import submodules in their parent_module for submodule_index in range(len(module_split)): if submodule_index > 0: parent_module += ('.' + module_split[submodule_index-1] if parent_module else module_split[submodule_index-1]) import_from = output_package if submodule_index > 0: import_from += '.' + '.'.join(module_split[:submodule_index]) module_code_builder.add_import( -1, parent_module, import_from, module_split[submodule_index], module_split[submodule_index]) return module_code_builder.build() def get_module(dir_path, relative_to_dir): """Get module that corresponds to path relative to relative_to_dir. Args: dir_path: Path to directory. relative_to_dir: Get module relative to this directory. Returns: Name of module that corresponds to the given directory. """ dir_path = dir_path[len(relative_to_dir):] # Convert path separators to '/' for easier parsing below. dir_path = dir_path.replace(os.sep, '/') return dir_path.replace('/', '.').strip('.') def get_module_docstring(module_name, package, api_name): """Get docstring for the given module. This method looks for docstring in the following order: 1. Checks if module has a docstring specified in doc_srcs. 2. Checks if module has a docstring source module specified in doc_srcs. If it does, gets docstring from that module. 3. Checks if module with module_name exists under base package. If it does, gets docstring from that module. 4. Returns a default docstring. Args: module_name: module name relative to tensorflow (excluding 'tensorflow.' prefix) to get a docstring for. package: Base python package containing python with target tf_export decorators. api_name: API you want to generate (e.g. `tensorflow` or `estimator`). Returns: One-line docstring to describe the module. """ # Module under base package to get a docstring from. docstring_module_name = module_name doc_sources = doc_srcs.get_doc_sources(api_name) if module_name in doc_sources: docsrc = doc_sources[module_name] if docsrc.docstring: return docsrc.docstring if docsrc.docstring_module_name: docstring_module_name = docsrc.docstring_module_name docstring_module_name = package + '.' + docstring_module_name if (docstring_module_name in sys.modules and sys.modules[docstring_module_name].__doc__): return sys.modules[docstring_module_name].__doc__ return 'Public API for tf.%s namespace.' % module_name def create_api_files( output_files, package, root_init_template, output_dir, output_package, api_name, api_version): """Creates __init__.py files for the Python API. Args: output_files: List of __init__.py file paths to create. Each file must be under api/ directory. package: Base python package containing python with target tf_export decorators. root_init_template: Template for top-level __init__.py file. "#API IMPORTS PLACEHOLDER" comment in the template file will be replaced with imports. output_dir: output API root directory. output_package: Base output package where generated API will be added. api_name: API you want to generate (e.g. `tensorflow` or `estimator`). api_version: API version to generate (`v1` or `v2`). Raises: ValueError: if an output file is not under api/ directory, or output_files list is missing a required file. """ module_name_to_file_path = {} for output_file in output_files: module_name = get_module(os.path.dirname(output_file), output_dir) module_name_to_file_path[module_name] = os.path.normpath(output_file) # Create file for each expected output in genrule. for module, file_path in module_name_to_file_path.items(): if not os.path.isdir(os.path.dirname(file_path)): os.makedirs(os.path.dirname(file_path)) open(file_path, 'a').close() module_text_map = get_api_init_text( package, output_package, api_name, api_version) # Add imports to output files. missing_output_files = [] for module, text in module_text_map.items(): # Make sure genrule output file list is in sync with API exports. if module not in module_name_to_file_path: module_file_path = '"%s/__init__.py"' % ( module.replace('.', '/')) missing_output_files.append(module_file_path) continue contents = '' if module or not root_init_template: contents = ( _GENERATED_FILE_HEADER % get_module_docstring(module, package, api_name) + text + _GENERATED_FILE_FOOTER) else: # Read base init file with open(root_init_template, 'r') as root_init_template_file: contents = root_init_template_file.read() contents = contents.replace('# API IMPORTS PLACEHOLDER', text) with open(module_name_to_file_path[module], 'w') as fp: fp.write(contents) if missing_output_files: raise ValueError( 'Missing outputs for python_api_gen genrule:\n%s.' 'Make sure all required outputs are in the ' 'tensorflow/tools/api/generator/api_gen.bzl file.' % ',\n'.join(sorted(missing_output_files))) def main(): parser = argparse.ArgumentParser() parser.add_argument( 'outputs', metavar='O', type=str, nargs='+', help='If a single file is passed in, then we we assume it contains a ' 'semicolon-separated list of Python files that we expect this script to ' 'output. If multiple files are passed in, then we assume output files ' 'are listed directly as arguments.') parser.add_argument( '--package', default=_DEFAULT_PACKAGE, type=str, help='Base package that imports modules containing the target tf_export ' 'decorators.') parser.add_argument( '--root_init_template', default='', type=str, help='Template for top level __init__.py file. ' '"#API IMPORTS PLACEHOLDER" comment will be replaced with imports.') parser.add_argument( '--apidir', type=str, required=True, help='Directory where generated output files are placed. ' 'gendir should be a prefix of apidir. Also, apidir ' 'should be a prefix of every directory in outputs.') parser.add_argument( '--apiname', required=True, type=str, choices=API_ATTRS.keys(), help='The API you want to generate.') parser.add_argument( '--apiversion', default=2, type=int, choices=[1, 2], help='The API version you want to generate.') parser.add_argument( '--output_package', default='tensorflow', type=str, help='Root output package.') args = parser.parse_args() if len(args.outputs) == 1: # If we only get a single argument, then it must be a file containing # list of outputs. with open(args.outputs[0]) as output_list_file: outputs = [line.strip() for line in output_list_file.read().split(';')] else: outputs = args.outputs # Populate `sys.modules` with modules containing tf_export(). importlib.import_module(args.package) create_api_files(outputs, args.package, args.root_init_template, args.apidir, args.output_package, args.apiname, args.apiversion) if __name__ == '__main__': main()
apache-2.0
kevgliss/lemur
lemur/migrations/versions/a02a678ddc25_.py
1
2093
"""Adds support for rotation policies. Creates a default rotation policy (30 days) with the name 'default' ensures that all existing certificates use the default policy. Revision ID: a02a678ddc25 Revises: 8ae67285ff14 Create Date: 2017-07-12 11:45:49.257927 """ # revision identifiers, used by Alembic. revision = 'a02a678ddc25' down_revision = '8ae67285ff14' from alembic import op import sqlalchemy as sa from sqlalchemy.sql import text def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('rotation_policies', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(), nullable=True), sa.Column('days', sa.Integer(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.add_column('certificates', sa.Column('rotation_policy_id', sa.Integer(), nullable=True)) op.create_foreign_key(None, 'certificates', 'rotation_policies', ['rotation_policy_id'], ['id']) conn = op.get_bind() stmt = text('insert into rotation_policies (days, name) values (:days, :name)') stmt = stmt.bindparams(days=30, name='default') conn.execute(stmt) stmt = text('select id from rotation_policies where name=:name') stmt = stmt.bindparams(name='default') rotation_policy_id = conn.execute(stmt).fetchone()[0] stmt = text('update certificates set rotation_policy_id=:rotation_policy_id') stmt = stmt.bindparams(rotation_policy_id=rotation_policy_id) conn.execute(stmt) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_constraint(None, 'certificates', type_='foreignkey') op.drop_column('certificates', 'rotation_policy_id') op.drop_index('certificate_replacement_associations_ix', table_name='certificate_replacement_associations') op.create_index('certificate_replacement_associations_ix', 'certificate_replacement_associations', ['replaced_certificate_id', 'certificate_id'], unique=True) op.drop_table('rotation_policies') # ### end Alembic commands ###
apache-2.0
emonty/vhd-util
tools/python/logging/logging-0.4.9.2/test/log_test6.py
42
2045
#!/usr/bin/env python # # Copyright 2001-2002 by Vinay Sajip. All Rights Reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, # provided that the above copyright notice appear in all copies and that # both that copyright notice and this permission notice appear in # supporting documentation, and that the name of Vinay Sajip # not be used in advertising or publicity pertaining to distribution # of the software without specific, written prior permission. # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # # This file is part of the Python logging distribution. See # http://www.red-dove.com/python_logging.html # """ A test harness for the logging module. Tests NTEventLogHandler. Copyright (C) 2001-2002 Vinay Sajip. All Rights Reserved. """ import logging, logging.handlers def main(): ntl = logging.handlers.NTEventLogHandler("Python Logging Test") logger = logging.getLogger("") logger.setLevel(logging.DEBUG) logger.addHandler(ntl) logger.debug("This is a '%s' message", "Debug") logger.info("This is a '%s' message", "Info") logger.warning("This is a '%s' message", "Warning") logger.error("This is a '%s' message", "Error") logger.critical("This is a '%s' message", "Critical") try: x = 4 / 0 except: logger.info("This is an %s (or should that be %s?)", "informational exception", "exceptional information", exc_info=1) logger.exception("This is the same stuff, via a %s", "exception() call") logger.removeHandler(ntl) if __name__ == "__main__": main()
gpl-2.0
punesemu/puNES
src/extra/p7zip_16.02/Utils/bin_to_sources.py
2
1794
#!/usr/bin/env python import fnmatch import os import sys dir0='CPP/7zip/Bundles/Alone' file0='Utils/file_7za.py' dir0='CPP/7zip/Bundles/SFXCon' file0='Utils/file_7zCon_sfx.py' dir0='CPP/7zip/UI/Console' file0='Utils/file_7z.py' dir0='CPP/7zip/Compress/Rar' file0='Utils/file_Codecs_Rar_so.py' dir0='CPP/7zip/Bundles/Format7zFree' file0='Utils/file_7z_so.py' dir0='CPP/7zip/UI/GUI' file0='Utils/file_7zG.py' dir0='CPP/7zip/Bundles/Alone7z' file0='Utils/file_7zr.py' dir0='CPP/7zip/UI/FileManager' file0='Utils/file_7zFM.py' dir0='CPP/7zip/Bundles/LzmaCon' file0='Utils/file_LzmaCon.py' dir0='CPP/7zip/UI/Client7z' file0='Utils/file_Client7z.py' dir0='CPP/7zip/UI/P7ZIP' file0='Utils/file_P7ZIP.py' dir0='CPP/7zip/TEST/TestUI' file0='Utils/file_TestUI.py' listO=[] for file in os.listdir(dir0): if fnmatch.fnmatch(file, '*.o'): # print(file) file=os.path.splitext(file)[0] listO.append(file) listO.sort() listc=[] listcpp=[] for file in listO: # print("Searching " + file + " ...") f_c= None f_cpp = None file_c = file + '.c' file_cpp = file + '.cpp' for root, dirs, files in os.walk("."): for f in files: if f == file_c: f_c=os.path.join(root, f) if f == file_cpp: f_cpp=os.path.join(root, f) if f_c is None: if f_cpp is None: print("Cannot find {}".format(file)) sys.exit(-1) else: listcpp.append(f_cpp[2:]) else: if f_cpp is None: listc.append(f_c[2:]) else: print("error {} => {} and {}".format(file,f_c,f_cpp)) sys.exit(-1) f=open(file0,'w') f.write('\n') listc.sort() listcpp.sort() f.write('files_c=[\n') for file in listc: f.write(" '{}',\n".format(file)) f.write(']\n') f.write('\n') f.write('files_cpp=[\n') for file in listcpp: f.write(" '{}',\n".format(file)) f.write(']\n') f.write('\n') f.close()
gpl-2.0
captainpete/rethinkdb
external/v8_3.30.33.16/build/gyp/test/ios/gyptest-per-config-settings.py
193
5219
#!/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. """ Verifies that device and simulator bundles are built correctly. """ import plistlib import TestGyp import os import struct import subprocess import sys import tempfile def CheckFileType(file, expected): proc = subprocess.Popen(['lipo', '-info', file], stdout=subprocess.PIPE) o = proc.communicate()[0].strip() assert not proc.returncode if not expected in o: print 'File: Expected %s, got %s' % (expected, o) test.fail_test() def HasCerts(): # Because the bots do not have certs, don't check them if there are no # certs available. proc = subprocess.Popen(['security','find-identity','-p', 'codesigning', '-v'], stdout=subprocess.PIPE) return "0 valid identities found" not in proc.communicate()[0].strip() def CheckSignature(file): proc = subprocess.Popen(['codesign', '-v', file], stdout=subprocess.PIPE) o = proc.communicate()[0].strip() assert not proc.returncode if "code object is not signed at all" in o: print 'File %s not properly signed.' % (file) test.fail_test() def CheckEntitlements(file, expected_entitlements): with tempfile.NamedTemporaryFile() as temp: proc = subprocess.Popen(['codesign', '--display', '--entitlements', temp.name, file], stdout=subprocess.PIPE) o = proc.communicate()[0].strip() assert not proc.returncode data = temp.read() entitlements = ParseEntitlements(data) if not entitlements: print 'No valid entitlements found in %s.' % (file) test.fail_test() if entitlements != expected_entitlements: print 'Unexpected entitlements found in %s.' % (file) test.fail_test() def ParseEntitlements(data): if len(data) < 8: return None magic, length = struct.unpack('>II', data[:8]) if magic != 0xfade7171 or length != len(data): return None return data[8:] def GetProductVersion(): args = ['xcodebuild','-version','-sdk','iphoneos','ProductVersion'] job = subprocess.Popen(args, stdout=subprocess.PIPE) return job.communicate()[0].strip() def CheckPlistvalue(plist, key, expected): if key not in plist: print '%s not set in plist' % key test.fail_test() return actual = plist[key] if actual != expected: print 'File: Expected %s, got %s for %s' % (expected, actual, key) test.fail_test() def CheckPlistNotSet(plist, key): if key in plist: print '%s should not be set in plist' % key test.fail_test() return def ConvertBinaryPlistToXML(path): proc = subprocess.call(['plutil', '-convert', 'xml1', path], stdout=subprocess.PIPE) if sys.platform == 'darwin': test = TestGyp.TestGyp(formats=['ninja', 'xcode']) test.run_gyp('test-device.gyp', chdir='app-bundle') test_configs = ['Default-iphoneos', 'Default'] # TODO(justincohen): Disabling 'Default-iphoneos' for xcode until bots are # configured with signing certs. if test.format == 'xcode': test_configs.remove('Default-iphoneos') for configuration in test_configs: test.set_configuration(configuration) test.build('test-device.gyp', 'test_app', chdir='app-bundle') result_file = test.built_file_path('Test App Gyp.bundle/Test App Gyp', chdir='app-bundle') test.must_exist(result_file) info_plist = test.built_file_path('Test App Gyp.bundle/Info.plist', chdir='app-bundle') # plistlib doesn't support binary plists, but that's what Xcode creates. if test.format == 'xcode': ConvertBinaryPlistToXML(info_plist) plist = plistlib.readPlist(info_plist) CheckPlistvalue(plist, 'UIDeviceFamily', [1, 2]) if configuration == 'Default-iphoneos': CheckFileType(result_file, 'armv7') CheckPlistvalue(plist, 'DTPlatformVersion', GetProductVersion()) CheckPlistvalue(plist, 'CFBundleSupportedPlatforms', ['iPhoneOS']) CheckPlistvalue(plist, 'DTPlatformName', 'iphoneos') else: CheckFileType(result_file, 'i386') CheckPlistNotSet(plist, 'DTPlatformVersion') CheckPlistvalue(plist, 'CFBundleSupportedPlatforms', ['iPhoneSimulator']) CheckPlistvalue(plist, 'DTPlatformName', 'iphonesimulator') if HasCerts() and configuration == 'Default-iphoneos': test.build('test-device.gyp', 'sig_test', chdir='app-bundle') result_file = test.built_file_path('sig_test.bundle/sig_test', chdir='app-bundle') CheckSignature(result_file) info_plist = test.built_file_path('sig_test.bundle/Info.plist', chdir='app-bundle') plist = plistlib.readPlist(info_plist) CheckPlistvalue(plist, 'UIDeviceFamily', [1]) entitlements_file = test.built_file_path('sig_test.xcent', chdir='app-bundle') if os.path.isfile(entitlements_file): expected_entitlements = open(entitlements_file).read() CheckEntitlements(result_file, expected_entitlements) test.pass_test()
agpl-3.0
Denisolt/IEEE-NYIT-MA
local/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/findstatic.py
463
1745
from __future__ import unicode_literals import os from django.contrib.staticfiles import finders from django.core.management.base import LabelCommand from django.utils.encoding import force_text class Command(LabelCommand): help = "Finds the absolute paths for the given static file(s)." label = 'static file' def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument('--first', action='store_false', dest='all', default=True, help="Only return the first match for each static file.") def handle_label(self, path, **options): verbosity = options['verbosity'] result = finders.find(path, all=options['all']) path = force_text(path) if verbosity >= 2: searched_locations = ("Looking in the following locations:\n %s" % "\n ".join(force_text(location) for location in finders.searched_locations)) else: searched_locations = '' if result: if not isinstance(result, (list, tuple)): result = [result] result = (force_text(os.path.realpath(path)) for path in result) if verbosity >= 1: file_list = '\n '.join(result) return ("Found '%s' here:\n %s\n%s" % (path, file_list, searched_locations)) else: return '\n'.join(result) else: message = ["No matching file found for '%s'." % path] if verbosity >= 2: message.append(searched_locations) if verbosity >= 1: self.stderr.write('\n'.join(message))
gpl-3.0
libscie/liberator
liberator/lib/python3.6/site-packages/django/contrib/gis/gdal/error.py
54
1997
""" This module houses the GDAL & SRS Exception objects, and the check_err() routine which checks the status code returned by GDAL/OGR methods. """ # #### GDAL & SRS Exceptions #### class GDALException(Exception): pass # Legacy name OGRException = GDALException class SRSException(Exception): pass class OGRIndexError(GDALException, KeyError): """ This exception is raised when an invalid index is encountered, and has the 'silent_variable_feature' attribute set to true. This ensures that django's templates proceed to use the next lookup type gracefully when an Exception is raised. Fixes ticket #4740. """ silent_variable_failure = True # #### GDAL/OGR error checking codes and routine #### # OGR Error Codes OGRERR_DICT = { 1: (GDALException, 'Not enough data.'), 2: (GDALException, 'Not enough memory.'), 3: (GDALException, 'Unsupported geometry type.'), 4: (GDALException, 'Unsupported operation.'), 5: (GDALException, 'Corrupt data.'), 6: (GDALException, 'OGR failure.'), 7: (SRSException, 'Unsupported SRS.'), 8: (GDALException, 'Invalid handle.'), } # CPL Error Codes # http://www.gdal.org/cpl__error_8h.html CPLERR_DICT = { 1: (GDALException, 'AppDefined'), 2: (GDALException, 'OutOfMemory'), 3: (GDALException, 'FileIO'), 4: (GDALException, 'OpenFailed'), 5: (GDALException, 'IllegalArg'), 6: (GDALException, 'NotSupported'), 7: (GDALException, 'AssertionFailed'), 8: (GDALException, 'NoWriteAccess'), 9: (GDALException, 'UserInterrupt'), 10: (GDALException, 'ObjectNull'), } ERR_NONE = 0 def check_err(code, cpl=False): """ Checks the given CPL/OGRERR, and raises an exception where appropriate. """ err_dict = CPLERR_DICT if cpl else OGRERR_DICT if code == ERR_NONE: return elif code in err_dict: e, msg = err_dict[code] raise e(msg) else: raise GDALException('Unknown error code: "%s"' % code)
cc0-1.0
Jonekee/chromium.src
ppapi/generators/idl_release.py
104
9847
#!/usr/bin/env python # 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. """ IDLRelease for PPAPI This file defines the behavior of the AST namespace which allows for resolving a symbol as one or more AST nodes given a Release or range of Releases. """ import sys from idl_log import ErrOut, InfoOut, WarnOut from idl_option import GetOption, Option, ParseOptions Option('release_debug', 'Debug Release data') Option('wgap', 'Ignore Release gap warning') # # Module level functions and data used for testing. # error = None warning = None def ReportReleaseError(msg): global error error = msg def ReportReleaseWarning(msg): global warning warning = msg def ReportClear(): global error, warning error = None warning = None # # IDLRelease # # IDLRelease is an object which stores the association of a given symbol # name, with an AST node for a range of Releases for that object. # # A vmin value of None indicates that the object begins at the earliest # available Release number. The value of vmin is always inclusive. # A vmax value of None indicates that the object is never deprecated, so # it exists until it is overloaded or until the latest available Release. # The value of vmax is always exclusive, representing the first Release # on which the object is no longer valid. class IDLRelease(object): def __init__(self, rmin, rmax): self.rmin = rmin self.rmax = rmax def __str__(self): if not self.rmin: rmin = '0' else: rmin = str(self.rmin) if not self.rmax: rmax = '+oo' else: rmax = str(self.rmax) return '[%s,%s)' % (rmin, rmax) def SetReleaseRange(self, rmin, rmax): self.rmin = rmin self.rmax = rmax # True, if Release falls within the interval [self.vmin, self.vmax) def IsRelease(self, release): if self.rmax and self.rmax <= release: return False if self.rmin and self.rmin > release: return False if GetOption('release_debug'): InfoOut.Log('%f is in %s' % (release, self)) return True # True, if Release falls within the interval [self.vmin, self.vmax) def InReleases(self, releases): if not releases: return False # Check last release first, since InRange does not match last item if self.IsRelease(releases[-1]): return True if len(releases) > 1: return self.InRange(releases[0], releases[-1]) return False # True, if interval [vmin, vmax) overlaps interval [self.vmin, self.vmax) def InRange(self, rmin, rmax): assert (rmin == None) or rmin < rmax # An min of None always passes a min bound test # An max of None always passes a max bound test if rmin is not None and self.rmax is not None: if self.rmax <= rmin: return False if rmax is not None and self.rmin is not None: if self.rmin >= rmax: return False if GetOption('release_debug'): InfoOut.Log('%f to %f is in %s' % (rmin, rmax, self)) return True def GetMinMax(self, releases = None): if not releases: return self.rmin, self.rmax if not self.rmin: rmin = releases[0] else: rmin = str(self.rmin) if not self.rmax: rmax = releases[-1] else: rmax = str(self.rmax) return (rmin, rmax) def SetMin(self, release): assert not self.rmin self.rmin = release def Error(self, msg): ReportReleaseError(msg) def Warn(self, msg): ReportReleaseWarning(msg) # # IDLReleaseList # # IDLReleaseList is a list based container for holding IDLRelease # objects in order. The IDLReleaseList can be added to, and searched by # range. Objects are stored in order, and must be added in order. # class IDLReleaseList(object): def __init__(self): self._nodes = [] def GetReleases(self): return self._nodes def FindRelease(self, release): for node in self._nodes: if node.IsRelease(release): return node return None def FindRange(self, rmin, rmax): assert (rmin == None) or rmin != rmax out = [] for node in self._nodes: if node.InRange(rmin, rmax): out.append(node) return out def AddNode(self, node): if GetOption('release_debug'): InfoOut.Log('\nAdding %s %s' % (node.Location(), node)) last = None # Check current releases in that namespace for cver in self._nodes: if GetOption('release_debug'): InfoOut.Log(' Checking %s' % cver) # We should only be missing a 'release' tag for the first item. if not node.rmin: node.Error('Missing release on overload of previous %s.' % cver.Location()) return False # If the node has no max, then set it to this one if not cver.rmax: cver.rmax = node.rmin if GetOption('release_debug'): InfoOut.Log(' Update %s' % cver) # if the max and min overlap, than's an error if cver.rmax > node.rmin: if node.rmax and cver.rmin >= node.rmax: node.Error('Declarations out of order.') else: node.Error('Overlap in releases: %s vs %s when adding %s' % (cver.rmax, node.rmin, node)) return False last = cver # Otherwise, the previous max and current min should match # unless this is the unlikely case of something being only # temporarily deprecated. if last and last.rmax != node.rmin: node.Warn('Gap in release numbers.') # If we made it here, this new node must be the 'newest' # and does not overlap with anything previously added, so # we can add it to the end of the list. if GetOption('release_debug'): InfoOut.Log('Done %s' % node) self._nodes.append(node) return True # # IDLReleaseMap # # A release map, can map from an float interface release, to a global # release string. # class IDLReleaseMap(object): def __init__(self, release_info): self.version_to_release = {} self.release_to_version = {} self.release_to_channel = {} for release, version, channel in release_info: self.version_to_release[version] = release self.release_to_version[release] = version self.release_to_channel[release] = channel self.releases = sorted(self.release_to_version.keys()) self.versions = sorted(self.version_to_release.keys()) def GetVersion(self, release): return self.release_to_version.get(release, None) def GetVersions(self): return self.versions def GetRelease(self, version): return self.version_to_release.get(version, None) def GetReleases(self): return self.releases def GetReleaseRange(self): return (self.releases[0], self.releases[-1]) def GetVersionRange(self): return (self.versions[0], self.version[-1]) def GetChannel(self, release): return self.release_to_channel.get(release, None) # # Test Code # def TestReleaseNode(): FooXX = IDLRelease(None, None) Foo1X = IDLRelease('M14', None) Foo23 = IDLRelease('M15', 'M16') assert FooXX.IsRelease('M13') assert FooXX.IsRelease('M14') assert FooXX.InRange('M13', 'M13A') assert FooXX.InRange('M14','M15') assert not Foo1X.IsRelease('M13') assert Foo1X.IsRelease('M14') assert Foo1X.IsRelease('M15') assert not Foo1X.InRange('M13', 'M14') assert not Foo1X.InRange('M13A', 'M14') assert Foo1X.InRange('M14', 'M15') assert Foo1X.InRange('M15', 'M16') assert not Foo23.InRange('M13', 'M14') assert not Foo23.InRange('M13A', 'M14') assert not Foo23.InRange('M14', 'M15') assert Foo23.InRange('M15', 'M16') assert Foo23.InRange('M14', 'M15A') assert Foo23.InRange('M15B', 'M17') assert not Foo23.InRange('M16', 'M17') print "TestReleaseNode - Passed" def TestReleaseListWarning(): FooXX = IDLRelease(None, None) Foo1X = IDLRelease('M14', None) Foo23 = IDLRelease('M15', 'M16') Foo45 = IDLRelease('M17', 'M18') # Add nodes out of order should fail ReportClear() releases = IDLReleaseList() assert releases.AddNode(Foo23) assert releases.AddNode(Foo45) assert warning print "TestReleaseListWarning - Passed" def TestReleaseListError(): FooXX = IDLRelease(None, None) Foo1X = IDLRelease('M14', None) Foo23 = IDLRelease('M15', 'M16') Foo45 = IDLRelease('M17', 'M18') # Add nodes out of order should fail ReportClear() releases = IDLReleaseList() assert releases.AddNode(FooXX) assert releases.AddNode(Foo23) assert not releases.AddNode(Foo1X) assert error print "TestReleaseListError - Passed" def TestReleaseListOK(): FooXX = IDLRelease(None, None) Foo1X = IDLRelease('M14', None) Foo23 = IDLRelease('M15', 'M16') Foo45 = IDLRelease('M17', 'M18') # Add nodes in order should work ReportClear() releases = IDLReleaseList() assert releases.AddNode(FooXX) assert releases.AddNode(Foo1X) assert releases.AddNode(Foo23) assert not error and not warning assert releases.AddNode(Foo45) assert warning assert releases.FindRelease('M13') == FooXX assert releases.FindRelease('M14') == Foo1X assert releases.FindRelease('M15') == Foo23 assert releases.FindRelease('M16') == None assert releases.FindRelease('M17') == Foo45 assert releases.FindRelease('M18') == None assert releases.FindRange('M13','M14') == [FooXX] assert releases.FindRange('M13','M17') == [FooXX, Foo1X, Foo23] assert releases.FindRange('M16','M17') == [] assert releases.FindRange(None, None) == [FooXX, Foo1X, Foo23, Foo45] # Verify we can find the correct versions print "TestReleaseListOK - Passed" def TestReleaseMap(): print "TestReleaseMap- Passed" def Main(args): TestReleaseNode() TestReleaseListWarning() TestReleaseListError() TestReleaseListOK() print "Passed" return 0 if __name__ == '__main__': sys.exit(Main(sys.argv[1:]))
bsd-3-clause
ghostflare76/scouter
scouter.host/scouter/host/who.py
11
1526
#!/usr/bin/env python # # original code from # https://github.com/giampaolo/psutil/blob/master/examples/ # # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ A clone of 'who' command; print information about users who are currently logged in. $ python examples/who.py giampaolo tty7 2014-02-23 17:25 (:0) giampaolo pts/7 2014-02-24 18:25 (:192.168.1.56) giampaolo pts/8 2014-02-24 18:25 (:0) giampaolo pts/9 2014-02-27 01:32 (:0) """ from datetime import datetime import psutil from scouter.lang.pack import * from scouter.lang.value import * def main(): users = psutil.get_users() for user in users: print("%-15s %-15s %s (%s)" % ( user.name, user.terminal or '-', datetime.fromtimestamp(user.started).strftime("%Y-%m-%d %H:%M"), user.host)) if __name__ == '__main__': main() def process(param): pack = MapPack() nameList = pack.newList("name") terminalList = pack.newList("terminal") startedList = pack.newList("started") hostList = pack.newList("host") users = psutil.users() for user in users: nameList.addStr(user.name) terminalList.addStr(user.terminal or '-') startedList.addStr(datetime.fromtimestamp(user.started).strftime("%Y-%m-%d %H:%M")) hostList.addStr(user.host) return pack
apache-2.0
YouLookFamiliar/swoop
setup.py
2
1584
import re import io from setuptools import setup from setuptools.command.test import test as TestCommand class Tox(TestCommand): user_options = [('tox-args=', 'a', "Arguments to pass to tox")] def initialize_options(self): TestCommand.initialize_options(self) self.tox_args = None def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): #import here, cause outside the eggs aren't loaded import tox import shlex args = self.tox_args if args: args = shlex.split(self.tox_args) tox.cmdline(args=args) with io.open('swoopi/__init__.py', 'r') as pkg_init: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', pkg_init.read(), re.MULTILINE).group(1) with io.open('README.rst', 'r', encoding='utf-8') as pkg_readme: readme = pkg_readme.read() if not version: raise RuntimeError('Can\'t find version information in package __init__') if not readme: raise RuntimeError('Can\'t find README.rst file') setup( name='swoopi', version=version, description='Camera interactions for the Raspberry Pi.', long_description=readme, url='https://github.com/swoopi/swoopi', author='Minn Soe', author_email='contributions@minn.io', packages=['swoopi'], install_requires=[], classifiers=[ 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 2.7' ] )
apache-2.0
trabucayre/gnuradio
gr-audio/examples/python/audio_to_file.py
6
1524
#!/usr/bin/env python # # Copyright 2004,2007,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # SPDX-License-Identifier: GPL-3.0-or-later # # from gnuradio import gr from gnuradio import audio from gnuradio import blocks from gnuradio.eng_arg import eng_float from argparse import ArgumentParser class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) parser = ArgumentParser() parser.add_argument("-I", "--audio-input", default="", help="pcm input device name. E.g., hw:0,0 or /dev/dsp") parser.add_argument("-r", "--sample-rate", type=eng_float, default=48000, help="set sample rate to RATE (%(default)r)") parser.add_argument("-N", "--nsamples", type=eng_float, help="number of samples to collect [default=+inf]") parser.add_argument('file_name', metavar='FILE-NAME', help="Output file path") args = parser.parse_args() sample_rate = int(args.sample_rate) src = audio.source(sample_rate, args.audio_input) dst = blocks.file_sink(gr.sizeof_float, args.file_name) if args.nsamples is None: self.connect((src, 0), dst) else: head = blocks.head(gr.sizeof_float, int(args.nsamples)) self.connect((src, 0), head, dst) if __name__ == '__main__': try: my_top_block().run() except KeyboardInterrupt: pass
gpl-3.0
karban/field
resources/python/logilab/common/compat.py
4
7473
# pylint: disable=E0601,W0622,W0611 # copyright 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-common. # # logilab-common 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. # # logilab-common 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 logilab-common. If not, see <http://www.gnu.org/licenses/>. """Wrappers around some builtins introduced in python 2.3, 2.4 and 2.5, making them available in for earlier versions of python. See another compatibility snippets from other projects: :mod:`lib2to3.fixes` :mod:`coverage.backward` :mod:`unittest2.compatibility` """ from __future__ import generators __docformat__ = "restructuredtext en" import os import sys from warnings import warn import __builtin__ as builtins # 2to3 will tranform '__builtin__' to 'builtins' if sys.version_info < (3, 0): str_to_bytes = str def str_encode(string, encoding): if isinstance(string, unicode): return string.encode(encoding) return str(string) else: def str_to_bytes(string): return str.encode(string) # we have to ignore the encoding in py3k to be able to write a string into a # TextIOWrapper or like object (which expect an unicode string) def str_encode(string, encoding): return str(string) # XXX shouldn't we remove this and just let 2to3 do his job ? try: callable = callable except NameError:# callable removed from py3k import collections def callable(something): return isinstance(something, collections.Callable) del collections if sys.version_info < (3, 0): raw_input = raw_input else: raw_input = input # Pythons 2 and 3 differ on where to get StringIO if sys.version_info < (3, 0): from cStringIO import StringIO FileIO = file BytesIO = StringIO reload = reload else: from io import FileIO, BytesIO, StringIO from imp import reload # Where do pickles come from? try: import cPickle as pickle except ImportError: import pickle from logilab.common.deprecation import deprecated from itertools import izip, chain, imap if sys.version_info < (3, 0):# 2to3 will remove the imports izip = deprecated('izip exists in itertools since py2.3')(izip) imap = deprecated('imap exists in itertools since py2.3')(imap) chain = deprecated('chain exists in itertools since py2.3')(chain) sum = deprecated('sum exists in builtins since py2.3')(sum) enumerate = deprecated('enumerate exists in builtins since py2.3')(enumerate) frozenset = deprecated('frozenset exists in builtins since py2.4')(frozenset) reversed = deprecated('reversed exists in builtins since py2.4')(reversed) sorted = deprecated('sorted exists in builtins since py2.4')(sorted) max = deprecated('max exists in builtins since py2.4')(max) # Python2.5 builtins try: any = any all = all except NameError: def any(iterable): """any(iterable) -> bool Return True if bool(x) is True for any x in the iterable. """ for elt in iterable: if elt: return True return False def all(iterable): """all(iterable) -> bool Return True if bool(x) is True for all values x in the iterable. """ for elt in iterable: if not elt: return False return True # Python2.5 subprocess added functions and exceptions try: from subprocess import Popen except ImportError: # gae or python < 2.3 class CalledProcessError(Exception): """This exception is raised when a process run by check_call() returns a non-zero exit status. The exit status will be stored in the returncode attribute.""" def __init__(self, returncode, cmd): self.returncode = returncode self.cmd = cmd def __str__(self): return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode) def call(*popenargs, **kwargs): """Run command with arguments. Wait for command to complete, then return the returncode attribute. The arguments are the same as for the Popen constructor. Example: retcode = call(["ls", "-l"]) """ # workaround: subprocess.Popen(cmd, stdout=sys.stdout) fails # see http://bugs.python.org/issue1531862 if "stdout" in kwargs: fileno = kwargs.get("stdout").fileno() del kwargs['stdout'] return Popen(stdout=os.dup(fileno), *popenargs, **kwargs).wait() return Popen(*popenargs, **kwargs).wait() def check_call(*popenargs, **kwargs): """Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute. The arguments are the same as for the Popen constructor. Example: check_call(["ls", "-l"]) """ retcode = call(*popenargs, **kwargs) cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] if retcode: raise CalledProcessError(retcode, cmd) return retcode try: from os.path import relpath except ImportError: # python < 2.6 from os.path import curdir, abspath, sep, commonprefix, pardir, join def relpath(path, start=curdir): """Return a relative version of a path""" if not path: raise ValueError("no path specified") start_list = abspath(start).split(sep) path_list = abspath(path).split(sep) # Work out how much of the filepath is shared by start and path. i = len(commonprefix([start_list, path_list])) rel_list = [pardir] * (len(start_list)-i) + path_list[i:] if not rel_list: return curdir return join(*rel_list) # XXX don't know why tests don't pass if I don't do that : _real_set, set = set, deprecated('set exists in builtins since py2.4')(set) if (2, 5) <= sys.version_info[:2]: InheritableSet = _real_set else: class InheritableSet(_real_set): """hacked resolving inheritancy issue from old style class in 2.4""" def __new__(cls, *args, **kwargs): if args: new_args = (args[0], ) else: new_args = () obj = _real_set.__new__(cls, *new_args) obj.__init__(*args, **kwargs) return obj # XXX shouldn't we remove this and just let 2to3 do his job ? # range or xrange? try: range = xrange except NameError: range = range # ConfigParser was renamed to the more-standard configparser try: import configparser except ImportError: import ConfigParser as configparser try: import json except ImportError: try: import simplejson as json except ImportError: json = None
gpl-2.0
rande/python-shirka
shirka/responders/status.py
1
2193
# vim: set fileencoding=utf-8 : from shirka.responders import Responder from shirka.consumers import BaseTestCase from random import choice import datetime STATUS = [ "You wanna piece of me, boy?", "Ready to roll out!", "Can I take your order?", "SCV good to go, sir.", "Alright! Bring it on!", ] MESSAGES = [ "I am ready.", "Direct my wrath.", "State your will.", "Your command?", "What would you ask of me?", "I hunger for battle...", "I hear you.", "How may I help?", "Your will?", "Hmm?", "You address me?", "Ready for battle.", "May I be of service?", "I stand ready.", "Yes?", "Awaiting instructions.", "Input command.", "Your thoughts...?", "Standing by.", "I'm here.", "What now...", "I'm waitin' on you!", "All crews reporting.", "Good day, commander.", "Go ahead HQ.", "You got my attention.", "Yes sir?", "Reportin' for duty.", ] class StatusResponder(Responder): def __init__(self): self.started_at = None self.word_counts = 0 def name(self): return 'status' def on_start(self, consumer): self.started_at = datetime.datetime.now() return False # return "%s" % choice(STATUS) def support(self, message): return True def generate(self, request): """ usage: status [full] return a random status message """ self.word_counts += len(request.content.split(" ")) words = request.content.split(" ", 2) if words[0] != 'status': return False if len(words) > 1 and words[1] == 'full': return "up since: %s, words parsed: %s" % (self.started_at, self.word_counts) return "%s" % choice(MESSAGES) class TestStatusResponder(BaseTestCase): def setUp(self): self.responder = StatusResponder() def test_support(self): self.assertTrue(self.responder.support(self.create_request("status"))) self.assertTrue(self.responder.support(self.create_request("fuu"))) def test_valid(self): self.assertIsNotNone(self.generate("status"))
mit
MotorolaMobilityLLC/external-chromium_org
third_party/android_testrunner/logger.py
171
2449
#!/usr/bin/python2.4 # # # Copyright 2007, The Android Open Source Project # # 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. """Simple logging utility. Dumps log messages to stdout, and optionally, to a log file. Init(path) must be called to enable logging to a file """ import datetime _LOG_FILE = None _verbose = False _log_time = True def Init(log_file_path): """Set the path to the log file""" global _LOG_FILE _LOG_FILE = log_file_path print "Using log file: %s" % _LOG_FILE def GetLogFilePath(): """Returns the path and name of the Log file""" global _LOG_FILE return _LOG_FILE def Log(new_str): """Appends new_str to the end of _LOG_FILE and prints it to stdout. Args: # new_str is a string. new_str: 'some message to log' """ msg = _PrependTimeStamp(new_str) print msg _WriteLog(msg) def _WriteLog(msg): global _LOG_FILE if _LOG_FILE is not None: file_handle = file(_LOG_FILE, 'a') file_handle.write('\n' + str(msg)) file_handle.close() def _PrependTimeStamp(log_string): """Returns the log_string prepended with current timestamp """ global _log_time if _log_time: return "# %s: %s" % (datetime.datetime.now().strftime("%m/%d/%y %H:%M:%S"), log_string) else: # timestamp logging disabled return log_string def SilentLog(new_str): """Silently log new_str. Unless verbose mode is enabled, will log new_str only to the log file Args: # new_str is a string. new_str: 'some message to log' """ global _verbose msg = _PrependTimeStamp(new_str) if _verbose: print msg _WriteLog(msg) def SetVerbose(new_verbose=True): """ Enable or disable verbose logging""" global _verbose _verbose = new_verbose def SetTimestampLogging(new_timestamp=True): """ Enable or disable outputting a timestamp with each log entry""" global _log_time _log_time = new_timestamp def main(): pass if __name__ == '__main__': main()
bsd-3-clause
shusenl/scikit-learn
examples/model_selection/plot_roc_crossval.py
247
3253
""" ============================================================= Receiver Operating Characteristic (ROC) with cross validation ============================================================= Example of Receiver Operating Characteristic (ROC) metric to evaluate classifier output quality using cross-validation. ROC curves typically feature true positive rate on the Y axis, and false positive rate on the X axis. This means that the top left corner of the plot is the "ideal" point - a false positive rate of zero, and a true positive rate of one. This is not very realistic, but it does mean that a larger area under the curve (AUC) is usually better. The "steepness" of ROC curves is also important, since it is ideal to maximize the true positive rate while minimizing the false positive rate. This example shows the ROC response of different datasets, created from K-fold cross-validation. Taking all of these curves, it is possible to calculate the mean area under curve, and see the variance of the curve when the training set is split into different subsets. This roughly shows how the classifier output is affected by changes in the training data, and how different the splits generated by K-fold cross-validation are from one another. .. note:: See also :func:`sklearn.metrics.auc_score`, :func:`sklearn.cross_validation.cross_val_score`, :ref:`example_model_selection_plot_roc.py`, """ print(__doc__) import numpy as np from scipy import interp import matplotlib.pyplot as plt from sklearn import svm, datasets from sklearn.metrics import roc_curve, auc from sklearn.cross_validation import StratifiedKFold ############################################################################### # Data IO and generation # import some data to play with iris = datasets.load_iris() X = iris.data y = iris.target X, y = X[y != 2], y[y != 2] n_samples, n_features = X.shape # Add noisy features random_state = np.random.RandomState(0) X = np.c_[X, random_state.randn(n_samples, 200 * n_features)] ############################################################################### # Classification and ROC analysis # Run classifier with cross-validation and plot ROC curves cv = StratifiedKFold(y, n_folds=6) classifier = svm.SVC(kernel='linear', probability=True, random_state=random_state) mean_tpr = 0.0 mean_fpr = np.linspace(0, 1, 100) all_tpr = [] for i, (train, test) in enumerate(cv): probas_ = classifier.fit(X[train], y[train]).predict_proba(X[test]) # Compute ROC curve and area the curve fpr, tpr, thresholds = roc_curve(y[test], probas_[:, 1]) mean_tpr += interp(mean_fpr, fpr, tpr) mean_tpr[0] = 0.0 roc_auc = auc(fpr, tpr) plt.plot(fpr, tpr, lw=1, label='ROC fold %d (area = %0.2f)' % (i, roc_auc)) plt.plot([0, 1], [0, 1], '--', color=(0.6, 0.6, 0.6), label='Luck') mean_tpr /= len(cv) mean_tpr[-1] = 1.0 mean_auc = auc(mean_fpr, mean_tpr) plt.plot(mean_fpr, mean_tpr, 'k--', label='Mean ROC (area = %0.2f)' % mean_auc, lw=2) plt.xlim([-0.05, 1.05]) plt.ylim([-0.05, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic example') plt.legend(loc="lower right") plt.show()
bsd-3-clause
kartikeys98/coala
coalib/bearlib/aspects/Formatting.py
7
11164
from coalib.bearlib.aspects import Root, Taste @Root.subaspect class Formatting: """ The visual appearance of source code. """ class docs: example = """ # Here is an example of Python code with lots of # formatting issues including: trailing spaces, missing spaces # around operators, strange and inconsistent indentation etc. z = 'hello'+'world' def f ( a): pass """ example_language = 'Python' importance_reason = """ A coding style (the of rules or guidelines used when writing the source code) can drastically affect the readability, and maintainability of a program and might as well introduce bugs. """ fix_suggestions = """ Defining a clearly and thoughtful coding style (based on the available ones given the programming language in use) and strictly respect it or apply it through out the implementation of a project. """ @Formatting.subaspect class Length: """ Hold sub-aspects for file and line length. """ class docs: example = """ # We assume that the maximum number of characters per line is 10 # and that the maximum number of lines per files is 3. def run(bear, file, filename, aspectlist): return bear.run(file, filename, aspectlist) """ example_language = 'Python' importance_reason = """ Too long lines of code and too large files result in code difficult to read, understand and maintain. """ fix_suggestions = """ Length issues can be fixed by writing shorter lines of code (splitting long lines into multiple shorter lines); writing shorter files (splitting files into modules, writing shorter methods and classes.). """ @Length.subaspect class LineLength: """ Number of characters found in a line of code. """ class docs: example = """ print('The length of this line is 38') """ example_langague = 'Python' importance_reason = """ Too long lines make code very difficult to read and maintain. """ fix_suggestions = """ Splitting long lines of code into multiple shorter lines whenever possible. Avoiding the usage of in-line language specific constructs whenever they result in too long lines. """ max_line_length = Taste[int]( 'Maximum number of character for a line.', (79, 80, 100, 120, 160), default=80) @Length.subaspect class FileLength: """ Number of lines found in a file. """ class docs: example = """ # This file would be a large file if we assume that the max number of # lines per file is 10 class Node: def __init__(self, value, left_most_child, left_sibling): self.value=value self.left_most_child=left_most_child self.left_sibling=left_sibling # This is example is just showing what this aspect is about, because # the max number of lines per file is usually 999. """ example_language = 'Python 3' importance_reason = """ Too long programs (or files) are difficult to read, maintain and understand. """ fix_suggestions = """ Splitting files into modules, writing shorter methods and classes. """ max_file_length = Taste[int]( 'Maximum number of line for a file', (999,), default=999) @Formatting.subaspect class Spacing: """ All whitespace found between non-whitespace characters. """ class docs: example = """ # Here is an example of code with spacing issues including # unnecessary blank lines and missing space around operators. def func( ): return 37*-+2 """ example_language = 'Python' importance_reason = """ Useless spacing affects the readability and maintainability of a code. """ fix_suggestions = """ Removing the trailing spaces and the meaningless blank lines. """ @Spacing.subaspect class TrailingSpace: """ Unnecessary whitespace at end of a line. Trailing space is all whitespace found after the last non-whitespace character on the line until the newline. This includes tabs "\\\\t", blank lines, blanks etc. """ class docs: example = """ def func( a ): pass """.replace('\n', '\t\n') example_language = 'Python' importance_reason = """ Trailing spaces make code less readable and maintainable. """ fix_suggestions = """ Removing the trailing spaces. """ allow_trailing_spaces = Taste[bool]( 'Determines whether or not trailing spaces should be allowed or not.', (True, False), default=False) @Spacing.subaspect class BlankLine: """ A line with zero characters. """ class docs: example = """ name = input('What is your name?') print('Hi, {}'.format(name)) """ example_language = 'Python 3' importance_reason = """ Various programming styles use blank lines in different places. The usage of blank lines affects the readability, maintainability and length of a code i.e blank lines can either make code longer, less readable and maintainable or do the reverse. """ fix_suggestions = """ Following specific rules about the usage of blank lines: using them only when necessary. """ @BlankLine.subaspect class BlankLineAfterDeclaration: """ Those found after declarations. """ class docs: example = """ #include <stdio.h> int main () { int a; float b; scanf("%d%f", &a, &b); printf("a = %d and b = %f", a, b); return 0; } """ example_language = 'C' importance_reason = """ Having a specific and reasonable number of blank lines after every block of declarations improves on the readability of the code. """ fix_suggestions = """ `BlankLintAfterDeclaration` issues can be fixed specifying (and of course using) a reasonable number of blank lines to use after block declaration. """ blank_lines_after_declarations = Taste[int]( 'Represents the number of blank lines after declarations', (0, 1, 2), default=0) @BlankLine.subaspect class BlankLineAfterProcedure: """ Those found after procedures or functions. """ class docs: example = """ #include <stdio.h> void proc(void){ printf("this does nothing"); } int add(float a, float b){ return a + b; } """ example_language = 'C' importance_reason = """ Having a specific and reasonable number of blank lines after every procedures improves on the readability of the code. """ fix_suggestions = """ `BlankLintAfterProcedure` issues can be fixed specifying (and of course using) a reasonable number of blank lines to use after procedures' definition. """ blank_lines_after_procedures = Taste[int]( 'Represents the number of blank lines to use after a procedure or' 'a function', (0, 1, 2), default=1) @BlankLine.subaspect class BlankLineAfterClass: """ Those found after classes' definitions. """ class docs: example = """ class SomeClass: def __init__(self): raise RuntimeError('Never instantiate this class') def func(): pass """ example_language = 'Python 3' importance_reason = """ Having a specific number of blank lines after every classes' definitions declarations improves on the readability of the code. """ fix_suggestions = """ """ blank_lines_after_class = Taste[int]( 'Represents the number of blank lines to use after a class' 'definition.', (1, 2), default=2) @BlankLine.subaspect class NewlineAtEOF: """ Newline character (usually '\\\\n', aka CR) found at the end of file. """ class docs: example = """ def do_nothing(): pass """ + ('\n') example_language = 'Python' importance_reason = """ A text file consists of a series of lines, each of which ends with a newline character (\\\\n). A file that is not empty and does not end with a newline is therefore not a text file. It's not just bad style, it can lead to unexpected behavior, utilities that are supposed to operate on text files may not cope well with files that don't end with a newline. """ fix_suggestions = """ `NewlineAtEOF` issues can be fixed by simply adding a newline at the end of the file. """ newline_at_EOF = Taste[bool]( 'If ``True``, enforce a newline at End Of File.', (True, False), default=True) @Spacing.subaspect class SpacesAroundOperator: """ Spacing around operators. """ class docs: example = """ def f(a, x): return 37+a[42 - x] """ example_language = 'Python' importance_reason = """ Having a specific and reasonable number of whitespace (blank) around operators improves on the readability of the code. """ fix_suggestions = """ `SpacesAroundOperator` issues can be fixed by simply specifying and the number of whitespace to be used after each operator. """ spaces_around_operators = Taste[int]( 'Represents the number of space to be used around operators.', (0, 1), default=1) spaces_before_colon = Taste[int]( 'Represents the number of blank spaces before colons.', (0, 1), default=0) spaces_after_colon = Taste[int]( 'Represents the number of blank spaces after colons.', (0, 1), default=1) @Formatting.subaspect class Quotation: """ Quotation mark used for strings and docstrings. """ class docs: example = """ # Here is an example of code where both '' and "" quotation mark # Are used. string = 'coala is always written with lowercase c.' string = "coala is always written with lowercase c." """ example_language = 'Python' importance_reason = """ Using the same quotation whenever possible in the code, improve on its readability by introducing consistency. """ fix_suggestions = """ Choosing a preferred quotation and using it everywhere (if possible). """ preferred_quotation = Taste[str]( 'Represents the preferred quotation', ('\'', '"'), default='\'')
agpl-3.0
camillemonchicourt/Geotrek
geotrek/core/migrations/0002_auto__del_field_trail_id__del_field_trail_date_update__del_field_trail.py
1
14912
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models from django.conf import settings class Migration(SchemaMigration): def forwards(self, orm): # Keep track of previous paths associated to trails by_paths = {} for path, trail in db.execute('SELECT id, sentier FROM l_t_troncon;'): by_paths.setdefault(trail, []).append(path) # Deleting trail reference from path db.delete_column('l_t_troncon', 'sentier') # Fields are now in topology model db.delete_column('l_t_sentier', 'date_update') db.delete_column('l_t_sentier', 'date_insert') # Adding field 'Trail.topo_object' db.add_column('l_t_sentier', 'topo_object', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['core.Topology'], null=True, db_column='evenement'), keep_default=False) # Restore NAIVELY previous trails from geotrek.core.models import Topology trails = db.execute('SELECT id FROM l_t_sentier') print "Migrating %s trails" % len(trails) for (trail,) in trails: topo = Topology() topo.kind = 'TRAIL' topo.save() print "Created empty topology %s" % topo.pk db.execute('UPDATE l_t_sentier SET evenement = %s WHERE id = %s', (topo.pk, trail)) trail_paths = by_paths.get(trail, []) print "%s paths for trail %s" % (len(trail_paths), trail) for path in trail_paths: db.execute('INSERT INTO e_r_evenement_troncon (troncon, evenement, pk_debut, pk_fin, ordre) VALUES (%s,%s, 0.0, 1.0, 1)', ( path, topo.pk)) db.execute('ALTER TABLE l_t_sentier ALTER COLUMN evenement SET NOT NULL') db.execute('ALTER TABLE l_t_sentier DROP CONSTRAINT l_t_sentier_pkey CASCADE') db.execute('ALTER TABLE l_t_sentier DROP COLUMN IF EXISTS id') db.execute('ALTER TABLE l_t_sentier ADD CONSTRAINT l_t_sentier_pkey PRIMARY KEY (evenement)') def backwards(self, orm): # User chose to not deal with backwards NULL issues for 'Trail.id' raise RuntimeError("Cannot reverse this migration. 'Trail.id' and its values cannot be restored.") # The following code is provided here to aid in writing a correct migration # Adding field 'Trail.id' db.add_column('l_t_sentier', u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True), keep_default=False) # User chose to not deal with backwards NULL issues for 'Trail.date_update' raise RuntimeError("Cannot reverse this migration. 'Trail.date_update' and its values cannot be restored.") # The following code is provided here to aid in writing a correct migration # Adding field 'Trail.date_update' db.add_column('l_t_sentier', 'date_update', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, db_column='date_update', blank=True), keep_default=False) # User chose to not deal with backwards NULL issues for 'Trail.date_insert' raise RuntimeError("Cannot reverse this migration. 'Trail.date_insert' and its values cannot be restored.") # The following code is provided here to aid in writing a correct migration # Adding field 'Trail.date_insert' db.add_column('l_t_sentier', 'date_insert', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, db_column='date_insert', blank=True), keep_default=False) # Deleting field 'Trail.topo_object' db.delete_column('l_t_sentier', 'evenement') # Adding field 'Path.trail' db.add_column('l_t_troncon', 'trail', self.gf('django.db.models.fields.related.ForeignKey')(related_name='paths', null=True, to=orm['core.Trail'], db_column='sentier', blank=True), keep_default=False) models = { u'authent.structure': { 'Meta': {'ordering': "['name']", 'object_name': 'Structure'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '256'}) }, u'core.comfort': { 'Meta': {'ordering': "['comfort']", 'object_name': 'Comfort', 'db_table': "'l_b_confort'"}, 'comfort': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_column': "'confort'"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'structure': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['authent.Structure']", 'db_column': "'structure'"}) }, u'core.datasource': { 'Meta': {'ordering': "['source']", 'object_name': 'Datasource', 'db_table': "'l_b_source'"}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'source': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'structure': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['authent.Structure']", 'db_column': "'structure'"}) }, u'core.network': { 'Meta': {'ordering': "['network']", 'object_name': 'Network', 'db_table': "'l_b_reseau'"}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'network': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_column': "'reseau'"}), 'structure': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['authent.Structure']", 'db_column': "'structure'"}) }, u'core.path': { 'Meta': {'object_name': 'Path', 'db_table': "'l_t_troncon'"}, 'arrival': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '250', 'null': 'True', 'db_column': "'arrivee'", 'blank': 'True'}), 'ascent': ('django.db.models.fields.IntegerField', [], {'default': '0', 'null': 'True', 'db_column': "'denivelee_positive'", 'blank': 'True'}), 'comfort': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'paths'", 'null': 'True', 'db_column': "'confort'", 'to': u"orm['core.Comfort']"}), 'comments': ('django.db.models.fields.TextField', [], {'null': 'True', 'db_column': "'remarques'", 'blank': 'True'}), 'datasource': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'paths'", 'null': 'True', 'db_column': "'source'", 'to': u"orm['core.Datasource']"}), 'date_insert': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_column': "'date_insert'", 'blank': 'True'}), 'date_update': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_column': "'date_update'", 'blank': 'True'}), 'departure': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '250', 'null': 'True', 'db_column': "'depart'", 'blank': 'True'}), 'descent': ('django.db.models.fields.IntegerField', [], {'default': '0', 'null': 'True', 'db_column': "'denivelee_negative'", 'blank': 'True'}), 'geom': ('django.contrib.gis.db.models.fields.LineStringField', [], {'srid': '%s' % settings.SRID, 'spatial_index': 'False'}), 'geom_3d': ('django.contrib.gis.db.models.fields.GeometryField', [], {'default': 'None', 'dim': '3', 'spatial_index': 'False', 'null': 'True', 'srid': '%s' % settings.SRID}), 'geom_cadastre': ('django.contrib.gis.db.models.fields.LineStringField', [], {'srid': '%s' % settings.SRID, 'null': 'True', 'spatial_index': 'False'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'length': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'db_column': "'longueur'", 'blank': 'True'}), 'max_elevation': ('django.db.models.fields.IntegerField', [], {'default': '0', 'null': 'True', 'db_column': "'altitude_maximum'", 'blank': 'True'}), 'min_elevation': ('django.db.models.fields.IntegerField', [], {'default': '0', 'null': 'True', 'db_column': "'altitude_minimum'", 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'db_column': "'nom'", 'blank': 'True'}), 'networks': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'paths'", 'to': u"orm['core.Network']", 'db_table': "'l_r_troncon_reseau'", 'blank': 'True', 'symmetrical': 'False', 'null': 'True'}), 'slope': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'db_column': "'pente'", 'blank': 'True'}), 'stake': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'paths'", 'null': 'True', 'db_column': "'enjeu'", 'to': u"orm['core.Stake']"}), 'structure': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['authent.Structure']", 'db_column': "'structure'"}), 'usages': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'paths'", 'to': u"orm['core.Usage']", 'db_table': "'l_r_troncon_usage'", 'blank': 'True', 'symmetrical': 'False', 'null': 'True'}), 'valid': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_column': "'valide'"}) }, u'core.pathaggregation': { 'Meta': {'ordering': "['id']", 'object_name': 'PathAggregation', 'db_table': "'e_r_evenement_troncon'"}, 'end_position': ('django.db.models.fields.FloatField', [], {'db_column': "'pk_fin'", 'db_index': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'order': ('django.db.models.fields.IntegerField', [], {'default': '0', 'null': 'True', 'db_column': "'ordre'", 'blank': 'True'}), 'path': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'aggregations'", 'on_delete': 'models.DO_NOTHING', 'db_column': "'troncon'", 'to': u"orm['core.Path']"}), 'start_position': ('django.db.models.fields.FloatField', [], {'db_column': "'pk_debut'", 'db_index': 'True'}), 'topo_object': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'aggregations'", 'db_column': "'evenement'", 'to': u"orm['core.Topology']"}) }, u'core.stake': { 'Meta': {'ordering': "['id']", 'object_name': 'Stake', 'db_table': "'l_b_enjeu'"}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'stake': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_column': "'enjeu'"}), 'structure': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['authent.Structure']", 'db_column': "'structure'"}) }, u'core.topology': { 'Meta': {'object_name': 'Topology', 'db_table': "'e_t_evenement'"}, 'ascent': ('django.db.models.fields.IntegerField', [], {'default': '0', 'null': 'True', 'db_column': "'denivelee_positive'", 'blank': 'True'}), 'date_insert': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_column': "'date_insert'", 'blank': 'True'}), 'date_update': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_column': "'date_update'", 'blank': 'True'}), 'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_column': "'supprime'"}), 'descent': ('django.db.models.fields.IntegerField', [], {'default': '0', 'null': 'True', 'db_column': "'denivelee_negative'", 'blank': 'True'}), 'geom': ('django.contrib.gis.db.models.fields.GeometryField', [], {'default': 'None', 'srid': '%s' % settings.SRID, 'null': 'True', 'spatial_index': 'False'}), 'geom_3d': ('django.contrib.gis.db.models.fields.GeometryField', [], {'default': 'None', 'dim': '3', 'spatial_index': 'False', 'null': 'True', 'srid': '%s' % settings.SRID}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'kind': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'length': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'db_column': "'longueur'", 'blank': 'True'}), 'max_elevation': ('django.db.models.fields.IntegerField', [], {'default': '0', 'null': 'True', 'db_column': "'altitude_maximum'", 'blank': 'True'}), 'min_elevation': ('django.db.models.fields.IntegerField', [], {'default': '0', 'null': 'True', 'db_column': "'altitude_minimum'", 'blank': 'True'}), 'offset': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'db_column': "'decallage'"}), 'paths': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['core.Path']", 'through': u"orm['core.PathAggregation']", 'db_column': "'troncons'", 'symmetrical': 'False'}), 'slope': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'db_column': "'pente'", 'blank': 'True'}) }, u'core.trail': { 'Meta': {'ordering': "['name']", 'object_name': 'Trail', 'db_table': "'l_t_sentier'", '_ormbases': [u'core.Topology']}, 'arrival': ('django.db.models.fields.CharField', [], {'max_length': '64', 'db_column': "'arrivee'"}), 'comments': ('django.db.models.fields.TextField', [], {'default': "''", 'db_column': "'commentaire'", 'blank': 'True'}), 'departure': ('django.db.models.fields.CharField', [], {'max_length': '64', 'db_column': "'depart'"}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '64', 'db_column': "'nom'"}), 'structure': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['authent.Structure']", 'db_column': "'structure'"}), 'topo_object': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['core.Topology']", 'unique': 'True', 'primary_key': 'True', 'db_column': "'evenement'"}) }, u'core.usage': { 'Meta': {'ordering': "['usage']", 'object_name': 'Usage', 'db_table': "'l_b_usage'"}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'structure': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['authent.Structure']", 'db_column': "'structure'"}), 'usage': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_column': "'usage'"}) } } complete_apps = ['core']
bsd-2-clause
PaddlePaddle/Paddle
python/paddle/fluid/tests/unittests/test_hash_op.py
2
4770
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import numpy as np from op_test import OpTest import paddle.fluid as fluid class TestHashOp(OpTest): def setUp(self): self.op_type = "hash" self.init_test_case() self.inputs = {'X': (self.in_seq, self.lod)} self.attrs = {'num_hash': 2, 'mod_by': 10000} self.outputs = {'Out': (self.out_seq, self.lod)} def init_test_case(self): np.random.seed(1) self.in_seq = np.random.randint(0, 10, (8, 1)).astype("int32") self.lod = [[2, 6]] self.out_seq = [[[3481], [7475]], [[1719], [5986]], [[8473], [694]], [[3481], [7475]], [[4372], [9456]], [[4372], [9456]], [[6897], [3218]], [[9038], [7951]]] self.out_seq = np.array(self.out_seq) def test_check_output(self): self.check_output() class TestHashNotLoDOp(TestHashOp): def setUp(self): self.op_type = "hash" self.init_test_case() self.inputs = {'X': self.in_seq} self.attrs = {'num_hash': 2, 'mod_by': 10000} self.outputs = {'Out': self.out_seq} def init_test_case(self): np.random.seed(1) self.in_seq = np.random.randint(0, 10, (8, 1)).astype("int32") self.out_seq = [[[3481], [7475]], [[1719], [5986]], [[8473], [694]], [[3481], [7475]], [[4372], [9456]], [[4372], [9456]], [[6897], [3218]], [[9038], [7951]]] self.out_seq = np.array(self.out_seq) def test_check_output(self): self.check_output() class TestHashOp2(TestHashOp): """ Case: int64 type input """ def setUp(self): self.op_type = "hash" self.init_test_case() self.inputs = {'X': self.in_seq} self.attrs = {'num_hash': 2, 'mod_by': 10000} self.outputs = {'Out': self.out_seq} def init_test_case(self): self.in_seq = np.array([1, 2**32 + 1]).reshape((2, 1)).astype("int64") self.out_seq = np.array([1269, 9609, 3868, 7268]).reshape((2, 2, 1)) def test_check_output(self): self.check_output() class TestHashOp3(TestHashOp): """ Case: int64 type input int64 type mod_by attr """ def setUp(self): self.op_type = "hash" self.init_test_case() self.inputs = {'X': self.in_seq} self.attrs = {'num_hash': 2, 'mod_by': 2**32} self.outputs = {'Out': self.out_seq} def init_test_case(self): self.in_seq = np.array([10, 5]).reshape((2, 1)).astype("int64") self.out_seq = np.array( [1204014882, 393011615, 3586283837, 2814821595]).reshape((2, 2, 1)) def test_check_output(self): self.check_output() class TestHashOpError(unittest.TestCase): def test_errors(self): with fluid.program_guard(fluid.Program(), fluid.Program()): input_data = np.random.randint(0, 10, (8, 1)).astype("int32") def test_Variable(): # the input type must be Variable fluid.layers.hash(input=input_data, hash_size=2**32) self.assertRaises(TypeError, test_Variable) def test_type(): # dtype must be int32, int64. x2 = fluid.layers.data( name='x2', shape=[1], dtype="float32", lod_level=1) fluid.layers.hash(input=x2, hash_size=2**32) self.assertRaises(TypeError, test_type) def test_hash_size_type(): # hash_size dtype must be int32, int64. x3 = fluid.layers.data( name='x3', shape=[1], dtype="int32", lod_level=1) fluid.layers.hash(input=x3, hash_size=1024.5) self.assertRaises(TypeError, test_hash_size_type) def test_num_hash_type(): # num_hash dtype must be int32, int64. x4 = fluid.layers.data( name='x4', shape=[1], dtype="int32", lod_level=1) fluid.layers.hash(input=x4, hash_size=2**32, num_hash=2.5) self.assertRaises(TypeError, test_num_hash_type) if __name__ == "__main__": unittest.main()
apache-2.0
jonieli/flask
tests/test_user_error_handler.py
150
3483
# -*- coding: utf-8 -*- from werkzeug.exceptions import Forbidden, InternalServerError import flask def test_error_handler_no_match(): app = flask.Flask(__name__) class CustomException(Exception): pass @app.errorhandler(CustomException) def custom_exception_handler(e): assert isinstance(e, CustomException) return 'custom' @app.errorhandler(500) def handle_500(e): return type(e).__name__ @app.route('/custom') def custom_test(): raise CustomException() @app.route('/keyerror') def key_error(): raise KeyError() c = app.test_client() assert c.get('/custom').data == b'custom' assert c.get('/keyerror').data == b'KeyError' def test_error_handler_subclass(): app = flask.Flask(__name__) class ParentException(Exception): pass class ChildExceptionUnregistered(ParentException): pass class ChildExceptionRegistered(ParentException): pass @app.errorhandler(ParentException) def parent_exception_handler(e): assert isinstance(e, ParentException) return 'parent' @app.errorhandler(ChildExceptionRegistered) def child_exception_handler(e): assert isinstance(e, ChildExceptionRegistered) return 'child-registered' @app.route('/parent') def parent_test(): raise ParentException() @app.route('/child-unregistered') def unregistered_test(): raise ChildExceptionUnregistered() @app.route('/child-registered') def registered_test(): raise ChildExceptionRegistered() c = app.test_client() assert c.get('/parent').data == b'parent' assert c.get('/child-unregistered').data == b'parent' assert c.get('/child-registered').data == b'child-registered' def test_error_handler_http_subclass(): app = flask.Flask(__name__) class ForbiddenSubclassRegistered(Forbidden): pass class ForbiddenSubclassUnregistered(Forbidden): pass @app.errorhandler(403) def code_exception_handler(e): assert isinstance(e, Forbidden) return 'forbidden' @app.errorhandler(ForbiddenSubclassRegistered) def subclass_exception_handler(e): assert isinstance(e, ForbiddenSubclassRegistered) return 'forbidden-registered' @app.route('/forbidden') def forbidden_test(): raise Forbidden() @app.route('/forbidden-registered') def registered_test(): raise ForbiddenSubclassRegistered() @app.route('/forbidden-unregistered') def unregistered_test(): raise ForbiddenSubclassUnregistered() c = app.test_client() assert c.get('/forbidden').data == b'forbidden' assert c.get('/forbidden-unregistered').data == b'forbidden' assert c.get('/forbidden-registered').data == b'forbidden-registered' def test_error_handler_blueprint(): bp = flask.Blueprint('bp', __name__) @bp.errorhandler(500) def bp_exception_handler(e): return 'bp-error' @bp.route('/error') def bp_test(): raise InternalServerError() app = flask.Flask(__name__) @app.errorhandler(500) def app_exception_handler(e): return 'app-error' @app.route('/error') def app_test(): raise InternalServerError() app.register_blueprint(bp, url_prefix='/bp') c = app.test_client() assert c.get('/error').data == b'app-error' assert c.get('/bp/error').data == b'bp-error'
bsd-3-clause
mitar/django-filer
filer/tests/utils.py
12
2446
#-*- coding: utf-8 -*- from django.core.files import File as DjangoFile from django.test.testcases import TestCase from filer.tests.helpers import create_image from filer.utils.loader import load from filer.utils.zip import unzip from zipfile import ZipFile import os #=============================================================================== # Some target classes for the classloading tests #=============================================================================== class TestTargetSuperClass(object): pass class TestTargetClass(TestTargetSuperClass): pass #=============================================================================== # Testing the classloader #=============================================================================== class ClassLoaderTestCase(TestCase): ''' Tests filer.utils.loader.load() ''' def test_loader_loads_strings_properly(self): target = 'filer.tests.utils.TestTargetClass' result = load(target, None) # Should return an instance self.assertEqual(result.__class__, TestTargetClass) def test_loader_loads_class(self): result = load(TestTargetClass(), TestTargetSuperClass) self.assertEqual(result.__class__, TestTargetClass) def test_loader_loads_subclass(self): result = load(TestTargetClass, TestTargetSuperClass) self.assertEqual(result.__class__, TestTargetClass) #=============================================================================== # Testing the zipping/unzipping of files #=============================================================================== class ZippingTestCase(TestCase): def create_fixtures(self): self.img = create_image() self.image_name = 'test_file.jpg' self.filename = os.path.join(os.path.dirname(__file__), self.image_name) self.img.save(self.filename, 'JPEG') self.file = DjangoFile(open(self.filename), name=self.image_name) self.zipfilename = 'test_zip.zip' self.zip = ZipFile(self.zipfilename, 'a') self.zip.write(self.filename) self.zip.close() def tearDown(self): # Clean up the created zip file os.remove(self.zipfilename) os.remove(self.filename) def test_unzipping_works(self): self.create_fixtures() result = unzip(self.zipfilename) self.assertEqual(result[0][0].name, self.file.name)
bsd-3-clause
aselims/androguard
androguard/gui/renamewindow.py
26
1287
from PySide import QtCore, QtGui from androguard.core import androconf class RenameDialog(QtGui.QDialog): ''' parent: SourceWindow that started the new XrefDialog ''' def __init__(self, parent=None, win=None, element="", info=()): super(RenameDialog, self).__init__(parent) self.sourceWin = parent self.info = info self.element = element title = "Rename: " + element self.setWindowTitle(title) layout = QtGui.QGridLayout() question = QtGui.QLabel("Please enter new name:") layout.addWidget(question, 0, 0) self.lineEdit = QtGui.QLineEdit() layout.addWidget(self.lineEdit, 0, 1) self.buttonOK = QtGui.QPushButton("OK", self) layout.addWidget(self.buttonOK, 1, 1) self.buttonCancel = QtGui.QPushButton("Cancel", self) layout.addWidget(self.buttonCancel, 1, 0) self.lineEdit.setText(self.element) self.setLayout(layout) self.buttonCancel.clicked.connect(self.cancelClicked) self.buttonOK.clicked.connect(self.okClicked) def cancelClicked(self): self.close() def okClicked(self): self.sourceWin.renameElement(self.element, self.lineEdit.text(), self.info) self.close()
apache-2.0
thingsinjars/electron
script/build.py
155
1166
#!/usr/bin/env python import argparse import os import subprocess import sys from lib.util import atom_gyp CONFIGURATIONS = ['Release', 'Debug'] SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) def main(): os.chdir(SOURCE_ROOT) ninja = os.path.join('vendor', 'depot_tools', 'ninja') if sys.platform == 'win32': ninja += '.exe' args = parse_args() for config in args.configuration: build_path = os.path.join('out', config[0]) ret = subprocess.call([ninja, '-C', build_path, args.target]) if ret != 0: sys.exit(ret) def parse_args(): parser = argparse.ArgumentParser(description='Build project') parser.add_argument('-c', '--configuration', help='Build with Release or Debug configuration', nargs='+', default=CONFIGURATIONS, required=False) parser.add_argument('-t', '--target', help='Build specified target', default=atom_gyp()['project_name%'], required=False) return parser.parse_args() if __name__ == '__main__': sys.exit(main())
mit
bsmrstu-warriors/Moytri--The-Drone-Aider
Lib/distutils/command/install_lib.py
251
8338
"""distutils.command.install_lib Implements the Distutils 'install_lib' command (install all Python modules).""" __revision__ = "$Id$" import os import sys from distutils.core import Command from distutils.errors import DistutilsOptionError # Extension for Python source files. if hasattr(os, 'extsep'): PYTHON_SOURCE_EXTENSION = os.extsep + "py" else: PYTHON_SOURCE_EXTENSION = ".py" class install_lib(Command): description = "install all Python modules (extensions and pure Python)" # The byte-compilation options are a tad confusing. Here are the # possible scenarios: # 1) no compilation at all (--no-compile --no-optimize) # 2) compile .pyc only (--compile --no-optimize; default) # 3) compile .pyc and "level 1" .pyo (--compile --optimize) # 4) compile "level 1" .pyo only (--no-compile --optimize) # 5) compile .pyc and "level 2" .pyo (--compile --optimize-more) # 6) compile "level 2" .pyo only (--no-compile --optimize-more) # # The UI for this is two option, 'compile' and 'optimize'. # 'compile' is strictly boolean, and only decides whether to # generate .pyc files. 'optimize' is three-way (0, 1, or 2), and # decides both whether to generate .pyo files and what level of # optimization to use. user_options = [ ('install-dir=', 'd', "directory to install to"), ('build-dir=','b', "build directory (where to install from)"), ('force', 'f', "force installation (overwrite existing files)"), ('compile', 'c', "compile .py to .pyc [default]"), ('no-compile', None, "don't compile .py files"), ('optimize=', 'O', "also compile with optimization: -O1 for \"python -O\", " "-O2 for \"python -OO\", and -O0 to disable [default: -O0]"), ('skip-build', None, "skip the build steps"), ] boolean_options = ['force', 'compile', 'skip-build'] negative_opt = {'no-compile' : 'compile'} def initialize_options(self): # let the 'install' command dictate our installation directory self.install_dir = None self.build_dir = None self.force = 0 self.compile = None self.optimize = None self.skip_build = None def finalize_options(self): # Get all the information we need to install pure Python modules # from the umbrella 'install' command -- build (source) directory, # install (target) directory, and whether to compile .py files. self.set_undefined_options('install', ('build_lib', 'build_dir'), ('install_lib', 'install_dir'), ('force', 'force'), ('compile', 'compile'), ('optimize', 'optimize'), ('skip_build', 'skip_build'), ) if self.compile is None: self.compile = 1 if self.optimize is None: self.optimize = 0 if not isinstance(self.optimize, int): try: self.optimize = int(self.optimize) if self.optimize not in (0, 1, 2): raise AssertionError except (ValueError, AssertionError): raise DistutilsOptionError, "optimize must be 0, 1, or 2" def run(self): # Make sure we have built everything we need first self.build() # Install everything: simply dump the entire contents of the build # directory to the installation directory (that's the beauty of # having a build directory!) outfiles = self.install() # (Optionally) compile .py to .pyc if outfiles is not None and self.distribution.has_pure_modules(): self.byte_compile(outfiles) # -- Top-level worker functions ------------------------------------ # (called from 'run()') def build(self): if not self.skip_build: if self.distribution.has_pure_modules(): self.run_command('build_py') if self.distribution.has_ext_modules(): self.run_command('build_ext') def install(self): if os.path.isdir(self.build_dir): outfiles = self.copy_tree(self.build_dir, self.install_dir) else: self.warn("'%s' does not exist -- no Python modules to install" % self.build_dir) return return outfiles def byte_compile(self, files): if sys.dont_write_bytecode: self.warn('byte-compiling is disabled, skipping.') return from distutils.util import byte_compile # Get the "--root" directory supplied to the "install" command, # and use it as a prefix to strip off the purported filename # encoded in bytecode files. This is far from complete, but it # should at least generate usable bytecode in RPM distributions. install_root = self.get_finalized_command('install').root if self.compile: byte_compile(files, optimize=0, force=self.force, prefix=install_root, dry_run=self.dry_run) if self.optimize > 0: byte_compile(files, optimize=self.optimize, force=self.force, prefix=install_root, verbose=self.verbose, dry_run=self.dry_run) # -- Utility methods ----------------------------------------------- def _mutate_outputs(self, has_any, build_cmd, cmd_option, output_dir): if not has_any: return [] build_cmd = self.get_finalized_command(build_cmd) build_files = build_cmd.get_outputs() build_dir = getattr(build_cmd, cmd_option) prefix_len = len(build_dir) + len(os.sep) outputs = [] for file in build_files: outputs.append(os.path.join(output_dir, file[prefix_len:])) return outputs def _bytecode_filenames(self, py_filenames): bytecode_files = [] for py_file in py_filenames: # Since build_py handles package data installation, the # list of outputs can contain more than just .py files. # Make sure we only report bytecode for the .py files. ext = os.path.splitext(os.path.normcase(py_file))[1] if ext != PYTHON_SOURCE_EXTENSION: continue if self.compile: bytecode_files.append(py_file + "c") if self.optimize > 0: bytecode_files.append(py_file + "o") return bytecode_files # -- External interface -------------------------------------------- # (called by outsiders) def get_outputs(self): """Return the list of files that would be installed if this command were actually run. Not affected by the "dry-run" flag or whether modules have actually been built yet. """ pure_outputs = \ self._mutate_outputs(self.distribution.has_pure_modules(), 'build_py', 'build_lib', self.install_dir) if self.compile: bytecode_outputs = self._bytecode_filenames(pure_outputs) else: bytecode_outputs = [] ext_outputs = \ self._mutate_outputs(self.distribution.has_ext_modules(), 'build_ext', 'build_lib', self.install_dir) return pure_outputs + bytecode_outputs + ext_outputs def get_inputs(self): """Get the list of files that are input to this command, ie. the files that get installed as they are named in the build tree. The files in this list correspond one-to-one to the output filenames returned by 'get_outputs()'. """ inputs = [] if self.distribution.has_pure_modules(): build_py = self.get_finalized_command('build_py') inputs.extend(build_py.get_outputs()) if self.distribution.has_ext_modules(): build_ext = self.get_finalized_command('build_ext') inputs.extend(build_ext.get_outputs()) return inputs
gpl-3.0
smrjan/seldon-server
docker/examples/iris/vw/vw_pipeline.py
2
1126
import sys, getopt, argparse import seldon.pipeline.basic_transforms as bt import seldon.pipeline.auto_transforms as pauto import seldon.pipeline.util as sutl from sklearn.pipeline import Pipeline import seldon.vw as vw import sys def run_pipeline(events,models): tNameId = bt.Feature_id_transform(min_size=0,exclude_missing=True,zero_based=True,input_feature="name",output_feature="nameId") tAuto = pauto.Auto_transform(max_values_numeric_categorical=2,exclude=["nameId","name"]) vwc = vw.VWClassifier(target="nameId",target_readable="name") transformers = [("tName",tNameId),("tAuto",tAuto),("vw",vwc)] p = Pipeline(transformers) pw = sutl.Pipeline_wrapper() df = pw.create_dataframe_from_files(events) df2 = p.fit(df) pw.save_pipeline(p,models) if __name__ == '__main__': parser = argparse.ArgumentParser(prog='xgb_pipeline') parser.add_argument('--events', help='events folder', required=True) parser.add_argument('--models', help='output models folder', required=True) args = parser.parse_args() opts = vars(args) run_pipeline([args.events],args.models)
apache-2.0
ridfrustum/django-assets
django_assets/templatetags/assets.py
5
5584
import tokenize import warnings from django import template from django_assets import Bundle from django_assets.env import get_env from webassets import six from webassets.exceptions import ImminentDeprecationWarning def parse_debug_value(value): """Django templates do not know what a boolean is, and anyway we need to support the 'merge' option.""" if isinstance(value, bool): return value try: from webassets.env import parse_debug_value return parse_debug_value(value) except ValueError: raise template.TemplateSyntaxError( '"debug" argument must be one of the strings ' '"true", "false" or "merge", not "%s"' % value) class AssetsNode(template.Node): # For testing, to inject a mock bundle BundleClass = Bundle def __init__(self, filters, depends, output, debug, files, childnodes): self.childnodes = childnodes self.output = output self.files = files self.depends = depends self.filters = filters self.debug = debug def resolve(self, context={}): """We allow variables to be used for all arguments; this function resolves all data against a given context. This is a separate method as the management command must have the ability to check if the tag can be resolved without a context. """ def resolve_var(x): if x is None: return None else: try: return template.Variable(x).resolve(context) except template.VariableDoesNotExist: # Django seems to hide those; we don't want to expose # them either, I guess. raise def resolve_depends(x): # Adapter to parse django template tags for depends. # into a webassets compabitble list if multiple depends is passed. # Django templates support depends in a (comma delimited form. e.g., # # {% assets filters="jsmin", output="path/to/file.js", depends="watchfile.js,second/watch/file.js" "projectfile.js" %} value = resolve_var(x) if isinstance(value, six.text_type): value = value.split(',') return value def resolve_bundle(name): # If a bundle with that name exists, use it. Otherwise, # assume a filename is meant. try: return get_env()[name] except KeyError: return name return self.BundleClass( *[resolve_bundle(resolve_var(f)) for f in self.files], **{'output': resolve_var(self.output), 'filters': resolve_var(self.filters), 'depends': resolve_depends(self.depends), 'debug': parse_debug_value(resolve_var(self.debug))}) def render(self, context): bundle = self.resolve(context) result = u"" with bundle.bind(get_env()): for url in bundle.urls(): context.update({'ASSET_URL': url, 'EXTRA': bundle.extra}) try: result += self.childnodes.render(context) finally: context.pop() return result def assets(parser, token): filters = None output = None debug = None depends = None files = [] # parse the arguments args = token.split_contents()[1:] for arg in args: # Handle separating comma; for backwards-compatibility # reasons, this is currently optional, but is enforced by # the Jinja extension already. if arg[-1] == ',': arg = arg[:-1] if not arg: continue # determine if keyword or positional argument arg = arg.split('=', 1) if len(arg) == 1: name = None value = arg[0] else: name, value = arg # handle known keyword arguments if name == 'output': output = value elif name == 'debug': debug = value elif name == 'filters': filters = value elif name == 'filter': filters = value warnings.warn('The "filter" option of the {% assets %} ' 'template tag has been renamed to ' '"filters" for consistency reasons.', ImminentDeprecationWarning) elif name == 'depends': depends = value # positional arguments are source files elif name is None: files.append(value) else: raise template.TemplateSyntaxError('Unsupported keyword argument "%s"'%name) # capture until closing tag childnodes = parser.parse(("endassets",)) parser.delete_first_token() return AssetsNode(filters, depends, output, debug, files, childnodes) # If Coffin is installed, expose the Jinja2 extension try: from coffin.template import Library as CoffinLibrary except ImportError: register = template.Library() else: register = CoffinLibrary() from webassets.ext.jinja2 import AssetsExtension from django_assets.env import get_env register.tag(AssetsExtension, environment={'assets_environment': get_env()}) # expose the default Django tag register.tag('assets', assets)
bsd-2-clause
MichaelNedzelsky/intellij-community
plugins/hg4idea/testData/bin/mercurial/changegroup.py
91
8282
# changegroup.py - Mercurial changegroup manipulation functions # # Copyright 2006 Matt Mackall <mpm@selenic.com> # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. from i18n import _ from node import nullrev import mdiff, util import struct, os, bz2, zlib, tempfile _BUNDLE10_DELTA_HEADER = "20s20s20s20s" def readexactly(stream, n): '''read n bytes from stream.read and abort if less was available''' s = stream.read(n) if len(s) < n: raise util.Abort(_("stream ended unexpectedly" " (got %d bytes, expected %d)") % (len(s), n)) return s def getchunk(stream): """return the next chunk from stream as a string""" d = readexactly(stream, 4) l = struct.unpack(">l", d)[0] if l <= 4: if l: raise util.Abort(_("invalid chunk length %d") % l) return "" return readexactly(stream, l - 4) def chunkheader(length): """return a changegroup chunk header (string)""" return struct.pack(">l", length + 4) def closechunk(): """return a changegroup chunk header (string) for a zero-length chunk""" return struct.pack(">l", 0) class nocompress(object): def compress(self, x): return x def flush(self): return "" bundletypes = { "": ("", nocompress), # only when using unbundle on ssh and old http servers # since the unification ssh accepts a header but there # is no capability signaling it. "HG10UN": ("HG10UN", nocompress), "HG10BZ": ("HG10", lambda: bz2.BZ2Compressor()), "HG10GZ": ("HG10GZ", lambda: zlib.compressobj()), } # hgweb uses this list to communicate its preferred type bundlepriority = ['HG10GZ', 'HG10BZ', 'HG10UN'] def writebundle(cg, filename, bundletype): """Write a bundle file and return its filename. Existing files will not be overwritten. If no filename is specified, a temporary file is created. bz2 compression can be turned off. The bundle file will be deleted in case of errors. """ fh = None cleanup = None try: if filename: fh = open(filename, "wb") else: fd, filename = tempfile.mkstemp(prefix="hg-bundle-", suffix=".hg") fh = os.fdopen(fd, "wb") cleanup = filename header, compressor = bundletypes[bundletype] fh.write(header) z = compressor() # parse the changegroup data, otherwise we will block # in case of sshrepo because we don't know the end of the stream # an empty chunkgroup is the end of the changegroup # a changegroup has at least 2 chunkgroups (changelog and manifest). # after that, an empty chunkgroup is the end of the changegroup empty = False count = 0 while not empty or count <= 2: empty = True count += 1 while True: chunk = getchunk(cg) if not chunk: break empty = False fh.write(z.compress(chunkheader(len(chunk)))) pos = 0 while pos < len(chunk): next = pos + 2**20 fh.write(z.compress(chunk[pos:next])) pos = next fh.write(z.compress(closechunk())) fh.write(z.flush()) cleanup = None return filename finally: if fh is not None: fh.close() if cleanup is not None: os.unlink(cleanup) def decompressor(fh, alg): if alg == 'UN': return fh elif alg == 'GZ': def generator(f): zd = zlib.decompressobj() for chunk in util.filechunkiter(f): yield zd.decompress(chunk) elif alg == 'BZ': def generator(f): zd = bz2.BZ2Decompressor() zd.decompress("BZ") for chunk in util.filechunkiter(f, 4096): yield zd.decompress(chunk) else: raise util.Abort("unknown bundle compression '%s'" % alg) return util.chunkbuffer(generator(fh)) class unbundle10(object): deltaheader = _BUNDLE10_DELTA_HEADER deltaheadersize = struct.calcsize(deltaheader) def __init__(self, fh, alg): self._stream = decompressor(fh, alg) self._type = alg self.callback = None def compressed(self): return self._type != 'UN' def read(self, l): return self._stream.read(l) def seek(self, pos): return self._stream.seek(pos) def tell(self): return self._stream.tell() def close(self): return self._stream.close() def chunklength(self): d = readexactly(self._stream, 4) l = struct.unpack(">l", d)[0] if l <= 4: if l: raise util.Abort(_("invalid chunk length %d") % l) return 0 if self.callback: self.callback() return l - 4 def changelogheader(self): """v10 does not have a changelog header chunk""" return {} def manifestheader(self): """v10 does not have a manifest header chunk""" return {} def filelogheader(self): """return the header of the filelogs chunk, v10 only has the filename""" l = self.chunklength() if not l: return {} fname = readexactly(self._stream, l) return dict(filename=fname) def _deltaheader(self, headertuple, prevnode): node, p1, p2, cs = headertuple if prevnode is None: deltabase = p1 else: deltabase = prevnode return node, p1, p2, deltabase, cs def deltachunk(self, prevnode): l = self.chunklength() if not l: return {} headerdata = readexactly(self._stream, self.deltaheadersize) header = struct.unpack(self.deltaheader, headerdata) delta = readexactly(self._stream, l - self.deltaheadersize) node, p1, p2, deltabase, cs = self._deltaheader(header, prevnode) return dict(node=node, p1=p1, p2=p2, cs=cs, deltabase=deltabase, delta=delta) class headerlessfixup(object): def __init__(self, fh, h): self._h = h self._fh = fh def read(self, n): if self._h: d, self._h = self._h[:n], self._h[n:] if len(d) < n: d += readexactly(self._fh, n - len(d)) return d return readexactly(self._fh, n) def readbundle(fh, fname): header = readexactly(fh, 6) if not fname: fname = "stream" if not header.startswith('HG') and header.startswith('\0'): fh = headerlessfixup(fh, header) header = "HG10UN" magic, version, alg = header[0:2], header[2:4], header[4:6] if magic != 'HG': raise util.Abort(_('%s: not a Mercurial bundle') % fname) if version != '10': raise util.Abort(_('%s: unknown bundle version %s') % (fname, version)) return unbundle10(fh, alg) class bundle10(object): deltaheader = _BUNDLE10_DELTA_HEADER def __init__(self, lookup): self._lookup = lookup def close(self): return closechunk() def fileheader(self, fname): return chunkheader(len(fname)) + fname def revchunk(self, revlog, rev, prev): node = revlog.node(rev) p1, p2 = revlog.parentrevs(rev) base = prev prefix = '' if base == nullrev: delta = revlog.revision(node) prefix = mdiff.trivialdiffheader(len(delta)) else: delta = revlog.revdiff(base, rev) linknode = self._lookup(revlog, node) p1n, p2n = revlog.parents(node) basenode = revlog.node(base) meta = self.builddeltaheader(node, p1n, p2n, basenode, linknode) meta += prefix l = len(meta) + len(delta) yield chunkheader(l) yield meta yield delta def builddeltaheader(self, node, p1n, p2n, basenode, linknode): # do nothing with basenode, it is implicitly the previous one in HG10 return struct.pack(self.deltaheader, node, p1n, p2n, linknode)
apache-2.0
crw/speedtest-easy
convert/mysqlite.py
1
2785
# # speedtest-easy (c) 2016 Craig Robert Wright <crw@crw.xyz> # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import sqlite3 class IntegrityError(sqlite3.IntegrityError): """Wrapper allows the calling script to not need to import sqlite3.""" pass class mysqlite(object): """Simple sqlite interface.""" filename = None schema = None conn = None def __init__(self, filename, schema): """Open and initializes a sqlite database. filename: str; location on disk of the sqlite db. schema: tuple of dict; schema definition for the sqlite db. ex. ( { tablename: [col_name, col_type, modifiers], [...] }, {...} ) """ if filename: self.filename = filename if schema: self.schema = schema self.open() self.initialize() def open(self): """Open a connection to a sqlite database (creates a connection object) """ if self.conn: self.close() self.conn = sqlite3.connect(self.filename) def commit(self): """Commits outstanding transaction.""" if self.conn: self.conn.commit() def close(self): """Closes the connection to the sqlite database.""" if self.conn: self.conn.close() def initialize(self): """Creates tables from schema, if not already created. No attempt is made to ALTER TABLE should the schema change. If the table name is found, it is simply not created. """ c = self.conn.cursor() for table_name in self.schema: columns = [] for column_tuple in self.schema[table_name]: columns.append(' '.join(column_tuple)) query = 'CREATE TABLE IF NOT EXISTS ' + table_name + \ '(' + ', '.join(columns) + ')' c.execute(query) self.commit() def insert(self, table, data): """Inserts one row of data into the sqlite database. table: string; name of the table into which to insert. data: dict; keys are column names, values are row values. """ c = self.conn.cursor() cols_arr = [] vals_arr = [] for key in data: cols_arr.append(key) vals_arr.append(':'+key) s_cols = ','.join(cols_arr) s_vals = ','.join(vals_arr) query = 'INSERT INTO ' + table + \ ' (' + s_cols + ') VALUES (' + s_vals + ')' try: c.execute(query, data) except sqlite3.IntegrityError: raise IntegrityError()
mpl-2.0
hudokkow/kodi-cmake
lib/gtest/scripts/upload.py
2511
51024
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tool for uploading diffs from a version control system to the codereview app. Usage summary: upload.py [options] [-- diff_options] Diff options are passed to the diff command of the underlying system. Supported version control systems: Git Mercurial Subversion It is important for Git/Mercurial users to specify a tree/node/branch to diff against by using the '--rev' option. """ # This code is derived from appcfg.py in the App Engine SDK (open source), # and from ASPN recipe #146306. import cookielib import getpass import logging import md5 import mimetypes import optparse import os import re import socket import subprocess import sys import urllib import urllib2 import urlparse try: import readline except ImportError: pass # The logging verbosity: # 0: Errors only. # 1: Status messages. # 2: Info logs. # 3: Debug logs. verbosity = 1 # Max size of patch or base file. MAX_UPLOAD_SIZE = 900 * 1024 def GetEmail(prompt): """Prompts the user for their email address and returns it. The last used email address is saved to a file and offered up as a suggestion to the user. If the user presses enter without typing in anything the last used email address is used. If the user enters a new address, it is saved for next time we prompt. """ last_email_file_name = os.path.expanduser("~/.last_codereview_email_address") last_email = "" if os.path.exists(last_email_file_name): try: last_email_file = open(last_email_file_name, "r") last_email = last_email_file.readline().strip("\n") last_email_file.close() prompt += " [%s]" % last_email except IOError, e: pass email = raw_input(prompt + ": ").strip() if email: try: last_email_file = open(last_email_file_name, "w") last_email_file.write(email) last_email_file.close() except IOError, e: pass else: email = last_email return email def StatusUpdate(msg): """Print a status message to stdout. If 'verbosity' is greater than 0, print the message. Args: msg: The string to print. """ if verbosity > 0: print msg def ErrorExit(msg): """Print an error message to stderr and exit.""" print >>sys.stderr, msg sys.exit(1) class ClientLoginError(urllib2.HTTPError): """Raised to indicate there was an error authenticating with ClientLogin.""" def __init__(self, url, code, msg, headers, args): urllib2.HTTPError.__init__(self, url, code, msg, headers, None) self.args = args self.reason = args["Error"] class AbstractRpcServer(object): """Provides a common interface for a simple RPC server.""" def __init__(self, host, auth_function, host_override=None, extra_headers={}, save_cookies=False): """Creates a new HttpRpcServer. Args: host: The host to send requests to. auth_function: A function that takes no arguments and returns an (email, password) tuple when called. Will be called if authentication is required. host_override: The host header to send to the server (defaults to host). extra_headers: A dict of extra headers to append to every request. save_cookies: If True, save the authentication cookies to local disk. If False, use an in-memory cookiejar instead. Subclasses must implement this functionality. Defaults to False. """ self.host = host self.host_override = host_override self.auth_function = auth_function self.authenticated = False self.extra_headers = extra_headers self.save_cookies = save_cookies self.opener = self._GetOpener() if self.host_override: logging.info("Server: %s; Host: %s", self.host, self.host_override) else: logging.info("Server: %s", self.host) def _GetOpener(self): """Returns an OpenerDirector for making HTTP requests. Returns: A urllib2.OpenerDirector object. """ raise NotImplementedError() def _CreateRequest(self, url, data=None): """Creates a new urllib request.""" logging.debug("Creating request for: '%s' with payload:\n%s", url, data) req = urllib2.Request(url, data=data) if self.host_override: req.add_header("Host", self.host_override) for key, value in self.extra_headers.iteritems(): req.add_header(key, value) return req def _GetAuthToken(self, email, password): """Uses ClientLogin to authenticate the user, returning an auth token. Args: email: The user's email address password: The user's password Raises: ClientLoginError: If there was an error authenticating with ClientLogin. HTTPError: If there was some other form of HTTP error. Returns: The authentication token returned by ClientLogin. """ account_type = "GOOGLE" if self.host.endswith(".google.com"): # Needed for use inside Google. account_type = "HOSTED" req = self._CreateRequest( url="https://www.google.com/accounts/ClientLogin", data=urllib.urlencode({ "Email": email, "Passwd": password, "service": "ah", "source": "rietveld-codereview-upload", "accountType": account_type, }), ) try: response = self.opener.open(req) response_body = response.read() response_dict = dict(x.split("=") for x in response_body.split("\n") if x) return response_dict["Auth"] except urllib2.HTTPError, e: if e.code == 403: body = e.read() response_dict = dict(x.split("=", 1) for x in body.split("\n") if x) raise ClientLoginError(req.get_full_url(), e.code, e.msg, e.headers, response_dict) else: raise def _GetAuthCookie(self, auth_token): """Fetches authentication cookies for an authentication token. Args: auth_token: The authentication token returned by ClientLogin. Raises: HTTPError: If there was an error fetching the authentication cookies. """ # This is a dummy value to allow us to identify when we're successful. continue_location = "http://localhost/" args = {"continue": continue_location, "auth": auth_token} req = self._CreateRequest("http://%s/_ah/login?%s" % (self.host, urllib.urlencode(args))) try: response = self.opener.open(req) except urllib2.HTTPError, e: response = e if (response.code != 302 or response.info()["location"] != continue_location): raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg, response.headers, response.fp) self.authenticated = True def _Authenticate(self): """Authenticates the user. The authentication process works as follows: 1) We get a username and password from the user 2) We use ClientLogin to obtain an AUTH token for the user (see http://code.google.com/apis/accounts/AuthForInstalledApps.html). 3) We pass the auth token to /_ah/login on the server to obtain an authentication cookie. If login was successful, it tries to redirect us to the URL we provided. If we attempt to access the upload API without first obtaining an authentication cookie, it returns a 401 response and directs us to authenticate ourselves with ClientLogin. """ for i in range(3): credentials = self.auth_function() try: auth_token = self._GetAuthToken(credentials[0], credentials[1]) except ClientLoginError, e: if e.reason == "BadAuthentication": print >>sys.stderr, "Invalid username or password." continue if e.reason == "CaptchaRequired": print >>sys.stderr, ( "Please go to\n" "https://www.google.com/accounts/DisplayUnlockCaptcha\n" "and verify you are a human. Then try again.") break if e.reason == "NotVerified": print >>sys.stderr, "Account not verified." break if e.reason == "TermsNotAgreed": print >>sys.stderr, "User has not agreed to TOS." break if e.reason == "AccountDeleted": print >>sys.stderr, "The user account has been deleted." break if e.reason == "AccountDisabled": print >>sys.stderr, "The user account has been disabled." break if e.reason == "ServiceDisabled": print >>sys.stderr, ("The user's access to the service has been " "disabled.") break if e.reason == "ServiceUnavailable": print >>sys.stderr, "The service is not available; try again later." break raise self._GetAuthCookie(auth_token) return def Send(self, request_path, payload=None, content_type="application/octet-stream", timeout=None, **kwargs): """Sends an RPC and returns the response. Args: request_path: The path to send the request to, eg /api/appversion/create. payload: The body of the request, or None to send an empty request. content_type: The Content-Type header to use. timeout: timeout in seconds; default None i.e. no timeout. (Note: for large requests on OS X, the timeout doesn't work right.) kwargs: Any keyword arguments are converted into query string parameters. Returns: The response body, as a string. """ # TODO: Don't require authentication. Let the server say # whether it is necessary. if not self.authenticated: self._Authenticate() old_timeout = socket.getdefaulttimeout() socket.setdefaulttimeout(timeout) try: tries = 0 while True: tries += 1 args = dict(kwargs) url = "http://%s%s" % (self.host, request_path) if args: url += "?" + urllib.urlencode(args) req = self._CreateRequest(url=url, data=payload) req.add_header("Content-Type", content_type) try: f = self.opener.open(req) response = f.read() f.close() return response except urllib2.HTTPError, e: if tries > 3: raise elif e.code == 401: self._Authenticate() ## elif e.code >= 500 and e.code < 600: ## # Server Error - try again. ## continue else: raise finally: socket.setdefaulttimeout(old_timeout) class HttpRpcServer(AbstractRpcServer): """Provides a simplified RPC-style interface for HTTP requests.""" def _Authenticate(self): """Save the cookie jar after authentication.""" super(HttpRpcServer, self)._Authenticate() if self.save_cookies: StatusUpdate("Saving authentication cookies to %s" % self.cookie_file) self.cookie_jar.save() def _GetOpener(self): """Returns an OpenerDirector that supports cookies and ignores redirects. Returns: A urllib2.OpenerDirector object. """ opener = urllib2.OpenerDirector() opener.add_handler(urllib2.ProxyHandler()) opener.add_handler(urllib2.UnknownHandler()) opener.add_handler(urllib2.HTTPHandler()) opener.add_handler(urllib2.HTTPDefaultErrorHandler()) opener.add_handler(urllib2.HTTPSHandler()) opener.add_handler(urllib2.HTTPErrorProcessor()) if self.save_cookies: self.cookie_file = os.path.expanduser("~/.codereview_upload_cookies") self.cookie_jar = cookielib.MozillaCookieJar(self.cookie_file) if os.path.exists(self.cookie_file): try: self.cookie_jar.load() self.authenticated = True StatusUpdate("Loaded authentication cookies from %s" % self.cookie_file) except (cookielib.LoadError, IOError): # Failed to load cookies - just ignore them. pass else: # Create an empty cookie file with mode 600 fd = os.open(self.cookie_file, os.O_CREAT, 0600) os.close(fd) # Always chmod the cookie file os.chmod(self.cookie_file, 0600) else: # Don't save cookies across runs of update.py. self.cookie_jar = cookielib.CookieJar() opener.add_handler(urllib2.HTTPCookieProcessor(self.cookie_jar)) return opener parser = optparse.OptionParser(usage="%prog [options] [-- diff_options]") parser.add_option("-y", "--assume_yes", action="store_true", dest="assume_yes", default=False, help="Assume that the answer to yes/no questions is 'yes'.") # Logging group = parser.add_option_group("Logging options") group.add_option("-q", "--quiet", action="store_const", const=0, dest="verbose", help="Print errors only.") group.add_option("-v", "--verbose", action="store_const", const=2, dest="verbose", default=1, help="Print info level logs (default).") group.add_option("--noisy", action="store_const", const=3, dest="verbose", help="Print all logs.") # Review server group = parser.add_option_group("Review server options") group.add_option("-s", "--server", action="store", dest="server", default="codereview.appspot.com", metavar="SERVER", help=("The server to upload to. The format is host[:port]. " "Defaults to 'codereview.appspot.com'.")) group.add_option("-e", "--email", action="store", dest="email", metavar="EMAIL", default=None, help="The username to use. Will prompt if omitted.") group.add_option("-H", "--host", action="store", dest="host", metavar="HOST", default=None, help="Overrides the Host header sent with all RPCs.") group.add_option("--no_cookies", action="store_false", dest="save_cookies", default=True, help="Do not save authentication cookies to local disk.") # Issue group = parser.add_option_group("Issue options") group.add_option("-d", "--description", action="store", dest="description", metavar="DESCRIPTION", default=None, help="Optional description when creating an issue.") group.add_option("-f", "--description_file", action="store", dest="description_file", metavar="DESCRIPTION_FILE", default=None, help="Optional path of a file that contains " "the description when creating an issue.") group.add_option("-r", "--reviewers", action="store", dest="reviewers", metavar="REVIEWERS", default=None, help="Add reviewers (comma separated email addresses).") group.add_option("--cc", action="store", dest="cc", metavar="CC", default=None, help="Add CC (comma separated email addresses).") # Upload options group = parser.add_option_group("Patch options") group.add_option("-m", "--message", action="store", dest="message", metavar="MESSAGE", default=None, help="A message to identify the patch. " "Will prompt if omitted.") group.add_option("-i", "--issue", type="int", action="store", metavar="ISSUE", default=None, help="Issue number to which to add. Defaults to new issue.") group.add_option("--download_base", action="store_true", dest="download_base", default=False, help="Base files will be downloaded by the server " "(side-by-side diffs may not work on files with CRs).") group.add_option("--rev", action="store", dest="revision", metavar="REV", default=None, help="Branch/tree/revision to diff against (used by DVCS).") group.add_option("--send_mail", action="store_true", dest="send_mail", default=False, help="Send notification email to reviewers.") def GetRpcServer(options): """Returns an instance of an AbstractRpcServer. Returns: A new AbstractRpcServer, on which RPC calls can be made. """ rpc_server_class = HttpRpcServer def GetUserCredentials(): """Prompts the user for a username and password.""" email = options.email if email is None: email = GetEmail("Email (login for uploading to %s)" % options.server) password = getpass.getpass("Password for %s: " % email) return (email, password) # If this is the dev_appserver, use fake authentication. host = (options.host or options.server).lower() if host == "localhost" or host.startswith("localhost:"): email = options.email if email is None: email = "test@example.com" logging.info("Using debug user %s. Override with --email" % email) server = rpc_server_class( options.server, lambda: (email, "password"), host_override=options.host, extra_headers={"Cookie": 'dev_appserver_login="%s:False"' % email}, save_cookies=options.save_cookies) # Don't try to talk to ClientLogin. server.authenticated = True return server return rpc_server_class(options.server, GetUserCredentials, host_override=options.host, save_cookies=options.save_cookies) def EncodeMultipartFormData(fields, files): """Encode form fields for multipart/form-data. Args: fields: A sequence of (name, value) elements for regular form fields. files: A sequence of (name, filename, value) elements for data to be uploaded as files. Returns: (content_type, body) ready for httplib.HTTP instance. Source: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 """ BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-' CRLF = '\r\n' lines = [] for (key, value) in fields: lines.append('--' + BOUNDARY) lines.append('Content-Disposition: form-data; name="%s"' % key) lines.append('') lines.append(value) for (key, filename, value) in files: lines.append('--' + BOUNDARY) lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) lines.append('Content-Type: %s' % GetContentType(filename)) lines.append('') lines.append(value) lines.append('--' + BOUNDARY + '--') lines.append('') body = CRLF.join(lines) content_type = 'multipart/form-data; boundary=%s' % BOUNDARY return content_type, body def GetContentType(filename): """Helper to guess the content-type from the filename.""" return mimetypes.guess_type(filename)[0] or 'application/octet-stream' # Use a shell for subcommands on Windows to get a PATH search. use_shell = sys.platform.startswith("win") def RunShellWithReturnCode(command, print_output=False, universal_newlines=True): """Executes a command and returns the output from stdout and the return code. Args: command: Command to execute. print_output: If True, the output is printed to stdout. If False, both stdout and stderr are ignored. universal_newlines: Use universal_newlines flag (default: True). Returns: Tuple (output, return code) """ logging.info("Running %s", command) p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=use_shell, universal_newlines=universal_newlines) if print_output: output_array = [] while True: line = p.stdout.readline() if not line: break print line.strip("\n") output_array.append(line) output = "".join(output_array) else: output = p.stdout.read() p.wait() errout = p.stderr.read() if print_output and errout: print >>sys.stderr, errout p.stdout.close() p.stderr.close() return output, p.returncode def RunShell(command, silent_ok=False, universal_newlines=True, print_output=False): data, retcode = RunShellWithReturnCode(command, print_output, universal_newlines) if retcode: ErrorExit("Got error status from %s:\n%s" % (command, data)) if not silent_ok and not data: ErrorExit("No output from %s" % command) return data class VersionControlSystem(object): """Abstract base class providing an interface to the VCS.""" def __init__(self, options): """Constructor. Args: options: Command line options. """ self.options = options def GenerateDiff(self, args): """Return the current diff as a string. Args: args: Extra arguments to pass to the diff command. """ raise NotImplementedError( "abstract method -- subclass %s must override" % self.__class__) def GetUnknownFiles(self): """Return a list of files unknown to the VCS.""" raise NotImplementedError( "abstract method -- subclass %s must override" % self.__class__) def CheckForUnknownFiles(self): """Show an "are you sure?" prompt if there are unknown files.""" unknown_files = self.GetUnknownFiles() if unknown_files: print "The following files are not added to version control:" for line in unknown_files: print line prompt = "Are you sure to continue?(y/N) " answer = raw_input(prompt).strip() if answer != "y": ErrorExit("User aborted") def GetBaseFile(self, filename): """Get the content of the upstream version of a file. Returns: A tuple (base_content, new_content, is_binary, status) base_content: The contents of the base file. new_content: For text files, this is empty. For binary files, this is the contents of the new file, since the diff output won't contain information to reconstruct the current file. is_binary: True iff the file is binary. status: The status of the file. """ raise NotImplementedError( "abstract method -- subclass %s must override" % self.__class__) def GetBaseFiles(self, diff): """Helper that calls GetBase file for each file in the patch. Returns: A dictionary that maps from filename to GetBaseFile's tuple. Filenames are retrieved based on lines that start with "Index:" or "Property changes on:". """ files = {} for line in diff.splitlines(True): if line.startswith('Index:') or line.startswith('Property changes on:'): unused, filename = line.split(':', 1) # On Windows if a file has property changes its filename uses '\' # instead of '/'. filename = filename.strip().replace('\\', '/') files[filename] = self.GetBaseFile(filename) return files def UploadBaseFiles(self, issue, rpc_server, patch_list, patchset, options, files): """Uploads the base files (and if necessary, the current ones as well).""" def UploadFile(filename, file_id, content, is_binary, status, is_base): """Uploads a file to the server.""" file_too_large = False if is_base: type = "base" else: type = "current" if len(content) > MAX_UPLOAD_SIZE: print ("Not uploading the %s file for %s because it's too large." % (type, filename)) file_too_large = True content = "" checksum = md5.new(content).hexdigest() if options.verbose > 0 and not file_too_large: print "Uploading %s file for %s" % (type, filename) url = "/%d/upload_content/%d/%d" % (int(issue), int(patchset), file_id) form_fields = [("filename", filename), ("status", status), ("checksum", checksum), ("is_binary", str(is_binary)), ("is_current", str(not is_base)), ] if file_too_large: form_fields.append(("file_too_large", "1")) if options.email: form_fields.append(("user", options.email)) ctype, body = EncodeMultipartFormData(form_fields, [("data", filename, content)]) response_body = rpc_server.Send(url, body, content_type=ctype) if not response_body.startswith("OK"): StatusUpdate(" --> %s" % response_body) sys.exit(1) patches = dict() [patches.setdefault(v, k) for k, v in patch_list] for filename in patches.keys(): base_content, new_content, is_binary, status = files[filename] file_id_str = patches.get(filename) if file_id_str.find("nobase") != -1: base_content = None file_id_str = file_id_str[file_id_str.rfind("_") + 1:] file_id = int(file_id_str) if base_content != None: UploadFile(filename, file_id, base_content, is_binary, status, True) if new_content != None: UploadFile(filename, file_id, new_content, is_binary, status, False) def IsImage(self, filename): """Returns true if the filename has an image extension.""" mimetype = mimetypes.guess_type(filename)[0] if not mimetype: return False return mimetype.startswith("image/") class SubversionVCS(VersionControlSystem): """Implementation of the VersionControlSystem interface for Subversion.""" def __init__(self, options): super(SubversionVCS, self).__init__(options) if self.options.revision: match = re.match(r"(\d+)(:(\d+))?", self.options.revision) if not match: ErrorExit("Invalid Subversion revision %s." % self.options.revision) self.rev_start = match.group(1) self.rev_end = match.group(3) else: self.rev_start = self.rev_end = None # Cache output from "svn list -r REVNO dirname". # Keys: dirname, Values: 2-tuple (ouput for start rev and end rev). self.svnls_cache = {} # SVN base URL is required to fetch files deleted in an older revision. # Result is cached to not guess it over and over again in GetBaseFile(). required = self.options.download_base or self.options.revision is not None self.svn_base = self._GuessBase(required) def GuessBase(self, required): """Wrapper for _GuessBase.""" return self.svn_base def _GuessBase(self, required): """Returns the SVN base URL. Args: required: If true, exits if the url can't be guessed, otherwise None is returned. """ info = RunShell(["svn", "info"]) for line in info.splitlines(): words = line.split() if len(words) == 2 and words[0] == "URL:": url = words[1] scheme, netloc, path, params, query, fragment = urlparse.urlparse(url) username, netloc = urllib.splituser(netloc) if username: logging.info("Removed username from base URL") if netloc.endswith("svn.python.org"): if netloc == "svn.python.org": if path.startswith("/projects/"): path = path[9:] elif netloc != "pythondev@svn.python.org": ErrorExit("Unrecognized Python URL: %s" % url) base = "http://svn.python.org/view/*checkout*%s/" % path logging.info("Guessed Python base = %s", base) elif netloc.endswith("svn.collab.net"): if path.startswith("/repos/"): path = path[6:] base = "http://svn.collab.net/viewvc/*checkout*%s/" % path logging.info("Guessed CollabNet base = %s", base) elif netloc.endswith(".googlecode.com"): path = path + "/" base = urlparse.urlunparse(("http", netloc, path, params, query, fragment)) logging.info("Guessed Google Code base = %s", base) else: path = path + "/" base = urlparse.urlunparse((scheme, netloc, path, params, query, fragment)) logging.info("Guessed base = %s", base) return base if required: ErrorExit("Can't find URL in output from svn info") return None def GenerateDiff(self, args): cmd = ["svn", "diff"] if self.options.revision: cmd += ["-r", self.options.revision] cmd.extend(args) data = RunShell(cmd) count = 0 for line in data.splitlines(): if line.startswith("Index:") or line.startswith("Property changes on:"): count += 1 logging.info(line) if not count: ErrorExit("No valid patches found in output from svn diff") return data def _CollapseKeywords(self, content, keyword_str): """Collapses SVN keywords.""" # svn cat translates keywords but svn diff doesn't. As a result of this # behavior patching.PatchChunks() fails with a chunk mismatch error. # This part was originally written by the Review Board development team # who had the same problem (http://reviews.review-board.org/r/276/). # Mapping of keywords to known aliases svn_keywords = { # Standard keywords 'Date': ['Date', 'LastChangedDate'], 'Revision': ['Revision', 'LastChangedRevision', 'Rev'], 'Author': ['Author', 'LastChangedBy'], 'HeadURL': ['HeadURL', 'URL'], 'Id': ['Id'], # Aliases 'LastChangedDate': ['LastChangedDate', 'Date'], 'LastChangedRevision': ['LastChangedRevision', 'Rev', 'Revision'], 'LastChangedBy': ['LastChangedBy', 'Author'], 'URL': ['URL', 'HeadURL'], } def repl(m): if m.group(2): return "$%s::%s$" % (m.group(1), " " * len(m.group(3))) return "$%s$" % m.group(1) keywords = [keyword for name in keyword_str.split(" ") for keyword in svn_keywords.get(name, [])] return re.sub(r"\$(%s):(:?)([^\$]+)\$" % '|'.join(keywords), repl, content) def GetUnknownFiles(self): status = RunShell(["svn", "status", "--ignore-externals"], silent_ok=True) unknown_files = [] for line in status.split("\n"): if line and line[0] == "?": unknown_files.append(line) return unknown_files def ReadFile(self, filename): """Returns the contents of a file.""" file = open(filename, 'rb') result = "" try: result = file.read() finally: file.close() return result def GetStatus(self, filename): """Returns the status of a file.""" if not self.options.revision: status = RunShell(["svn", "status", "--ignore-externals", filename]) if not status: ErrorExit("svn status returned no output for %s" % filename) status_lines = status.splitlines() # If file is in a cl, the output will begin with # "\n--- Changelist 'cl_name':\n". See # http://svn.collab.net/repos/svn/trunk/notes/changelist-design.txt if (len(status_lines) == 3 and not status_lines[0] and status_lines[1].startswith("--- Changelist")): status = status_lines[2] else: status = status_lines[0] # If we have a revision to diff against we need to run "svn list" # for the old and the new revision and compare the results to get # the correct status for a file. else: dirname, relfilename = os.path.split(filename) if dirname not in self.svnls_cache: cmd = ["svn", "list", "-r", self.rev_start, dirname or "."] out, returncode = RunShellWithReturnCode(cmd) if returncode: ErrorExit("Failed to get status for %s." % filename) old_files = out.splitlines() args = ["svn", "list"] if self.rev_end: args += ["-r", self.rev_end] cmd = args + [dirname or "."] out, returncode = RunShellWithReturnCode(cmd) if returncode: ErrorExit("Failed to run command %s" % cmd) self.svnls_cache[dirname] = (old_files, out.splitlines()) old_files, new_files = self.svnls_cache[dirname] if relfilename in old_files and relfilename not in new_files: status = "D " elif relfilename in old_files and relfilename in new_files: status = "M " else: status = "A " return status def GetBaseFile(self, filename): status = self.GetStatus(filename) base_content = None new_content = None # If a file is copied its status will be "A +", which signifies # "addition-with-history". See "svn st" for more information. We need to # upload the original file or else diff parsing will fail if the file was # edited. if status[0] == "A" and status[3] != "+": # We'll need to upload the new content if we're adding a binary file # since diff's output won't contain it. mimetype = RunShell(["svn", "propget", "svn:mime-type", filename], silent_ok=True) base_content = "" is_binary = mimetype and not mimetype.startswith("text/") if is_binary and self.IsImage(filename): new_content = self.ReadFile(filename) elif (status[0] in ("M", "D", "R") or (status[0] == "A" and status[3] == "+") or # Copied file. (status[0] == " " and status[1] == "M")): # Property change. args = [] if self.options.revision: url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start) else: # Don't change filename, it's needed later. url = filename args += ["-r", "BASE"] cmd = ["svn"] + args + ["propget", "svn:mime-type", url] mimetype, returncode = RunShellWithReturnCode(cmd) if returncode: # File does not exist in the requested revision. # Reset mimetype, it contains an error message. mimetype = "" get_base = False is_binary = mimetype and not mimetype.startswith("text/") if status[0] == " ": # Empty base content just to force an upload. base_content = "" elif is_binary: if self.IsImage(filename): get_base = True if status[0] == "M": if not self.rev_end: new_content = self.ReadFile(filename) else: url = "%s/%s@%s" % (self.svn_base, filename, self.rev_end) new_content = RunShell(["svn", "cat", url], universal_newlines=True, silent_ok=True) else: base_content = "" else: get_base = True if get_base: if is_binary: universal_newlines = False else: universal_newlines = True if self.rev_start: # "svn cat -r REV delete_file.txt" doesn't work. cat requires # the full URL with "@REV" appended instead of using "-r" option. url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start) base_content = RunShell(["svn", "cat", url], universal_newlines=universal_newlines, silent_ok=True) else: base_content = RunShell(["svn", "cat", filename], universal_newlines=universal_newlines, silent_ok=True) if not is_binary: args = [] if self.rev_start: url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start) else: url = filename args += ["-r", "BASE"] cmd = ["svn"] + args + ["propget", "svn:keywords", url] keywords, returncode = RunShellWithReturnCode(cmd) if keywords and not returncode: base_content = self._CollapseKeywords(base_content, keywords) else: StatusUpdate("svn status returned unexpected output: %s" % status) sys.exit(1) return base_content, new_content, is_binary, status[0:5] class GitVCS(VersionControlSystem): """Implementation of the VersionControlSystem interface for Git.""" def __init__(self, options): super(GitVCS, self).__init__(options) # Map of filename -> hash of base file. self.base_hashes = {} def GenerateDiff(self, extra_args): # This is more complicated than svn's GenerateDiff because we must convert # the diff output to include an svn-style "Index:" line as well as record # the hashes of the base files, so we can upload them along with our diff. if self.options.revision: extra_args = [self.options.revision] + extra_args gitdiff = RunShell(["git", "diff", "--full-index"] + extra_args) svndiff = [] filecount = 0 filename = None for line in gitdiff.splitlines(): match = re.match(r"diff --git a/(.*) b/.*$", line) if match: filecount += 1 filename = match.group(1) svndiff.append("Index: %s\n" % filename) else: # The "index" line in a git diff looks like this (long hashes elided): # index 82c0d44..b2cee3f 100755 # We want to save the left hash, as that identifies the base file. match = re.match(r"index (\w+)\.\.", line) if match: self.base_hashes[filename] = match.group(1) svndiff.append(line + "\n") if not filecount: ErrorExit("No valid patches found in output from git diff") return "".join(svndiff) def GetUnknownFiles(self): status = RunShell(["git", "ls-files", "--exclude-standard", "--others"], silent_ok=True) return status.splitlines() def GetBaseFile(self, filename): hash = self.base_hashes[filename] base_content = None new_content = None is_binary = False if hash == "0" * 40: # All-zero hash indicates no base file. status = "A" base_content = "" else: status = "M" base_content, returncode = RunShellWithReturnCode(["git", "show", hash]) if returncode: ErrorExit("Got error status from 'git show %s'" % hash) return (base_content, new_content, is_binary, status) class MercurialVCS(VersionControlSystem): """Implementation of the VersionControlSystem interface for Mercurial.""" def __init__(self, options, repo_dir): super(MercurialVCS, self).__init__(options) # Absolute path to repository (we can be in a subdir) self.repo_dir = os.path.normpath(repo_dir) # Compute the subdir cwd = os.path.normpath(os.getcwd()) assert cwd.startswith(self.repo_dir) self.subdir = cwd[len(self.repo_dir):].lstrip(r"\/") if self.options.revision: self.base_rev = self.options.revision else: self.base_rev = RunShell(["hg", "parent", "-q"]).split(':')[1].strip() def _GetRelPath(self, filename): """Get relative path of a file according to the current directory, given its logical path in the repo.""" assert filename.startswith(self.subdir), filename return filename[len(self.subdir):].lstrip(r"\/") def GenerateDiff(self, extra_args): # If no file specified, restrict to the current subdir extra_args = extra_args or ["."] cmd = ["hg", "diff", "--git", "-r", self.base_rev] + extra_args data = RunShell(cmd, silent_ok=True) svndiff = [] filecount = 0 for line in data.splitlines(): m = re.match("diff --git a/(\S+) b/(\S+)", line) if m: # Modify line to make it look like as it comes from svn diff. # With this modification no changes on the server side are required # to make upload.py work with Mercurial repos. # NOTE: for proper handling of moved/copied files, we have to use # the second filename. filename = m.group(2) svndiff.append("Index: %s" % filename) svndiff.append("=" * 67) filecount += 1 logging.info(line) else: svndiff.append(line) if not filecount: ErrorExit("No valid patches found in output from hg diff") return "\n".join(svndiff) + "\n" def GetUnknownFiles(self): """Return a list of files unknown to the VCS.""" args = [] status = RunShell(["hg", "status", "--rev", self.base_rev, "-u", "."], silent_ok=True) unknown_files = [] for line in status.splitlines(): st, fn = line.split(" ", 1) if st == "?": unknown_files.append(fn) return unknown_files def GetBaseFile(self, filename): # "hg status" and "hg cat" both take a path relative to the current subdir # rather than to the repo root, but "hg diff" has given us the full path # to the repo root. base_content = "" new_content = None is_binary = False oldrelpath = relpath = self._GetRelPath(filename) # "hg status -C" returns two lines for moved/copied files, one otherwise out = RunShell(["hg", "status", "-C", "--rev", self.base_rev, relpath]) out = out.splitlines() # HACK: strip error message about missing file/directory if it isn't in # the working copy if out[0].startswith('%s: ' % relpath): out = out[1:] if len(out) > 1: # Moved/copied => considered as modified, use old filename to # retrieve base contents oldrelpath = out[1].strip() status = "M" else: status, _ = out[0].split(' ', 1) if status != "A": base_content = RunShell(["hg", "cat", "-r", self.base_rev, oldrelpath], silent_ok=True) is_binary = "\0" in base_content # Mercurial's heuristic if status != "R": new_content = open(relpath, "rb").read() is_binary = is_binary or "\0" in new_content if is_binary and base_content: # Fetch again without converting newlines base_content = RunShell(["hg", "cat", "-r", self.base_rev, oldrelpath], silent_ok=True, universal_newlines=False) if not is_binary or not self.IsImage(relpath): new_content = None return base_content, new_content, is_binary, status # NOTE: The SplitPatch function is duplicated in engine.py, keep them in sync. def SplitPatch(data): """Splits a patch into separate pieces for each file. Args: data: A string containing the output of svn diff. Returns: A list of 2-tuple (filename, text) where text is the svn diff output pertaining to filename. """ patches = [] filename = None diff = [] for line in data.splitlines(True): new_filename = None if line.startswith('Index:'): unused, new_filename = line.split(':', 1) new_filename = new_filename.strip() elif line.startswith('Property changes on:'): unused, temp_filename = line.split(':', 1) # When a file is modified, paths use '/' between directories, however # when a property is modified '\' is used on Windows. Make them the same # otherwise the file shows up twice. temp_filename = temp_filename.strip().replace('\\', '/') if temp_filename != filename: # File has property changes but no modifications, create a new diff. new_filename = temp_filename if new_filename: if filename and diff: patches.append((filename, ''.join(diff))) filename = new_filename diff = [line] continue if diff is not None: diff.append(line) if filename and diff: patches.append((filename, ''.join(diff))) return patches def UploadSeparatePatches(issue, rpc_server, patchset, data, options): """Uploads a separate patch for each file in the diff output. Returns a list of [patch_key, filename] for each file. """ patches = SplitPatch(data) rv = [] for patch in patches: if len(patch[1]) > MAX_UPLOAD_SIZE: print ("Not uploading the patch for " + patch[0] + " because the file is too large.") continue form_fields = [("filename", patch[0])] if not options.download_base: form_fields.append(("content_upload", "1")) files = [("data", "data.diff", patch[1])] ctype, body = EncodeMultipartFormData(form_fields, files) url = "/%d/upload_patch/%d" % (int(issue), int(patchset)) print "Uploading patch for " + patch[0] response_body = rpc_server.Send(url, body, content_type=ctype) lines = response_body.splitlines() if not lines or lines[0] != "OK": StatusUpdate(" --> %s" % response_body) sys.exit(1) rv.append([lines[1], patch[0]]) return rv def GuessVCS(options): """Helper to guess the version control system. This examines the current directory, guesses which VersionControlSystem we're using, and returns an instance of the appropriate class. Exit with an error if we can't figure it out. Returns: A VersionControlSystem instance. Exits if the VCS can't be guessed. """ # Mercurial has a command to get the base directory of a repository # Try running it, but don't die if we don't have hg installed. # NOTE: we try Mercurial first as it can sit on top of an SVN working copy. try: out, returncode = RunShellWithReturnCode(["hg", "root"]) if returncode == 0: return MercurialVCS(options, out.strip()) except OSError, (errno, message): if errno != 2: # ENOENT -- they don't have hg installed. raise # Subversion has a .svn in all working directories. if os.path.isdir('.svn'): logging.info("Guessed VCS = Subversion") return SubversionVCS(options) # Git has a command to test if you're in a git tree. # Try running it, but don't die if we don't have git installed. try: out, returncode = RunShellWithReturnCode(["git", "rev-parse", "--is-inside-work-tree"]) if returncode == 0: return GitVCS(options) except OSError, (errno, message): if errno != 2: # ENOENT -- they don't have git installed. raise ErrorExit(("Could not guess version control system. " "Are you in a working copy directory?")) def RealMain(argv, data=None): """The real main function. Args: argv: Command line arguments. data: Diff contents. If None (default) the diff is generated by the VersionControlSystem implementation returned by GuessVCS(). Returns: A 2-tuple (issue id, patchset id). The patchset id is None if the base files are not uploaded by this script (applies only to SVN checkouts). """ logging.basicConfig(format=("%(asctime).19s %(levelname)s %(filename)s:" "%(lineno)s %(message)s ")) os.environ['LC_ALL'] = 'C' options, args = parser.parse_args(argv[1:]) global verbosity verbosity = options.verbose if verbosity >= 3: logging.getLogger().setLevel(logging.DEBUG) elif verbosity >= 2: logging.getLogger().setLevel(logging.INFO) vcs = GuessVCS(options) if isinstance(vcs, SubversionVCS): # base field is only allowed for Subversion. # Note: Fetching base files may become deprecated in future releases. base = vcs.GuessBase(options.download_base) else: base = None if not base and options.download_base: options.download_base = True logging.info("Enabled upload of base file") if not options.assume_yes: vcs.CheckForUnknownFiles() if data is None: data = vcs.GenerateDiff(args) files = vcs.GetBaseFiles(data) if verbosity >= 1: print "Upload server:", options.server, "(change with -s/--server)" if options.issue: prompt = "Message describing this patch set: " else: prompt = "New issue subject: " message = options.message or raw_input(prompt).strip() if not message: ErrorExit("A non-empty message is required") rpc_server = GetRpcServer(options) form_fields = [("subject", message)] if base: form_fields.append(("base", base)) if options.issue: form_fields.append(("issue", str(options.issue))) if options.email: form_fields.append(("user", options.email)) if options.reviewers: for reviewer in options.reviewers.split(','): if "@" in reviewer and not reviewer.split("@")[1].count(".") == 1: ErrorExit("Invalid email address: %s" % reviewer) form_fields.append(("reviewers", options.reviewers)) if options.cc: for cc in options.cc.split(','): if "@" in cc and not cc.split("@")[1].count(".") == 1: ErrorExit("Invalid email address: %s" % cc) form_fields.append(("cc", options.cc)) description = options.description if options.description_file: if options.description: ErrorExit("Can't specify description and description_file") file = open(options.description_file, 'r') description = file.read() file.close() if description: form_fields.append(("description", description)) # Send a hash of all the base file so the server can determine if a copy # already exists in an earlier patchset. base_hashes = "" for file, info in files.iteritems(): if not info[0] is None: checksum = md5.new(info[0]).hexdigest() if base_hashes: base_hashes += "|" base_hashes += checksum + ":" + file form_fields.append(("base_hashes", base_hashes)) # If we're uploading base files, don't send the email before the uploads, so # that it contains the file status. if options.send_mail and options.download_base: form_fields.append(("send_mail", "1")) if not options.download_base: form_fields.append(("content_upload", "1")) if len(data) > MAX_UPLOAD_SIZE: print "Patch is large, so uploading file patches separately." uploaded_diff_file = [] form_fields.append(("separate_patches", "1")) else: uploaded_diff_file = [("data", "data.diff", data)] ctype, body = EncodeMultipartFormData(form_fields, uploaded_diff_file) response_body = rpc_server.Send("/upload", body, content_type=ctype) patchset = None if not options.download_base or not uploaded_diff_file: lines = response_body.splitlines() if len(lines) >= 2: msg = lines[0] patchset = lines[1].strip() patches = [x.split(" ", 1) for x in lines[2:]] else: msg = response_body else: msg = response_body StatusUpdate(msg) if not response_body.startswith("Issue created.") and \ not response_body.startswith("Issue updated."): sys.exit(0) issue = msg[msg.rfind("/")+1:] if not uploaded_diff_file: result = UploadSeparatePatches(issue, rpc_server, patchset, data, options) if not options.download_base: patches = result if not options.download_base: vcs.UploadBaseFiles(issue, rpc_server, patches, patchset, options, files) if options.send_mail: rpc_server.Send("/" + issue + "/mail", payload="") return issue, patchset def main(): try: RealMain(sys.argv) except KeyboardInterrupt: print StatusUpdate("Interrupted.") sys.exit(1) if __name__ == "__main__": main()
gpl-2.0
grimmjow8/ansible
lib/ansible/modules/cloud/cloudstack/cs_instancegroup.py
48
5867
#!/usr/bin/python # -*- coding: utf-8 -*- # # (c) 2015, René Moser <mail@renemoser.net> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'status': ['stableinterface'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' --- module: cs_instancegroup short_description: Manages instance groups on Apache CloudStack based clouds. description: - Create and remove instance groups. version_added: '2.0' author: "René Moser (@resmo)" options: name: description: - Name of the instance group. required: true domain: description: - Domain the instance group is related to. required: false default: null account: description: - Account the instance group is related to. required: false default: null project: description: - Project the instance group is related to. required: false default: null state: description: - State of the instance group. required: false default: 'present' choices: [ 'present', 'absent' ] extends_documentation_fragment: cloudstack ''' EXAMPLES = ''' # Create an instance group - local_action: module: cs_instancegroup name: loadbalancers # Remove an instance group - local_action: module: cs_instancegroup name: loadbalancers state: absent ''' RETURN = ''' --- id: description: UUID of the instance group. returned: success type: string sample: 04589590-ac63-4ffc-93f5-b698b8ac38b6 name: description: Name of the instance group. returned: success type: string sample: webservers created: description: Date when the instance group was created. returned: success type: string sample: 2015-05-03T15:05:51+0200 domain: description: Domain the instance group is related to. returned: success type: string sample: example domain account: description: Account the instance group is related to. returned: success type: string sample: example account project: description: Project the instance group is related to. returned: success type: string sample: example project ''' # import cloudstack common from ansible.module_utils.cloudstack import * class AnsibleCloudStackInstanceGroup(AnsibleCloudStack): def __init__(self, module): super(AnsibleCloudStackInstanceGroup, self).__init__(module) self.instance_group = None def get_instance_group(self): if self.instance_group: return self.instance_group name = self.module.params.get('name') args = {} args['account'] = self.get_account('name') args['domainid'] = self.get_domain('id') args['projectid'] = self.get_project('id') instance_groups = self.cs.listInstanceGroups(**args) if instance_groups: for g in instance_groups['instancegroup']: if name in [ g['name'], g['id'] ]: self.instance_group = g break return self.instance_group def present_instance_group(self): instance_group = self.get_instance_group() if not instance_group: self.result['changed'] = True args = {} args['name'] = self.module.params.get('name') args['account'] = self.get_account('name') args['domainid'] = self.get_domain('id') args['projectid'] = self.get_project('id') if not self.module.check_mode: res = self.cs.createInstanceGroup(**args) if 'errortext' in res: self.module.fail_json(msg="Failed: '%s'" % res['errortext']) instance_group = res['instancegroup'] return instance_group def absent_instance_group(self): instance_group = self.get_instance_group() if instance_group: self.result['changed'] = True if not self.module.check_mode: res = self.cs.deleteInstanceGroup(id=instance_group['id']) if 'errortext' in res: self.module.fail_json(msg="Failed: '%s'" % res['errortext']) return instance_group def main(): argument_spec = cs_argument_spec() argument_spec.update(dict( name = dict(required=True), state = dict(default='present', choices=['present', 'absent']), domain = dict(default=None), account = dict(default=None), project = dict(default=None), )) module = AnsibleModule( argument_spec=argument_spec, required_together=cs_required_together(), supports_check_mode=True ) try: acs_ig = AnsibleCloudStackInstanceGroup(module) state = module.params.get('state') if state in ['absent']: instance_group = acs_ig.absent_instance_group() else: instance_group = acs_ig.present_instance_group() result = acs_ig.get_result(instance_group) except CloudStackException as e: module.fail_json(msg='CloudStackException: %s' % str(e)) module.exit_json(**result) # import module snippets from ansible.module_utils.basic import * if __name__ == '__main__': main()
gpl-3.0
Varentsov/servo
tests/wpt/web-platform-tests/tools/third_party/py/py/_io/capture.py
268
11640
import os import sys import py import tempfile try: from io import StringIO except ImportError: from StringIO import StringIO if sys.version_info < (3,0): class TextIO(StringIO): def write(self, data): if not isinstance(data, unicode): data = unicode(data, getattr(self, '_encoding', 'UTF-8'), 'replace') StringIO.write(self, data) else: TextIO = StringIO try: from io import BytesIO except ImportError: class BytesIO(StringIO): def write(self, data): if isinstance(data, unicode): raise TypeError("not a byte value: %r" %(data,)) StringIO.write(self, data) patchsysdict = {0: 'stdin', 1: 'stdout', 2: 'stderr'} class FDCapture: """ Capture IO to/from a given os-level filedescriptor. """ def __init__(self, targetfd, tmpfile=None, now=True, patchsys=False): """ save targetfd descriptor, and open a new temporary file there. If no tmpfile is specified a tempfile.Tempfile() will be opened in text mode. """ self.targetfd = targetfd if tmpfile is None and targetfd != 0: f = tempfile.TemporaryFile('wb+') tmpfile = dupfile(f, encoding="UTF-8") f.close() self.tmpfile = tmpfile self._savefd = os.dup(self.targetfd) if patchsys: self._oldsys = getattr(sys, patchsysdict[targetfd]) if now: self.start() def start(self): try: os.fstat(self._savefd) except OSError: raise ValueError("saved filedescriptor not valid, " "did you call start() twice?") if self.targetfd == 0 and not self.tmpfile: fd = os.open(devnullpath, os.O_RDONLY) os.dup2(fd, 0) os.close(fd) if hasattr(self, '_oldsys'): setattr(sys, patchsysdict[self.targetfd], DontReadFromInput()) else: os.dup2(self.tmpfile.fileno(), self.targetfd) if hasattr(self, '_oldsys'): setattr(sys, patchsysdict[self.targetfd], self.tmpfile) def done(self): """ unpatch and clean up, returns the self.tmpfile (file object) """ os.dup2(self._savefd, self.targetfd) os.close(self._savefd) if self.targetfd != 0: self.tmpfile.seek(0) if hasattr(self, '_oldsys'): setattr(sys, patchsysdict[self.targetfd], self._oldsys) return self.tmpfile def writeorg(self, data): """ write a string to the original file descriptor """ tempfp = tempfile.TemporaryFile() try: os.dup2(self._savefd, tempfp.fileno()) tempfp.write(data) finally: tempfp.close() def dupfile(f, mode=None, buffering=0, raising=False, encoding=None): """ return a new open file object that's a duplicate of f mode is duplicated if not given, 'buffering' controls buffer size (defaulting to no buffering) and 'raising' defines whether an exception is raised when an incompatible file object is passed in (if raising is False, the file object itself will be returned) """ try: fd = f.fileno() mode = mode or f.mode except AttributeError: if raising: raise return f newfd = os.dup(fd) if sys.version_info >= (3,0): if encoding is not None: mode = mode.replace("b", "") buffering = True return os.fdopen(newfd, mode, buffering, encoding, closefd=True) else: f = os.fdopen(newfd, mode, buffering) if encoding is not None: return EncodedFile(f, encoding) return f class EncodedFile(object): def __init__(self, _stream, encoding): self._stream = _stream self.encoding = encoding def write(self, obj): if isinstance(obj, unicode): obj = obj.encode(self.encoding) elif isinstance(obj, str): pass else: obj = str(obj) self._stream.write(obj) def writelines(self, linelist): data = ''.join(linelist) self.write(data) def __getattr__(self, name): return getattr(self._stream, name) class Capture(object): def call(cls, func, *args, **kwargs): """ return a (res, out, err) tuple where out and err represent the output/error output during function execution. call the given function with args/kwargs and capture output/error during its execution. """ so = cls() try: res = func(*args, **kwargs) finally: out, err = so.reset() return res, out, err call = classmethod(call) def reset(self): """ reset sys.stdout/stderr and return captured output as strings. """ if hasattr(self, '_reset'): raise ValueError("was already reset") self._reset = True outfile, errfile = self.done(save=False) out, err = "", "" if outfile and not outfile.closed: out = outfile.read() outfile.close() if errfile and errfile != outfile and not errfile.closed: err = errfile.read() errfile.close() return out, err def suspend(self): """ return current snapshot captures, memorize tempfiles. """ outerr = self.readouterr() outfile, errfile = self.done() return outerr class StdCaptureFD(Capture): """ This class allows to capture writes to FD1 and FD2 and may connect a NULL file to FD0 (and prevent reads from sys.stdin). If any of the 0,1,2 file descriptors is invalid it will not be captured. """ def __init__(self, out=True, err=True, mixed=False, in_=True, patchsys=True, now=True): self._options = { "out": out, "err": err, "mixed": mixed, "in_": in_, "patchsys": patchsys, "now": now, } self._save() if now: self.startall() def _save(self): in_ = self._options['in_'] out = self._options['out'] err = self._options['err'] mixed = self._options['mixed'] patchsys = self._options['patchsys'] if in_: try: self.in_ = FDCapture(0, tmpfile=None, now=False, patchsys=patchsys) except OSError: pass if out: tmpfile = None if hasattr(out, 'write'): tmpfile = out try: self.out = FDCapture(1, tmpfile=tmpfile, now=False, patchsys=patchsys) self._options['out'] = self.out.tmpfile except OSError: pass if err: if out and mixed: tmpfile = self.out.tmpfile elif hasattr(err, 'write'): tmpfile = err else: tmpfile = None try: self.err = FDCapture(2, tmpfile=tmpfile, now=False, patchsys=patchsys) self._options['err'] = self.err.tmpfile except OSError: pass def startall(self): if hasattr(self, 'in_'): self.in_.start() if hasattr(self, 'out'): self.out.start() if hasattr(self, 'err'): self.err.start() def resume(self): """ resume capturing with original temp files. """ self.startall() def done(self, save=True): """ return (outfile, errfile) and stop capturing. """ outfile = errfile = None if hasattr(self, 'out') and not self.out.tmpfile.closed: outfile = self.out.done() if hasattr(self, 'err') and not self.err.tmpfile.closed: errfile = self.err.done() if hasattr(self, 'in_'): tmpfile = self.in_.done() if save: self._save() return outfile, errfile def readouterr(self): """ return snapshot value of stdout/stderr capturings. """ if hasattr(self, "out"): out = self._readsnapshot(self.out.tmpfile) else: out = "" if hasattr(self, "err"): err = self._readsnapshot(self.err.tmpfile) else: err = "" return [out, err] def _readsnapshot(self, f): f.seek(0) res = f.read() enc = getattr(f, "encoding", None) if enc: res = py.builtin._totext(res, enc, "replace") f.truncate(0) f.seek(0) return res class StdCapture(Capture): """ This class allows to capture writes to sys.stdout|stderr "in-memory" and will raise errors on tries to read from sys.stdin. It only modifies sys.stdout|stderr|stdin attributes and does not touch underlying File Descriptors (use StdCaptureFD for that). """ def __init__(self, out=True, err=True, in_=True, mixed=False, now=True): self._oldout = sys.stdout self._olderr = sys.stderr self._oldin = sys.stdin if out and not hasattr(out, 'file'): out = TextIO() self.out = out if err: if mixed: err = out elif not hasattr(err, 'write'): err = TextIO() self.err = err self.in_ = in_ if now: self.startall() def startall(self): if self.out: sys.stdout = self.out if self.err: sys.stderr = self.err if self.in_: sys.stdin = self.in_ = DontReadFromInput() def done(self, save=True): """ return (outfile, errfile) and stop capturing. """ outfile = errfile = None if self.out and not self.out.closed: sys.stdout = self._oldout outfile = self.out outfile.seek(0) if self.err and not self.err.closed: sys.stderr = self._olderr errfile = self.err errfile.seek(0) if self.in_: sys.stdin = self._oldin return outfile, errfile def resume(self): """ resume capturing with original temp files. """ self.startall() def readouterr(self): """ return snapshot value of stdout/stderr capturings. """ out = err = "" if self.out: out = self.out.getvalue() self.out.truncate(0) self.out.seek(0) if self.err: err = self.err.getvalue() self.err.truncate(0) self.err.seek(0) return out, err class DontReadFromInput: """Temporary stub class. Ideally when stdin is accessed, the capturing should be turned off, with possibly all data captured so far sent to the screen. This should be configurable, though, because in automated test runs it is better to crash than hang indefinitely. """ def read(self, *args): raise IOError("reading from stdin while output is captured") readline = read readlines = read __iter__ = read def fileno(self): raise ValueError("redirected Stdin is pseudofile, has no fileno()") def isatty(self): return False def close(self): pass try: devnullpath = os.devnull except AttributeError: if os.name == 'nt': devnullpath = 'NUL' else: devnullpath = '/dev/null'
mpl-2.0
sephalon/python-ivi
ivi/agilent/agilentDSO7032A.py
7
1688
""" Python Interchangeable Virtual Instrument Library Copyright (c) 2012-2014 Alex Forencich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from .agilent7000A import * class agilentDSO7032A(agilent7000A): "Agilent InfiniiVision DSO7032A IVI oscilloscope driver" def __init__(self, *args, **kwargs): self.__dict__.setdefault('_instrument_id', 'DSO7032A') super(agilentDSO7032A, self).__init__(*args, **kwargs) self._analog_channel_count = 2 self._digital_channel_count = 0 self._channel_count = self._analog_channel_count + self._digital_channel_count self._bandwidth = 350e6 self._init_channels()
mit
ahlusar1989/geocoder
test_geocoder.py
1
3292
#!/usr/bin/python # coding: utf8 import geocoder address = '453 Booth Street, Ottawa' location = 'Ottawa, Ontario' words = 'embedded.fizzled.trial' city = 'Ottawa' ip = '74.125.226.99' china = '中国' repeat = 3 ottawa = (45.4215296, -75.6971930) toronto = (43.653226, -79.3831843) def test_entry_points(): geocoder.ip geocoder.osm geocoder.w3w geocoder.bing geocoder.here geocoder.baidu geocoder.yahoo geocoder.google geocoder.yandex geocoder.tomtom geocoder.arcgis geocoder.geonames geocoder.mapquest geocoder.timezone geocoder.maxmind geocoder.elevation geocoder.freegeoip geocoder.geolytica geocoder.timezone geocoder.opencage geocoder.elevation geocoder.canadapost """ Server Down def test_freegeoip(): g = geocoder.freegeoip(ip) assert g.ok """ def test_yandex(): g = geocoder.yandex(location) assert g.ok def test_w3w(): g = geocoder.w3w(words) assert g.ok def test_w3w_reverse(): g = geocoder.w3w(ottawa, method='reverse') assert g.ok def test_maxmind(): g = geocoder.maxmind(ip) assert g.ok def test_baidu(): g = geocoder.baidu(china) assert g.ok def test_google(): g = geocoder.google(location) assert g.ok assert g.city == city def test_google_reverse(): g = geocoder.google(ottawa, method='reverse') assert g.ok def test_google_timezone(): g = geocoder.google(ottawa, method='timezone') assert g.ok def test_google_elevation(): g = geocoder.google(ottawa, method='elevation') assert g.ok def test_location(): g = geocoder.location('45.4215296, -75.6971931') assert g.ok g = geocoder.location({'lat': 45.4215296, 'lng': -75.6971931}) assert g.ok g = geocoder.location([45.4215296, -75.6971931]) assert g.ok """ Bing causing issues First request is rarely successful def test_bing(): g = geocoder.bing(location) g = geocoder.bing(location) assert g.ok assert g.city == city def test_bing_reverse(): # First request rarely successful g = geocoder.bing(ottawa, method='reverse') g = geocoder.bing(ottawa, method='reverse') assert g.ok """ """ Quote Exceeded def test_opencage(): g = geocoder.opencage(location) assert g.ok def test_opencage_reverse(): g = geocoder.opencage(ottawa, method='reverse') assert g.ok """ def test_yahoo(): g = geocoder.yahoo(location) assert g.ok assert g.city == city def test_arcgis(): g = geocoder.arcgis(location) assert g.ok def test_geolytica(): g = geocoder.geolytica(address) assert g.ok def test_canadapost(): g = geocoder.canadapost(address) assert g.ok """ License Expired def test_here(): g = geocoder.here(location) assert g.ok assert g.city == city def test_here_reverse(): g = geocoder.here(ottawa, method='reverse') assert g.ok """ def test_osm(): g = geocoder.osm(location) assert g.ok assert g.city == city def test_tomtom(): g = geocoder.tomtom(location) assert g.ok assert g.city == city def test_mapquest(): g = geocoder.mapquest(location) assert g.ok assert g.city == city def test_geonames(): g = geocoder.geonames(city) assert g.ok
mit
mtougeron/python-openstacksdk
openstack/utils.py
3
2677
# 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 logging def enable_logging(debug=False, path=None, stream=None): """Enable logging to a file at path and/or a console stream. This function is available for debugging purposes. If you wish to log this package's message in your application, the standard library ``logging`` package will receive these messages in any handlers you create. :param bool debug: Set this to ``True`` to receive debug messages, which includes HTTP requests and responses, or ``False`` for warning messages. :param str path: If a *path* is specified, logging output will written to that file in addition to sys.stderr. The path is passed to logging.FileHandler, which will append messages the file (and create it if needed). :param stream: One of ``None `` or ``sys.stdout`` or ``sys.stderr``. If it is ``None``, nothing is logged to a stream. If it isn't ``None``, console output is logged to this stream. :rtype: None """ if path is None and stream is None: raise ValueError("path and/or stream must be set") logger = logging.getLogger('openstack') formatter = logging.Formatter( '%(asctime)s %(levelname)s: %(name)s %(message)s') if stream is not None: console = logging.StreamHandler(stream) console.setFormatter(formatter) logger.addHandler(console) if path is not None: file_handler = logging.FileHandler(path) file_handler.setFormatter(formatter) logger.addHandler(file_handler) logger.setLevel(logging.DEBUG if debug else logging.WARNING) def urljoin(*args): """A custom version of urljoin that simply joins strings into a path. The real urljoin takes into account web semantics like when joining a url like /path this should be joined to http://host/path as it is an anchored link. We generally won't care about that in client. """ return '/'.join(str(a or '').strip('/') for a in args)
apache-2.0
ganeshnalawade/ansible
lib/ansible/plugins/doc_fragments/template_common.py
56
4573
# -*- coding: utf-8 -*- # Copyright (c) 2019 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type class ModuleDocFragment(object): # Standard template documentation fragment, use by template and win_template. DOCUMENTATION = r''' description: - Templates are processed by the L(Jinja2 templating language,http://jinja.pocoo.org/docs/). - Documentation on the template formatting can be found in the L(Template Designer Documentation,http://jinja.pocoo.org/docs/templates/). - Additional variables listed below can be used in templates. - C(ansible_managed) (configurable via the C(defaults) section of C(ansible.cfg)) contains a string which can be used to describe the template name, host, modification time of the template file and the owner uid. - C(template_host) contains the node name of the template's machine. - C(template_uid) is the numeric user id of the owner. - C(template_path) is the path of the template. - C(template_fullpath) is the absolute path of the template. - C(template_destpath) is the path of the template on the remote system (added in 2.8). - C(template_run_date) is the date that the template was rendered. options: src: description: - Path of a Jinja2 formatted template on the Ansible controller. - This can be a relative or an absolute path. - The file must be encoded with C(utf-8) but I(output_encoding) can be used to control the encoding of the output template. type: path required: yes dest: description: - Location to render the template to on the remote machine. type: path required: yes newline_sequence: description: - Specify the newline sequence to use for templating files. type: str choices: [ '\n', '\r', '\r\n' ] default: '\n' version_added: '2.4' block_start_string: description: - The string marking the beginning of a block. type: str default: '{%' version_added: '2.4' block_end_string: description: - The string marking the end of a block. type: str default: '%}' version_added: '2.4' variable_start_string: description: - The string marking the beginning of a print statement. type: str default: '{{' version_added: '2.4' variable_end_string: description: - The string marking the end of a print statement. type: str default: '}}' version_added: '2.4' trim_blocks: description: - Determine when newlines should be removed from blocks. - When set to C(yes) the first newline after a block is removed (block, not variable tag!). type: bool default: yes version_added: '2.4' lstrip_blocks: description: - Determine when leading spaces and tabs should be stripped. - When set to C(yes) leading spaces and tabs are stripped from the start of a line to a block. - This functionality requires Jinja 2.7 or newer. type: bool default: no version_added: '2.6' force: description: - Determine when the file is being transferred if the destination already exists. - When set to C(yes), replace the remote file when contents are different than the source. - When set to C(no), the file will only be transferred if the destination does not exist. type: bool default: yes output_encoding: description: - Overrides the encoding used to write the template file defined by C(dest). - It defaults to C(utf-8), but any encoding supported by python can be used. - The source template file must always be encoded using C(utf-8), for homogeneity. type: str default: utf-8 version_added: '2.7' notes: - Including a string that uses a date in the template will result in the template being marked 'changed' each time. - Since Ansible 0.9, templates are loaded with C(trim_blocks=True). - > Also, you can override jinja2 settings by adding a special header to template file. i.e. C(#jinja2:variable_start_string:'[%', variable_end_string:'%]', trim_blocks: False) which changes the variable interpolation markers to C([% var %]) instead of C({{ var }}). This is the best way to prevent evaluation of things that look like, but should not be Jinja2. - Using raw/endraw in Jinja2 will not work as you expect because templates in Ansible are recursively evaluated. - To find Byte Order Marks in files, use C(Format-Hex <file> -Count 16) on Windows, and use C(od -a -t x1 -N 16 <file>) on Linux. '''
gpl-3.0
jhawkesworth/ansible
lib/ansible/modules/network/avi/avi_serverautoscalepolicy.py
31
7506
#!/usr/bin/python # # @author: Gaurav Rastogi (grastogi@avinetworks.com) # Eric Anderson (eanderson@avinetworks.com) # module_check: supported # # Copyright: (c) 2017 Gaurav Rastogi, <grastogi@avinetworks.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: avi_serverautoscalepolicy author: Gaurav Rastogi (@grastogi23) <grastogi@avinetworks.com> short_description: Module for setup of ServerAutoScalePolicy Avi RESTful Object description: - This module is used to configure ServerAutoScalePolicy object - more examples at U(https://github.com/avinetworks/devops) requirements: [ avisdk ] version_added: "2.4" options: state: description: - The state that should be applied on the entity. default: present choices: ["absent", "present"] avi_api_update_method: description: - Default method for object update is HTTP PUT. - Setting to patch will override that behavior to use HTTP PATCH. version_added: "2.5" default: put choices: ["put", "patch"] avi_api_patch_op: description: - Patch operation to use when using avi_api_update_method as patch. version_added: "2.5" choices: ["add", "replace", "delete"] description: description: - User defined description for the object. intelligent_autoscale: description: - Use avi intelligent autoscale algorithm where autoscale is performed by comparing load on the pool against estimated capacity of all the servers. - Default value when not specified in API or module is interpreted by Avi Controller as False. type: bool intelligent_scalein_margin: description: - Maximum extra capacity as percentage of load used by the intelligent scheme. - Scalein is triggered when available capacity is more than this margin. - Allowed values are 1-99. - Default value when not specified in API or module is interpreted by Avi Controller as 40. intelligent_scaleout_margin: description: - Minimum extra capacity as percentage of load used by the intelligent scheme. - Scaleout is triggered when available capacity is less than this margin. - Allowed values are 1-99. - Default value when not specified in API or module is interpreted by Avi Controller as 20. max_scalein_adjustment_step: description: - Maximum number of servers to scalein simultaneously. - The actual number of servers to scalein is chosen such that target number of servers is always more than or equal to the min_size. - Default value when not specified in API or module is interpreted by Avi Controller as 1. max_scaleout_adjustment_step: description: - Maximum number of servers to scaleout simultaneously. - The actual number of servers to scaleout is chosen such that target number of servers is always less than or equal to the max_size. - Default value when not specified in API or module is interpreted by Avi Controller as 1. max_size: description: - Maximum number of servers after scaleout. - Allowed values are 0-400. min_size: description: - No scale-in happens once number of operationally up servers reach min_servers. - Allowed values are 0-400. name: description: - Name of the object. required: true scalein_alertconfig_refs: description: - Trigger scalein when alerts due to any of these alert configurations are raised. - It is a reference to an object of type alertconfig. scalein_cooldown: description: - Cooldown period during which no new scalein is triggered to allow previous scalein to successfully complete. - Default value when not specified in API or module is interpreted by Avi Controller as 300. - Units(SEC). scaleout_alertconfig_refs: description: - Trigger scaleout when alerts due to any of these alert configurations are raised. - It is a reference to an object of type alertconfig. scaleout_cooldown: description: - Cooldown period during which no new scaleout is triggered to allow previous scaleout to successfully complete. - Default value when not specified in API or module is interpreted by Avi Controller as 300. - Units(SEC). tenant_ref: description: - It is a reference to an object of type tenant. url: description: - Avi controller URL of the object. use_predicted_load: description: - Use predicted load rather than current load. - Default value when not specified in API or module is interpreted by Avi Controller as False. type: bool uuid: description: - Unique object identifier of the object. extends_documentation_fragment: - avi ''' EXAMPLES = """ - name: Example to create ServerAutoScalePolicy object avi_serverautoscalepolicy: controller: 10.10.25.42 username: admin password: something state: present name: sample_serverautoscalepolicy """ RETURN = ''' obj: description: ServerAutoScalePolicy (api/serverautoscalepolicy) object returned: success, changed type: dict ''' from ansible.module_utils.basic import AnsibleModule try: from ansible.module_utils.network.avi.avi import ( avi_common_argument_spec, HAS_AVI, avi_ansible_api) except ImportError: HAS_AVI = False def main(): argument_specs = dict( state=dict(default='present', choices=['absent', 'present']), avi_api_update_method=dict(default='put', choices=['put', 'patch']), avi_api_patch_op=dict(choices=['add', 'replace', 'delete']), description=dict(type='str',), intelligent_autoscale=dict(type='bool',), intelligent_scalein_margin=dict(type='int',), intelligent_scaleout_margin=dict(type='int',), max_scalein_adjustment_step=dict(type='int',), max_scaleout_adjustment_step=dict(type='int',), max_size=dict(type='int',), min_size=dict(type='int',), name=dict(type='str', required=True), scalein_alertconfig_refs=dict(type='list',), scalein_cooldown=dict(type='int',), scaleout_alertconfig_refs=dict(type='list',), scaleout_cooldown=dict(type='int',), tenant_ref=dict(type='str',), url=dict(type='str',), use_predicted_load=dict(type='bool',), uuid=dict(type='str',), ) argument_specs.update(avi_common_argument_spec()) module = AnsibleModule( argument_spec=argument_specs, supports_check_mode=True) if not HAS_AVI: return module.fail_json(msg=( 'Avi python API SDK (avisdk>=17.1) is not installed. ' 'For more details visit https://github.com/avinetworks/sdk.')) return avi_ansible_api(module, 'serverautoscalepolicy', set([])) if __name__ == '__main__': main()
gpl-3.0
keras-team/keras-tuner
keras_tuner/engine/base_tuner.py
1
12695
# Copyright 2019 The Keras Tuner Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://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. "Tuner base class." from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tensorflow as tf from .. import utils from ..distribute import oracle_chief from ..distribute import oracle_client from ..distribute import utils as dist_utils from . import hypermodel as hm_module from . import oracle as oracle_module from . import stateful from . import trial as trial_module from . import tuner_utils class BaseTuner(stateful.Stateful): """Tuner base class. `BaseTuner` is the base class for all Tuners, which manages the search loop, Oracle, logging, saving, etc. Tuners for non-Keras models can be created by subclassing `BaseTuner`. Args: oracle: Instance of Oracle class. hypermodel: Instance of HyperModel class (or callable that takes hyperparameters and returns a Model instance). directory: A string, the relative path to the working directory. project_name: A string, the name to use as prefix for files saved by this Tuner. logger: Optional instance of `kerastuner.Logger` class for streaming logs for monitoring. overwrite: Boolean, defaults to `False`. If `False`, reloads an existing project of the same name if one is found. Otherwise, overwrites the project. Attributes: remaining_trials: Number of trials remaining, `None` if `max_trials` is not set. This is useful when resuming a previously stopped search. """ def __init__( self, oracle, hypermodel, directory=None, project_name=None, logger=None, overwrite=False, ): # Ops and metadata self.directory = directory or "." self.project_name = project_name or "untitled_project" if overwrite and tf.io.gfile.exists(self.project_dir): tf.io.gfile.rmtree(self.project_dir) if not isinstance(oracle, oracle_module.Oracle): raise ValueError( "Expected oracle to be " "an instance of Oracle, got: %s" % (oracle,) ) self.oracle = oracle self.oracle._set_project_dir( self.directory, self.project_name, overwrite=overwrite ) # Run in distributed mode. if dist_utils.is_chief_oracle(): # Blocks forever. oracle_chief.start_server(self.oracle) elif dist_utils.has_chief_oracle(): # Proxies requests to the chief oracle. self.oracle = oracle_client.OracleClient(self.oracle) # To support tuning distribution. self.tuner_id = os.environ.get("KERASTUNER_TUNER_ID", "tuner0") self.hypermodel = hm_module.get_hypermodel(hypermodel) # Logs etc self.logger = logger self._display = tuner_utils.Display(oracle=self.oracle) self._populate_initial_space() if not overwrite and tf.io.gfile.exists(self._get_tuner_fname()): tf.get_logger().info( "Reloading Tuner from {}".format(self._get_tuner_fname()) ) self.reload() def _populate_initial_space(self): """Populate initial search space for oracle. Keep this function as a subroutine for AutoKeras to override. The space may not be ready at the initialization of the tuner, but after seeing the training data. """ hp = self.oracle.get_space() self.hypermodel.build(hp) self.oracle.update_space(hp) def search(self, *fit_args, **fit_kwargs): """Performs a search for best hyperparameter configuations. Args: *fit_args: Positional arguments that should be passed to `run_trial`, for example the training and validation data. **fit_kwargs: Keyword arguments that should be passed to `run_trial`, for example the training and validation data. """ if "verbose" in fit_kwargs: self._display.verbose = fit_kwargs.get("verbose") self.on_search_begin() while True: trial = self.oracle.create_trial(self.tuner_id) if trial.status == trial_module.TrialStatus.STOPPED: # Oracle triggered exit. tf.get_logger().info("Oracle triggered exit") break if trial.status == trial_module.TrialStatus.IDLE: # Oracle is calculating, resend request. continue self.on_trial_begin(trial) self.run_trial(trial, *fit_args, **fit_kwargs) self.on_trial_end(trial) self.on_search_end() def run_trial(self, trial, *fit_args, **fit_kwargs): """Evaluates a set of hyperparameter values. This method is called multiple times during `search` to build and evaluate the models with different hyperparameters. The method is responsible for reporting metrics related to the `Trial` to the `Oracle` via `self.oracle.update_trial`. Example: ```python def run_trial(self, trial, x, y, val_x, val_y): model = self.hypermodel.build(trial.hyperparameters) model.fit(x, y) loss = model.evaluate(val_x, val_y) self.oracle.update_trial( trial.trial_id, {'loss': loss}) self.save_model(trial.trial_id, model) ``` Args: trial: A `Trial` instance that contains the information needed to run this trial. Hyperparameters can be accessed via `trial.hyperparameters`. *fit_args: Positional arguments passed by `search`. **fit_kwargs: Keyword arguments passed by `search`. """ raise NotImplementedError def save_model(self, trial_id, model, step=0): """Saves a Model for a given trial. Args: trial_id: The ID of the `Trial` corresponding to this Model. model: The trained model. step: Integer, for models that report intermediate results to the `Oracle`, the step the saved file correspond to. For example, for Keras models this is the number of epochs trained. """ raise NotImplementedError def load_model(self, trial): """Loads a Model from a given trial. For models that report intermediate results to the `Oracle`, generally `load_model` should load the best reported `step` by relying of `trial.best_step`. Args: trial: A `Trial` instance, the `Trial` corresponding to the model to load. """ raise NotImplementedError def on_trial_begin(self, trial): """Called at the beginning of a trial. Args: trial: A `Trial` instance. """ if self.logger: self.logger.register_trial(trial.trial_id, trial.get_state()) self._display.on_trial_begin(self.oracle.get_trial(trial.trial_id)) def on_trial_end(self, trial): """Called at the end of a trial. Args: trial: A `Trial` instance. """ # Send status to Logger if self.logger: self.logger.report_trial_state(trial.trial_id, trial.get_state()) self.oracle.end_trial(trial.trial_id, trial_module.TrialStatus.COMPLETED) self.oracle.update_space(trial.hyperparameters) # Display needs the updated trial scored by the Oracle. self._display.on_trial_end(self.oracle.get_trial(trial.trial_id)) self.save() def on_search_begin(self): """Called at the beginning of the `search` method.""" if self.logger: self.logger.register_tuner(self.get_state()) def on_search_end(self): """Called at the end of the `search` method.""" if self.logger: self.logger.exit() def get_best_models(self, num_models=1): """Returns the best model(s), as determined by the objective. This method is for querying the models trained during the search. For best performance, it is recommended to retrain your Model on the full dataset using the best hyperparameters found during `search`, which can be obtained using `tuner.get_best_hyperparameters()`. Args: num_models: Optional number of best models to return. Defaults to 1. Returns: List of trained models sorted from the best to the worst. """ best_trials = self.oracle.get_best_trials(num_models) models = [self.load_model(trial) for trial in best_trials] return models def get_best_hyperparameters(self, num_trials=1): """Returns the best hyperparameters, as determined by the objective. This method can be used to reinstantiate the (untrained) best model found during the search process. Example: ```python best_hp = tuner.get_best_hyperparameters()[0] model = tuner.hypermodel.build(best_hp) ``` Args: num_trials: Optional number of `HyperParameters` objects to return. Returns: List of `HyperParameter` objects sorted from the best to the worst. """ return [t.hyperparameters for t in self.oracle.get_best_trials(num_trials)] def search_space_summary(self, extended=False): """Print search space summary. The methods prints a summary of the hyperparameters in the search space, which can be called before calling the `search` method. Args: extended: Optional boolean, whether to display an extended summary. Defaults to False. """ print("Search space summary") hp = self.oracle.get_space() print("Default search space size: %d" % len(hp.space)) for p in hp.space: config = p.get_config() name = config.pop("name") print("%s (%s)" % (name, p.__class__.__name__)) print(config) def results_summary(self, num_trials=10): """Display tuning results summary. The method prints a summary of the search results including the hyperparameter values and evaluation results for each trial. Args: num_trials: Optional number of trials to display. Defaults to 10. """ print("Results summary") print("Results in %s" % self.project_dir) print("Showing %d best trials" % num_trials) print("{}".format(self.oracle.objective)) best_trials = self.oracle.get_best_trials(num_trials) for trial in best_trials: trial.summary() @property def remaining_trials(self): """Returns the number of trials remaining. Will return `None` if `max_trials` is not set. This is useful when resuming a previously stopped search. """ return self.oracle.remaining_trials() def get_state(self): return {} def set_state(self, state): pass def save(self): """Saves this object to its project directory.""" if not dist_utils.has_chief_oracle(): self.oracle.save() super(BaseTuner, self).save(self._get_tuner_fname()) def reload(self): """Reloads this object from its project directory.""" if not dist_utils.has_chief_oracle(): self.oracle.reload() super(BaseTuner, self).reload(self._get_tuner_fname()) @property def project_dir(self): dirname = os.path.join(str(self.directory), self.project_name) utils.create_directory(dirname) return dirname def get_trial_dir(self, trial_id): dirname = os.path.join(str(self.project_dir), "trial_" + str(trial_id)) utils.create_directory(dirname) return dirname def _get_tuner_fname(self): return os.path.join(str(self.project_dir), str(self.tuner_id) + ".json")
apache-2.0
fritsvanveen/QGIS
python/ext-libs/owslib/fes.py
22
16894
# -*- coding: ISO-8859-15 -*- # ============================================================================= # Copyright (c) 2009 Tom Kralidis # # Authors : Tom Kralidis <tomkralidis@gmail.com> # # Contact email: tomkralidis@gmail.com # ============================================================================= """ API for OGC Filter Encoding (FE) constructs and metadata. Filter Encoding: http://www.opengeospatial.org/standards/filter Currently supports version 1.1.0 (04-095). """ from __future__ import (absolute_import, division, print_function) from owslib.etree import etree from owslib import util from owslib.namespaces import Namespaces # default variables def get_namespaces(): n = Namespaces() ns = n.get_namespaces(["dif","fes","gml","ogc","xs","xsi"]) ns[None] = n.get_namespace("ogc") return ns namespaces = get_namespaces() schema = 'http://schemas.opengis.net/filter/1.1.0/filter.xsd' schema_location = '%s %s' % (namespaces['ogc'], schema) class FilterRequest(object): """ filter class """ def __init__(self, parent=None, version='1.1.0'): """ filter Constructor Parameters ---------- - parent: parent etree.Element object (default is None) - version: version (default is '1.1.0') """ self.version = version self._root = etree.Element(util.nspath_eval('ogc:Filter', namespaces)) if parent is not None: self._root.set(util.nspath_eval('xsi:schemaLocation', namespaces), schema_location) def set(self, parent=False, qtype=None, keywords=[], typenames='csw:Record', propertyname='csw:AnyText', bbox=None, identifier=None): """ Construct and process a GetRecords request Parameters ---------- - parent: the parent Element object. If this is not, then generate a standalone request - qtype: type of resource to query (i.e. service, dataset) - keywords: list of keywords - propertyname: the PropertyName to Filter against - bbox: the bounding box of the spatial query in the form [minx,miny,maxx,maxy] - identifier: the dc:identifier to query against with a PropertyIsEqualTo. Ignores all other inputs. """ # Set the identifier if passed. Ignore other parameters dc_identifier_equals_filter = None if identifier is not None: dc_identifier_equals_filter = PropertyIsEqualTo('dc:identifier', identifier) self._root.append(dc_identifier_equals_filter.toXML()) return self._root # Set the query type if passed dc_type_equals_filter = None if qtype is not None: dc_type_equals_filter = PropertyIsEqualTo('dc:type', qtype) # Set a bbox query if passed bbox_filter = None if bbox is not None: bbox_filter = BBox(bbox) # Set a keyword query if passed keyword_filter = None if len(keywords) > 0: if len(keywords) > 1: # loop multiple keywords into an Or ks = [] for i in keywords: ks.append(PropertyIsLike(propertyname, "*%s*" % i, wildCard="*")) keyword_filter = Or(operations=ks) elif len(keywords) == 1: # one keyword keyword_filter = PropertyIsLike(propertyname, "*%s*" % keywords[0], wildCard="*") # And together filters if more than one exists filters = [_f for _f in [keyword_filter, bbox_filter, dc_type_equals_filter] if _f] if len(filters) == 1: self._root.append(filters[0].toXML()) elif len(filters) > 1: self._root.append(And(operations=filters).toXML()) return self._root def setConstraint(self, constraint, tostring=False): """ Construct and process a GetRecords request Parameters ---------- - constraint: An OgcExpression object - tostring (optional): return as string """ self._root.append(constraint.toXML()) if tostring: return util.element_to_string(self._root, xml_declaration=False) return self._root def setConstraintList(self, constraints, tostring=False): """ Construct and process a GetRecords request Parameters ---------- - constraints: A list of OgcExpression objects The list is interpretted like so: [a,b,c] a || b || c [[a,b,c]] a && b && c [[a,b],[c],[d],[e]] or [[a,b],c,d,e] (a && b) || c || d || e - tostring (optional): return as string """ ors = [] if len(constraints) == 1: if isinstance(constraints[0], OgcExpression): flt = self.setConstraint(constraints[0]) else: self._root.append(And(operations=constraints[0]).toXML()) flt = self._root if tostring: return util.element_to_string(flt, xml_declaration=False) else: return flt for c in constraints: if isinstance(c, OgcExpression): ors.append(c) elif isinstance(c, list) or isinstance(c, tuple): if len(c) == 1: ors.append(c[0]) elif len(c) >= 2: ands = [] for sub in c: if isinstance(sub, OgcExpression): ands.append(sub) ors.append(And(operations=ands)) self._root.append(Or(operations=ors).toXML()) if tostring: return util.element_to_string(self._root, xml_declaration=False) return self._root class FilterCapabilities(object): """ Abstraction for Filter_Capabilities """ def __init__(self, elem): # Spatial_Capabilities self.spatial_operands = [f.text for f in elem.findall(util.nspath_eval('ogc:Spatial_Capabilities/ogc:GeometryOperands/ogc:GeometryOperand', namespaces))] self.spatial_operators = [] for f in elem.findall(util.nspath_eval('ogc:Spatial_Capabilities/ogc:SpatialOperators/ogc:SpatialOperator', namespaces)): self.spatial_operators.append(f.attrib['name']) # Temporal_Capabilities self.temporal_operands = [f.text for f in elem.findall(util.nspath_eval('ogc:Temporal_Capabilities/ogc:TemporalOperands/ogc:TemporalOperand', namespaces))] self.temporal_operators = [] for f in elem.findall(util.nspath_eval('ogc:Temporal_Capabilities/ogc:TemporalOperators/ogc:TemporalOperator', namespaces)): self.temporal_operators.append(f.attrib['name']) # Scalar_Capabilities self.scalar_comparison_operators = [f.text for f in elem.findall(util.nspath_eval('ogc:Scalar_Capabilities/ogc:ComparisonOperators/ogc:ComparisonOperator', namespaces))] class FilterCapabilities200(object): """Abstraction for Filter_Capabilities 2.0""" def __init__(self, elem): # Spatial_Capabilities self.spatial_operands = [f.attrib.get('name') for f in elem.findall(util.nspath_eval('fes:Spatial_Capabilities/fes:GeometryOperands/fes:GeometryOperand', namespaces))] self.spatial_operators = [] for f in elem.findall(util.nspath_eval('fes:Spatial_Capabilities/fes:SpatialOperators/fes:SpatialOperator', namespaces)): self.spatial_operators.append(f.attrib['name']) # Temporal_Capabilities self.temporal_operands = [f.attrib.get('name') for f in elem.findall(util.nspath_eval('fes:Temporal_Capabilities/fes:TemporalOperands/fes:TemporalOperand', namespaces))] self.temporal_operators = [] for f in elem.findall(util.nspath_eval('fes:Temporal_Capabilities/fes:TemporalOperators/fes:TemporalOperator', namespaces)): self.temporal_operators.append(f.attrib['name']) # Scalar_Capabilities self.scalar_comparison_operators = [f.text for f in elem.findall(util.nspath_eval('fes:Scalar_Capabilities/fes:ComparisonOperators/fes:ComparisonOperator', namespaces))] # Conformance self.conformance = [] for f in elem.findall(util.nspath_eval('fes:Conformance/fes:Constraint', namespaces)): self.conformance[f.attrib.get('name')] = f.find(util.nspath_eval('fes:DefaultValue', namespaces)).text def setsortby(parent, propertyname, order='ASC'): """ constructs a SortBy element Parameters ---------- - parent: parent etree.Element object - propertyname: the PropertyName - order: the SortOrder (default is 'ASC') """ tmp = etree.SubElement(parent, util.nspath_eval('ogc:SortBy', namespaces)) tmp2 = etree.SubElement(tmp, util.nspath_eval('ogc:SortProperty', namespaces)) etree.SubElement(tmp2, util.nspath_eval('ogc:PropertyName', namespaces)).text = propertyname etree.SubElement(tmp2, util.nspath_eval('ogc:SortOrder', namespaces)).text = order class SortProperty(object): def __init__(self, propertyname, order='ASC'): self.propertyname = propertyname self.order = order.upper() if self.order not in ['DESC','ASC']: raise ValueError("SortOrder can only be 'ASC' or 'DESC'") def toXML(self): node0 = etree.Element(util.nspath_eval("ogc:SortProperty", namespaces)) etree.SubElement(node0, util.nspath_eval('ogc:PropertyName', namespaces)).text = self.propertyname etree.SubElement(node0, util.nspath_eval('ogc:SortOrder', namespaces)).text = self.order return node0 class SortBy(object): def __init__(self, properties): self.properties = properties def toXML(self): node0 = etree.Element(util.nspath_eval("ogc:SortBy", namespaces)) for prop in self.properties: node0.append(prop.toXML()) return node0 class OgcExpression(object): def __init__(self): pass class BinaryComparisonOpType(OgcExpression): """ Super class of all the property operation classes""" def __init__(self, propertyoperator, propertyname, literal, matchcase=True): self.propertyoperator = propertyoperator self.propertyname = propertyname self.literal = literal self.matchcase = matchcase def toXML(self): node0 = etree.Element(util.nspath_eval(self.propertyoperator, namespaces)) if not self.matchcase: node0.set('matchCase', 'false') etree.SubElement(node0, util.nspath_eval('ogc:PropertyName', namespaces)).text = self.propertyname etree.SubElement(node0, util.nspath_eval('ogc:Literal', namespaces)).text = self.literal return node0 class PropertyIsEqualTo(BinaryComparisonOpType): """ PropertyIsEqualTo class""" def __init__(self, propertyname, literal, matchcase=True): BinaryComparisonOpType.__init__(self, 'ogc:PropertyIsEqualTo', propertyname, literal, matchcase) class PropertyIsNotEqualTo(BinaryComparisonOpType): """ PropertyIsNotEqualTo class """ def __init__(self, propertyname, literal, matchcase=True): BinaryComparisonOpType.__init__(self, 'ogc:PropertyIsNotEqualTo', propertyname, literal, matchcase) class PropertyIsLessThan(BinaryComparisonOpType): """PropertyIsLessThan class""" def __init__(self, propertyname, literal, matchcase=True): BinaryComparisonOpType.__init__(self, 'ogc:PropertyIsLessThan', propertyname, literal, matchcase) class PropertyIsGreaterThan(BinaryComparisonOpType): """PropertyIsGreaterThan class""" def __init__(self, propertyname, literal, matchcase=True): BinaryComparisonOpType.__init__(self, 'ogc:PropertyIsGreaterThan', propertyname, literal, matchcase) class PropertyIsLessThanOrEqualTo(BinaryComparisonOpType): """PropertyIsLessThanOrEqualTo class""" def __init__(self, propertyname, literal, matchcase=True): BinaryComparisonOpType.__init__(self, 'ogc:PropertyIsLessThanOrEqualTo', propertyname, literal, matchcase) class PropertyIsGreaterThanOrEqualTo(BinaryComparisonOpType): """PropertyIsGreaterThanOrEqualTo class""" def __init__(self, propertyname, literal, matchcase=True): BinaryComparisonOpType.__init__(self, 'ogc:PropertyIsGreaterThanOrEqualTo', propertyname, literal, matchcase) class PropertyIsLike(OgcExpression): """PropertyIsLike class""" def __init__(self, propertyname, literal, escapeChar='\\', singleChar='_', wildCard='%', matchCase=True): self.propertyname = propertyname self.literal = literal self.escapeChar = escapeChar self.singleChar = singleChar self.wildCard = wildCard self.matchCase = matchCase def toXML(self): node0 = etree.Element(util.nspath_eval('ogc:PropertyIsLike', namespaces)) node0.set('wildCard', self.wildCard) node0.set('singleChar', self.singleChar) node0.set('escapeChar', self.escapeChar) if not self.matchCase: node0.set('matchCase', 'false') etree.SubElement(node0, util.nspath_eval('ogc:PropertyName', namespaces)).text = self.propertyname etree.SubElement(node0, util.nspath_eval('ogc:Literal', namespaces)).text = self.literal return node0 class PropertyIsNull(OgcExpression): """PropertyIsNull class""" def __init__(self, propertyname): self.propertyname = propertyname def toXML(self): node0 = etree.Element(util.nspath_eval('ogc:PropertyIsNull', namespaces)) etree.SubElement(node0, util.nspath_eval('ogc:PropertyName', namespaces)).text = self.propertyname return node0 class PropertyIsBetween(OgcExpression): """PropertyIsBetween class""" def __init__(self, propertyname, lower, upper): self.propertyname = propertyname self.lower = lower self.upper = upper def toXML(self): node0 = etree.Element(util.nspath_eval('ogc:PropertyIsBetween', namespaces)) etree.SubElement(node0, util.nspath_eval('ogc:PropertyName', namespaces)).text = self.propertyname node1 = etree.SubElement(node0, util.nspath_eval('ogc:LowerBoundary', namespaces)) etree.SubElement(node1, util.nspath_eval('ogc:Literal', namespaces)).text = '%s' % self.lower node2 = etree.SubElement(node0, util.nspath_eval('ogc:UpperBoundary', namespaces)) etree.SubElement(node2, util.nspath_eval('ogc:Literal', namespaces)).text = '%s' % self.upper return node0 class BBox(OgcExpression): """Construct a BBox, two pairs of coordinates (west-south and east-north)""" def __init__(self, bbox, crs=None): self.bbox = bbox self.crs = crs def toXML(self): tmp = etree.Element(util.nspath_eval('ogc:BBOX', namespaces)) etree.SubElement(tmp, util.nspath_eval('ogc:PropertyName', namespaces)).text = 'ows:BoundingBox' tmp2 = etree.SubElement(tmp, util.nspath_eval('gml:Envelope', namespaces)) if self.crs is not None: tmp2.set('srsName', self.crs) etree.SubElement(tmp2, util.nspath_eval('gml:lowerCorner', namespaces)).text = '%s %s' % (self.bbox[0], self.bbox[1]) etree.SubElement(tmp2, util.nspath_eval('gml:upperCorner', namespaces)).text = '%s %s' % (self.bbox[2], self.bbox[3]) return tmp # BINARY class BinaryLogicOpType(OgcExpression): """ Binary Operators: And / Or """ def __init__(self, binary_operator, operations): self.binary_operator = binary_operator try: assert len(operations) >= 2 self.operations = operations except: raise ValueError("Binary operations (And / Or) require a minimum of two operations to operate against") def toXML(self): node0 = etree.Element(util.nspath_eval(self.binary_operator, namespaces)) for op in self.operations: node0.append(op.toXML()) return node0 class And(BinaryLogicOpType): def __init__(self, operations): super(And,self).__init__('ogc:And', operations) class Or(BinaryLogicOpType): def __init__(self, operations): super(Or,self).__init__('ogc:Or', operations) # UNARY class UnaryLogicOpType(OgcExpression): """ Unary Operator: Not """ def __init__(self, urary_operator, operations): self.urary_operator = urary_operator self.operations = operations def toXML(self): node0 = etree.Element(util.nspath_eval(self.urary_operator, namespaces)) for op in self.operations: node0.append(op.toXML()) return node0 class Not(UnaryLogicOpType): def __init__(self, operations): super(Not,self).__init__('ogc:Not', operations)
gpl-2.0
MarkusAlexander/makken
node_modules/pangyp/gyp/pylib/gyp/generator/ninja_test.py
1843
1786
#!/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. """ Unit tests for the ninja.py file. """ import gyp.generator.ninja as ninja import unittest import StringIO import sys import TestCommon class TestPrefixesAndSuffixes(unittest.TestCase): def test_BinaryNamesWindows(self): # These cannot run on non-Windows as they require a VS installation to # correctly handle variable expansion. if sys.platform.startswith('win'): writer = ninja.NinjaWriter('foo', 'wee', '.', '.', 'build.ninja', '.', 'build.ninja', 'win') spec = { 'target_name': 'wee' } self.assertTrue(writer.ComputeOutputFileName(spec, 'executable'). endswith('.exe')) self.assertTrue(writer.ComputeOutputFileName(spec, 'shared_library'). endswith('.dll')) self.assertTrue(writer.ComputeOutputFileName(spec, 'static_library'). endswith('.lib')) def test_BinaryNamesLinux(self): writer = ninja.NinjaWriter('foo', 'wee', '.', '.', 'build.ninja', '.', 'build.ninja', 'linux') spec = { 'target_name': 'wee' } self.assertTrue('.' not in writer.ComputeOutputFileName(spec, 'executable')) self.assertTrue(writer.ComputeOutputFileName(spec, 'shared_library'). startswith('lib')) self.assertTrue(writer.ComputeOutputFileName(spec, 'static_library'). startswith('lib')) self.assertTrue(writer.ComputeOutputFileName(spec, 'shared_library'). endswith('.so')) self.assertTrue(writer.ComputeOutputFileName(spec, 'static_library'). endswith('.a')) if __name__ == '__main__': unittest.main()
mit
pnedunuri/scipy
scipy/special/tests/test_basic.py
24
122406
# this program corresponds to special.py ### Means test is not done yet # E Means test is giving error (E) # F Means test is failing (F) # EF Means test is giving error and Failing #! Means test is segfaulting # 8 Means test runs forever ### test_besselpoly ### test_mathieu_a ### test_mathieu_even_coef ### test_mathieu_odd_coef ### test_modfresnelp ### test_modfresnelm # test_pbdv_seq ### test_pbvv_seq ### test_sph_harm # test_sph_in # test_sph_jn # test_sph_kn from __future__ import division, print_function, absolute_import import itertools import warnings import numpy as np from numpy import array, isnan, r_, arange, finfo, pi, sin, cos, tan, exp, \ log, zeros, sqrt, asarray, inf, nan_to_num, real, arctan, float_ from numpy.testing import assert_equal, assert_almost_equal, \ assert_array_equal, assert_array_almost_equal, assert_approx_equal, \ assert_, rand, dec, TestCase, run_module_suite, assert_allclose, \ assert_raises, assert_array_almost_equal_nulp from scipy import special import scipy.special._ufuncs as cephes from scipy.special import ellipk from scipy.special._testutils import assert_tol_equal, with_special_errors, \ assert_func_equal class TestCephes(TestCase): def test_airy(self): cephes.airy(0) def test_airye(self): cephes.airye(0) def test_binom(self): n = np.array([0.264, 4, 5.2, 17]) k = np.array([2, 0.4, 7, 3.3]) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T rknown = np.array([[-0.097152, 0.9263051596159367, 0.01858423645695389, -0.007581020651518199],[6, 2.0214389119675666, 0, 2.9827344527963846], [10.92, 2.22993515861399, -0.00585728, 10.468891352063146], [136, 3.5252179590758828, 19448, 1024.5526916174495]]) assert_func_equal(cephes.binom, rknown.ravel(), nk, rtol=1e-13) # Test branches in implementation np.random.seed(1234) n = np.r_[np.arange(-7, 30), 1000*np.random.rand(30) - 500] k = np.arange(0, 102) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T assert_func_equal(cephes.binom, cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)), nk, atol=1e-10, rtol=1e-10) def test_binom_2(self): # Test branches in implementation np.random.seed(1234) n = np.r_[np.logspace(1, 300, 20)] k = np.arange(0, 102) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T assert_func_equal(cephes.binom, cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)), nk, atol=1e-10, rtol=1e-10) def test_binom_exact(self): @np.vectorize def binom_int(n, k): n = int(n) k = int(k) num = int(1) den = int(1) for i in range(1, k+1): num *= i + n - k den *= i return float(num/den) np.random.seed(1234) n = np.arange(1, 15) k = np.arange(0, 15) nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) ).reshape(2, -1).T nk = nk[nk[:,0] >= nk[:,1]] assert_func_equal(cephes.binom, binom_int(nk[:,0], nk[:,1]), nk, atol=0, rtol=0) def test_bdtr(self): assert_equal(cephes.bdtr(1,1,0.5),1.0) def test_bdtri(self): assert_equal(cephes.bdtri(1,3,0.5),0.5) def test_bdtrc(self): assert_equal(cephes.bdtrc(1,3,0.5),0.5) def test_bdtrin(self): assert_equal(cephes.bdtrin(1,0,1),5.0) def test_bdtrik(self): cephes.bdtrik(1,3,0.5) def test_bei(self): assert_equal(cephes.bei(0),0.0) def test_beip(self): assert_equal(cephes.beip(0),0.0) def test_ber(self): assert_equal(cephes.ber(0),1.0) def test_berp(self): assert_equal(cephes.berp(0),0.0) def test_besselpoly(self): assert_equal(cephes.besselpoly(0,0,0),1.0) def test_beta(self): assert_equal(cephes.beta(1,1),1.0) assert_allclose(cephes.beta(-100.3, 1e-200), cephes.gamma(1e-200)) assert_allclose(cephes.beta(0.0342, 171), 24.070498359873497, rtol=1e-13, atol=0) def test_betainc(self): assert_equal(cephes.betainc(1,1,1),1.0) assert_allclose(cephes.betainc(0.0342, 171, 1e-10), 0.55269916901806648) def test_betaln(self): assert_equal(cephes.betaln(1,1),0.0) assert_allclose(cephes.betaln(-100.3, 1e-200), cephes.gammaln(1e-200)) assert_allclose(cephes.betaln(0.0342, 170), 3.1811881124242447, rtol=1e-14, atol=0) def test_betaincinv(self): assert_equal(cephes.betaincinv(1,1,1),1.0) assert_allclose(cephes.betaincinv(0.0342, 171, 0.25), 8.4231316935498957e-21, rtol=3e-12, atol=0) def test_beta_inf(self): assert_(np.isinf(special.beta(-1, 2))) def test_btdtr(self): assert_equal(cephes.btdtr(1,1,1),1.0) def test_btdtri(self): assert_equal(cephes.btdtri(1,1,1),1.0) def test_btdtria(self): assert_equal(cephes.btdtria(1,1,1),5.0) def test_btdtrib(self): assert_equal(cephes.btdtrib(1,1,1),5.0) def test_cbrt(self): assert_approx_equal(cephes.cbrt(1),1.0) def test_chdtr(self): assert_equal(cephes.chdtr(1,0),0.0) def test_chdtrc(self): assert_equal(cephes.chdtrc(1,0),1.0) def test_chdtri(self): assert_equal(cephes.chdtri(1,1),0.0) def test_chdtriv(self): assert_equal(cephes.chdtriv(0,0),5.0) def test_chndtr(self): assert_equal(cephes.chndtr(0,1,0),0.0) p = cephes.chndtr(np.linspace(20, 25, 5), 2, 1.07458615e+02) assert_allclose(p, [1.21805009e-09, 2.81979982e-09, 6.25652736e-09, 1.33520017e-08, 2.74909967e-08], rtol=1e-6, atol=0) assert_almost_equal(cephes.chndtr(np.inf, np.inf, 0), 2.0) assert_almost_equal(cephes.chndtr(2, 1, np.inf), 0.0) assert_(np.isnan(cephes.chndtr(np.nan, 1, 2))) assert_(np.isnan(cephes.chndtr(5, np.nan, 2))) assert_(np.isnan(cephes.chndtr(5, 1, np.nan))) def test_chndtridf(self): assert_equal(cephes.chndtridf(0,0,1),5.0) def test_chndtrinc(self): assert_equal(cephes.chndtrinc(0,1,0),5.0) def test_chndtrix(self): assert_equal(cephes.chndtrix(0,1,0),0.0) def test_cosdg(self): assert_equal(cephes.cosdg(0),1.0) def test_cosm1(self): assert_equal(cephes.cosm1(0),0.0) def test_cotdg(self): assert_almost_equal(cephes.cotdg(45),1.0) def test_dawsn(self): assert_equal(cephes.dawsn(0),0.0) assert_allclose(cephes.dawsn(1.23), 0.50053727749081767) def test_diric(self): # Test behavior near multiples of 2pi. Regression test for issue # described in gh-4001. n_odd = [1, 5, 25] x = np.array(2*np.pi + 5e-5).astype(np.float32) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=7) x = np.array(2*np.pi + 1e-9).astype(np.float64) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15) x = np.array(2*np.pi + 1e-15).astype(np.float64) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15) if hasattr(np, 'float128'): # No float128 available in 32-bit numpy x = np.array(2*np.pi + 1e-12).astype(np.float128) assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=19) n_even = [2, 4, 24] x = np.array(2*np.pi + 1e-9).astype(np.float64) assert_almost_equal(special.diric(x, n_even), -1.0, decimal=15) # Test at some values not near a multiple of pi x = np.arange(0.2*np.pi, 1.0*np.pi, 0.2*np.pi) octave_result = [0.872677996249965, 0.539344662916632, 0.127322003750035, -0.206011329583298] assert_almost_equal(special.diric(x, 3), octave_result, decimal=15) def test_diric_broadcasting(self): x = np.arange(5) n = np.array([1, 3, 7]) assert_(special.diric(x[:, np.newaxis], n).shape == (x.size, n.size)) def test_ellipe(self): assert_equal(cephes.ellipe(1),1.0) def test_ellipeinc(self): assert_equal(cephes.ellipeinc(0,1),0.0) def test_ellipj(self): cephes.ellipj(0,1) def test_ellipk(self): assert_allclose(ellipk(0), pi/2) def test_ellipkinc(self): assert_equal(cephes.ellipkinc(0,0),0.0) def test_erf(self): assert_equal(cephes.erf(0),0.0) def test_erfc(self): assert_equal(cephes.erfc(0),1.0) def test_exp1(self): cephes.exp1(1) def test_expi(self): cephes.expi(1) def test_expn(self): cephes.expn(1,1) def test_exp1_reg(self): # Regression for #834 a = cephes.exp1(-complex(19.9999990)) b = cephes.exp1(-complex(19.9999991)) assert_array_almost_equal(a.imag, b.imag) def test_exp10(self): assert_approx_equal(cephes.exp10(2),100.0) def test_exp2(self): assert_equal(cephes.exp2(2),4.0) def test_expm1(self): assert_equal(cephes.expm1(0),0.0) def test_fdtr(self): assert_equal(cephes.fdtr(1,1,0),0.0) def test_fdtrc(self): assert_equal(cephes.fdtrc(1,1,0),1.0) def test_fdtri(self): # cephes.fdtri(1,1,0.5) #BUG: gives NaN, should be 1 assert_allclose(cephes.fdtri(1, 1, [0.499, 0.501]), array([0.9937365, 1.00630298]), rtol=1e-6) def test_fdtridfd(self): assert_equal(cephes.fdtridfd(1,0,0),5.0) def test_fresnel(self): assert_equal(cephes.fresnel(0),(0.0,0.0)) def test_gamma(self): assert_equal(cephes.gamma(5),24.0) def test_gammainc(self): assert_equal(cephes.gammainc(5,0),0.0) def test_gammaincc(self): assert_equal(cephes.gammaincc(5,0),1.0) def test_gammainccinv(self): assert_equal(cephes.gammainccinv(5,1),0.0) def test_gammaln(self): cephes.gammaln(10) def test_gammasgn(self): vals = np.array([-4, -3.5, -2.3, 1, 4.2], np.float64) assert_array_equal(cephes.gammasgn(vals), np.sign(cephes.rgamma(vals))) def test_gdtr(self): assert_equal(cephes.gdtr(1,1,0),0.0) def test_gdtrc(self): assert_equal(cephes.gdtrc(1,1,0),1.0) def test_gdtria(self): assert_equal(cephes.gdtria(0,1,1),0.0) def test_gdtrib(self): cephes.gdtrib(1,0,1) # assert_equal(cephes.gdtrib(1,0,1),5.0) def test_gdtrix(self): cephes.gdtrix(1,1,.1) def test_hankel1(self): cephes.hankel1(1,1) def test_hankel1e(self): cephes.hankel1e(1,1) def test_hankel2(self): cephes.hankel2(1,1) def test_hankel2e(self): cephes.hankel2e(1,1) def test_hyp1f1(self): assert_approx_equal(cephes.hyp1f1(1,1,1), exp(1.0)) assert_approx_equal(cephes.hyp1f1(3,4,-6), 0.026056422099537251095) cephes.hyp1f1(1,1,1) def test_hyp1f2(self): cephes.hyp1f2(1,1,1,1) def test_hyp2f0(self): cephes.hyp2f0(1,1,1,1) def test_hyp2f1(self): assert_equal(cephes.hyp2f1(1,1,1,0),1.0) def test_hyp3f0(self): assert_equal(cephes.hyp3f0(1,1,1,0),(1.0,0.0)) def test_hyperu(self): assert_equal(cephes.hyperu(0,1,1),1.0) def test_i0(self): assert_equal(cephes.i0(0),1.0) def test_i0e(self): assert_equal(cephes.i0e(0),1.0) def test_i1(self): assert_equal(cephes.i1(0),0.0) def test_i1e(self): assert_equal(cephes.i1e(0),0.0) def test_it2i0k0(self): cephes.it2i0k0(1) def test_it2j0y0(self): cephes.it2j0y0(1) def test_it2struve0(self): cephes.it2struve0(1) def test_itairy(self): cephes.itairy(1) def test_iti0k0(self): assert_equal(cephes.iti0k0(0),(0.0,0.0)) def test_itj0y0(self): assert_equal(cephes.itj0y0(0),(0.0,0.0)) def test_itmodstruve0(self): assert_equal(cephes.itmodstruve0(0),0.0) def test_itstruve0(self): assert_equal(cephes.itstruve0(0),0.0) def test_iv(self): assert_equal(cephes.iv(1,0),0.0) def _check_ive(self): assert_equal(cephes.ive(1,0),0.0) def test_j0(self): assert_equal(cephes.j0(0),1.0) def test_j1(self): assert_equal(cephes.j1(0),0.0) def test_jn(self): assert_equal(cephes.jn(0,0),1.0) def test_jv(self): assert_equal(cephes.jv(0,0),1.0) def _check_jve(self): assert_equal(cephes.jve(0,0),1.0) def test_k0(self): cephes.k0(2) def test_k0e(self): cephes.k0e(2) def test_k1(self): cephes.k1(2) def test_k1e(self): cephes.k1e(2) def test_kei(self): cephes.kei(2) def test_keip(self): assert_equal(cephes.keip(0),0.0) def test_ker(self): cephes.ker(2) def test_kerp(self): cephes.kerp(2) def _check_kelvin(self): cephes.kelvin(2) def test_kn(self): cephes.kn(1,1) def test_kolmogi(self): assert_equal(cephes.kolmogi(1),0.0) assert_(np.isnan(cephes.kolmogi(np.nan))) def test_kolmogorov(self): assert_equal(cephes.kolmogorov(0),1.0) def _check_kv(self): cephes.kv(1,1) def _check_kve(self): cephes.kve(1,1) def test_log1p(self): assert_equal(cephes.log1p(0),0.0) def test_lpmv(self): assert_equal(cephes.lpmv(0,0,1),1.0) def test_mathieu_a(self): assert_equal(cephes.mathieu_a(1,0),1.0) def test_mathieu_b(self): assert_equal(cephes.mathieu_b(1,0),1.0) def test_mathieu_cem(self): assert_equal(cephes.mathieu_cem(1,0,0),(1.0,0.0)) # Test AMS 20.2.27 @np.vectorize def ce_smallq(m, q, z): z *= np.pi/180 if m == 0: return 2**(-0.5) * (1 - .5*q*cos(2*z)) # + O(q^2) elif m == 1: return cos(z) - q/8 * cos(3*z) # + O(q^2) elif m == 2: return cos(2*z) - q*(cos(4*z)/12 - 1/4) # + O(q^2) else: return cos(m*z) - q*(cos((m+2)*z)/(4*(m+1)) - cos((m-2)*z)/(4*(m-1))) # + O(q^2) m = np.arange(0, 100) q = np.r_[0, np.logspace(-30, -9, 10)] assert_allclose(cephes.mathieu_cem(m[:,None], q[None,:], 0.123)[0], ce_smallq(m[:,None], q[None,:], 0.123), rtol=1e-14, atol=0) def test_mathieu_sem(self): assert_equal(cephes.mathieu_sem(1,0,0),(0.0,1.0)) # Test AMS 20.2.27 @np.vectorize def se_smallq(m, q, z): z *= np.pi/180 if m == 1: return sin(z) - q/8 * sin(3*z) # + O(q^2) elif m == 2: return sin(2*z) - q*sin(4*z)/12 # + O(q^2) else: return sin(m*z) - q*(sin((m+2)*z)/(4*(m+1)) - sin((m-2)*z)/(4*(m-1))) # + O(q^2) m = np.arange(1, 100) q = np.r_[0, np.logspace(-30, -9, 10)] assert_allclose(cephes.mathieu_sem(m[:,None], q[None,:], 0.123)[0], se_smallq(m[:,None], q[None,:], 0.123), rtol=1e-14, atol=0) def test_mathieu_modcem1(self): assert_equal(cephes.mathieu_modcem1(1,0,0),(0.0,0.0)) def test_mathieu_modcem2(self): cephes.mathieu_modcem2(1,1,1) # Test reflection relation AMS 20.6.19 m = np.arange(0, 4)[:,None,None] q = np.r_[np.logspace(-2, 2, 10)][None,:,None] z = np.linspace(0, 1, 7)[None,None,:] y1 = cephes.mathieu_modcem2(m, q, -z)[0] fr = -cephes.mathieu_modcem2(m, q, 0)[0] / cephes.mathieu_modcem1(m, q, 0)[0] y2 = -cephes.mathieu_modcem2(m, q, z)[0] - 2*fr*cephes.mathieu_modcem1(m, q, z)[0] assert_allclose(y1, y2, rtol=1e-10) def test_mathieu_modsem1(self): assert_equal(cephes.mathieu_modsem1(1,0,0),(0.0,0.0)) def test_mathieu_modsem2(self): cephes.mathieu_modsem2(1,1,1) # Test reflection relation AMS 20.6.20 m = np.arange(1, 4)[:,None,None] q = np.r_[np.logspace(-2, 2, 10)][None,:,None] z = np.linspace(0, 1, 7)[None,None,:] y1 = cephes.mathieu_modsem2(m, q, -z)[0] fr = cephes.mathieu_modsem2(m, q, 0)[1] / cephes.mathieu_modsem1(m, q, 0)[1] y2 = cephes.mathieu_modsem2(m, q, z)[0] - 2*fr*cephes.mathieu_modsem1(m, q, z)[0] assert_allclose(y1, y2, rtol=1e-10) def test_mathieu_overflow(self): # Check that these return NaNs instead of causing a SEGV assert_equal(cephes.mathieu_cem(10000, 0, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_sem(10000, 0, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_cem(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_sem(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modcem1(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modsem1(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modcem2(10000, 1.5, 1.3), (np.nan, np.nan)) assert_equal(cephes.mathieu_modsem2(10000, 1.5, 1.3), (np.nan, np.nan)) def test_mathieu_ticket_1847(self): # Regression test --- this call had some out-of-bounds access # and could return nan occasionally for k in range(60): v = cephes.mathieu_modsem2(2, 100, -1) # Values from ACM TOMS 804 (derivate by numerical differentiation) assert_allclose(v[0], 0.1431742913063671074347, rtol=1e-10) assert_allclose(v[1], 0.9017807375832909144719, rtol=1e-4) def test_modfresnelm(self): cephes.modfresnelm(0) def test_modfresnelp(self): cephes.modfresnelp(0) def _check_modstruve(self): assert_equal(cephes.modstruve(1,0),0.0) def test_nbdtr(self): assert_equal(cephes.nbdtr(1,1,1),1.0) def test_nbdtrc(self): assert_equal(cephes.nbdtrc(1,1,1),0.0) def test_nbdtri(self): assert_equal(cephes.nbdtri(1,1,1),1.0) def __check_nbdtrik(self): cephes.nbdtrik(1,.4,.5) def test_nbdtrin(self): assert_equal(cephes.nbdtrin(1,0,0),5.0) def test_ncfdtr(self): assert_equal(cephes.ncfdtr(1,1,1,0),0.0) def test_ncfdtri(self): assert_equal(cephes.ncfdtri(1,1,1,0),0.0) def test_ncfdtridfd(self): cephes.ncfdtridfd(1,0.5,0,1) def __check_ncfdtridfn(self): cephes.ncfdtridfn(1,0.5,0,1) def __check_ncfdtrinc(self): cephes.ncfdtrinc(1,0.5,0,1) def test_nctdtr(self): assert_equal(cephes.nctdtr(1,0,0),0.5) assert_equal(cephes.nctdtr(9, 65536, 45), 0.0) assert_approx_equal(cephes.nctdtr(np.inf, 1., 1.), 0.5, 5) assert_(np.isnan(cephes.nctdtr(2., np.inf, 10.))) assert_approx_equal(cephes.nctdtr(2., 1., np.inf), 1.) assert_(np.isnan(cephes.nctdtr(np.nan, 1., 1.))) assert_(np.isnan(cephes.nctdtr(2., np.nan, 1.))) assert_(np.isnan(cephes.nctdtr(2., 1., np.nan))) def __check_nctdtridf(self): cephes.nctdtridf(1,0.5,0) def test_nctdtrinc(self): cephes.nctdtrinc(1,0,0) def test_nctdtrit(self): cephes.nctdtrit(.1,0.2,.5) def test_ndtr(self): assert_equal(cephes.ndtr(0), 0.5) assert_almost_equal(cephes.ndtr(1), 0.84134474606) def test_ndtri(self): assert_equal(cephes.ndtri(0.5),0.0) def test_nrdtrimn(self): assert_approx_equal(cephes.nrdtrimn(0.5,1,1),1.0) def test_nrdtrisd(self): assert_tol_equal(cephes.nrdtrisd(0.5,0.5,0.5), 0.0, atol=0, rtol=0) def test_obl_ang1(self): cephes.obl_ang1(1,1,1,0) def test_obl_ang1_cv(self): result = cephes.obl_ang1_cv(1,1,1,1,0) assert_almost_equal(result[0],1.0) assert_almost_equal(result[1],0.0) def _check_obl_cv(self): assert_equal(cephes.obl_cv(1,1,0),2.0) def test_obl_rad1(self): cephes.obl_rad1(1,1,1,0) def test_obl_rad1_cv(self): cephes.obl_rad1_cv(1,1,1,1,0) def test_obl_rad2(self): cephes.obl_rad2(1,1,1,0) def test_obl_rad2_cv(self): cephes.obl_rad2_cv(1,1,1,1,0) def test_pbdv(self): assert_equal(cephes.pbdv(1,0),(0.0,1.0)) def test_pbvv(self): cephes.pbvv(1,0) def test_pbwa(self): cephes.pbwa(1,0) def test_pdtr(self): val = cephes.pdtr(0, 1) assert_almost_equal(val, np.exp(-1)) # Edge case: m = 0. val = cephes.pdtr([0, 1, 2], 0.0) assert_array_equal(val, [1, 1, 1]) def test_pdtrc(self): val = cephes.pdtrc(0, 1) assert_almost_equal(val, 1 - np.exp(-1)) # Edge case: m = 0. val = cephes.pdtrc([0, 1, 2], 0.0) assert_array_equal(val, [0, 0, 0]) def test_pdtri(self): with warnings.catch_warnings(): warnings.simplefilter("ignore", RuntimeWarning) cephes.pdtri(0.5,0.5) def test_pdtrik(self): k = cephes.pdtrik(0.5, 1) assert_almost_equal(cephes.gammaincc(k + 1, 1), 0.5) # Edge case: m = 0 or very small. k = cephes.pdtrik([[0], [0.25], [0.95]], [0, 1e-20, 1e-6]) assert_array_equal(k, np.zeros((3, 3))) def test_pro_ang1(self): cephes.pro_ang1(1,1,1,0) def test_pro_ang1_cv(self): assert_array_almost_equal(cephes.pro_ang1_cv(1,1,1,1,0), array((1.0,0.0))) def _check_pro_cv(self): assert_equal(cephes.pro_cv(1,1,0),2.0) def test_pro_rad1(self): cephes.pro_rad1(1,1,1,0.1) def test_pro_rad1_cv(self): cephes.pro_rad1_cv(1,1,1,1,0) def test_pro_rad2(self): cephes.pro_rad2(1,1,1,0) def test_pro_rad2_cv(self): cephes.pro_rad2_cv(1,1,1,1,0) def test_psi(self): cephes.psi(1) def test_radian(self): assert_equal(cephes.radian(0,0,0),0) def test_rgamma(self): assert_equal(cephes.rgamma(1),1.0) def test_round(self): assert_equal(cephes.round(3.4),3.0) assert_equal(cephes.round(-3.4),-3.0) assert_equal(cephes.round(3.6),4.0) assert_equal(cephes.round(-3.6),-4.0) assert_equal(cephes.round(3.5),4.0) assert_equal(cephes.round(-3.5),-4.0) def test_shichi(self): cephes.shichi(1) def test_sici(self): cephes.sici(1) s, c = cephes.sici(np.inf) assert_almost_equal(s, np.pi * 0.5) assert_almost_equal(c, 0) s, c = cephes.sici(-np.inf) assert_almost_equal(s, -np.pi * 0.5) assert_(np.isnan(c), "cosine integral(-inf) is not nan") def test_sindg(self): assert_equal(cephes.sindg(90),1.0) def test_smirnov(self): assert_equal(cephes.smirnov(1,.1),0.9) assert_(np.isnan(cephes.smirnov(1,np.nan))) def test_smirnovi(self): assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.4)),0.4) assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.6)),0.6) assert_(np.isnan(cephes.smirnovi(1,np.nan))) def test_spence(self): assert_equal(cephes.spence(1),0.0) def test_stdtr(self): assert_equal(cephes.stdtr(1,0),0.5) assert_almost_equal(cephes.stdtr(1,1), 0.75) assert_almost_equal(cephes.stdtr(1,2), 0.852416382349) def test_stdtridf(self): cephes.stdtridf(0.7,1) def test_stdtrit(self): cephes.stdtrit(1,0.7) def test_struve(self): assert_equal(cephes.struve(0,0),0.0) def test_tandg(self): assert_equal(cephes.tandg(45),1.0) def test_tklmbda(self): assert_almost_equal(cephes.tklmbda(1,1),1.0) def test_y0(self): cephes.y0(1) def test_y1(self): cephes.y1(1) def test_yn(self): cephes.yn(1,1) def test_yv(self): cephes.yv(1,1) def _check_yve(self): cephes.yve(1,1) def test_zeta(self): cephes.zeta(2,2) def test_zetac(self): assert_equal(cephes.zetac(0),-1.5) def test_wofz(self): z = [complex(624.2,-0.26123), complex(-0.4,3.), complex(0.6,2.), complex(-1.,1.), complex(-1.,-9.), complex(-1.,9.), complex(-0.0000000234545,1.1234), complex(-3.,5.1), complex(-53,30.1), complex(0.0,0.12345), complex(11,1), complex(-22,-2), complex(9,-28), complex(21,-33), complex(1e5,1e5), complex(1e14,1e14) ] w = [ complex(-3.78270245518980507452677445620103199303131110e-7, 0.000903861276433172057331093754199933411710053155), complex(0.1764906227004816847297495349730234591778719532788, -0.02146550539468457616788719893991501311573031095617), complex(0.2410250715772692146133539023007113781272362309451, 0.06087579663428089745895459735240964093522265589350), complex(0.30474420525691259245713884106959496013413834051768, -0.20821893820283162728743734725471561394145872072738), complex(7.317131068972378096865595229600561710140617977e34, 8.321873499714402777186848353320412813066170427e34), complex(0.0615698507236323685519612934241429530190806818395, -0.00676005783716575013073036218018565206070072304635), complex(0.3960793007699874918961319170187598400134746631, -5.593152259116644920546186222529802777409274656e-9), complex(0.08217199226739447943295069917990417630675021771804, -0.04701291087643609891018366143118110965272615832184), complex(0.00457246000350281640952328010227885008541748668738, -0.00804900791411691821818731763401840373998654987934), complex(0.8746342859608052666092782112565360755791467973338452, 0.), complex(0.00468190164965444174367477874864366058339647648741, 0.0510735563901306197993676329845149741675029197050), complex(-0.0023193175200187620902125853834909543869428763219, -0.025460054739731556004902057663500272721780776336), complex(9.11463368405637174660562096516414499772662584e304, 3.97101807145263333769664875189354358563218932e305), complex(-4.4927207857715598976165541011143706155432296e281, -2.8019591213423077494444700357168707775769028e281), complex(2.820947917809305132678577516325951485807107151e-6, 2.820947917668257736791638444590253942253354058e-6), complex(2.82094791773878143474039725787438662716372268e-15, 2.82094791773878143474039725773333923127678361e-15) ] assert_func_equal(cephes.wofz, w, z, rtol=1e-13) class TestAiry(TestCase): def test_airy(self): # This tests the airy function to ensure 8 place accuracy in computation x = special.airy(.99) assert_array_almost_equal(x,array([0.13689066,-0.16050153,1.19815925,0.92046818]),8) x = special.airy(.41) assert_array_almost_equal(x,array([0.25238916,-.23480512,0.80686202,0.51053919]),8) x = special.airy(-.36) assert_array_almost_equal(x,array([0.44508477,-0.23186773,0.44939534,0.48105354]),8) def test_airye(self): a = special.airye(0.01) b = special.airy(0.01) b1 = [None]*4 for n in range(2): b1[n] = b[n]*exp(2.0/3.0*0.01*sqrt(0.01)) for n in range(2,4): b1[n] = b[n]*exp(-abs(real(2.0/3.0*0.01*sqrt(0.01)))) assert_array_almost_equal(a,b1,6) def test_bi_zeros(self): bi = special.bi_zeros(2) bia = (array([-1.17371322, -3.2710930]), array([-2.29443968, -4.07315509]), array([-0.45494438, 0.39652284]), array([0.60195789, -0.76031014])) assert_array_almost_equal(bi,bia,4) bi = special.bi_zeros(5) assert_array_almost_equal(bi[0],array([-1.173713222709127, -3.271093302836352, -4.830737841662016, -6.169852128310251, -7.376762079367764]),11) assert_array_almost_equal(bi[1],array([-2.294439682614122, -4.073155089071828, -5.512395729663599, -6.781294445990305, -7.940178689168587]),10) assert_array_almost_equal(bi[2],array([-0.454944383639657, 0.396522836094465, -0.367969161486959, 0.349499116831805, -0.336026240133662]),11) assert_array_almost_equal(bi[3],array([0.601957887976239, -0.760310141492801, 0.836991012619261, -0.88947990142654, 0.929983638568022]),10) def test_ai_zeros(self): ai = special.ai_zeros(1) assert_array_almost_equal(ai,(array([-2.33810741]), array([-1.01879297]), array([0.5357]), array([0.7012])),4) def test_ai_zeros_big(self): z, zp, ai_zpx, aip_zx = special.ai_zeros(50000) ai_z, aip_z, _, _ = special.airy(z) ai_zp, aip_zp, _, _ = special.airy(zp) ai_envelope = 1/abs(z)**(1./4) aip_envelope = abs(zp)**(1./4) # Check values assert_allclose(ai_zpx, ai_zp, rtol=1e-10) assert_allclose(aip_zx, aip_z, rtol=1e-10) # Check they are zeros assert_allclose(ai_z/ai_envelope, 0, atol=1e-10, rtol=0) assert_allclose(aip_zp/aip_envelope, 0, atol=1e-10, rtol=0) # Check first zeros, DLMF 9.9.1 assert_allclose(z[:6], [-2.3381074105, -4.0879494441, -5.5205598281, -6.7867080901, -7.9441335871, -9.0226508533], rtol=1e-10) assert_allclose(zp[:6], [-1.0187929716, -3.2481975822, -4.8200992112, -6.1633073556, -7.3721772550, -8.4884867340], rtol=1e-10) def test_bi_zeros_big(self): z, zp, bi_zpx, bip_zx = special.bi_zeros(50000) _, _, bi_z, bip_z = special.airy(z) _, _, bi_zp, bip_zp = special.airy(zp) bi_envelope = 1/abs(z)**(1./4) bip_envelope = abs(zp)**(1./4) # Check values assert_allclose(bi_zpx, bi_zp, rtol=1e-10) assert_allclose(bip_zx, bip_z, rtol=1e-10) # Check they are zeros assert_allclose(bi_z/bi_envelope, 0, atol=1e-10, rtol=0) assert_allclose(bip_zp/bip_envelope, 0, atol=1e-10, rtol=0) # Check first zeros, DLMF 9.9.2 assert_allclose(z[:6], [-1.1737132227, -3.2710933028, -4.8307378417, -6.1698521283, -7.3767620794, -8.4919488465], rtol=1e-10) assert_allclose(zp[:6], [-2.2944396826, -4.0731550891, -5.5123957297, -6.7812944460, -7.9401786892, -9.0195833588], rtol=1e-10) class TestAssocLaguerre(TestCase): def test_assoc_laguerre(self): a1 = special.genlaguerre(11,1) a2 = special.assoc_laguerre(.2,11,1) assert_array_almost_equal(a2,a1(.2),8) a2 = special.assoc_laguerre(1,11,1) assert_array_almost_equal(a2,a1(1),8) class TestBesselpoly(TestCase): def test_besselpoly(self): pass class TestKelvin(TestCase): def test_bei(self): mbei = special.bei(2) assert_almost_equal(mbei, 0.9722916273066613,5) # this may not be exact def test_beip(self): mbeip = special.beip(2) assert_almost_equal(mbeip,0.91701361338403631,5) # this may not be exact def test_ber(self): mber = special.ber(2) assert_almost_equal(mber,0.75173418271380821,5) # this may not be exact def test_berp(self): mberp = special.berp(2) assert_almost_equal(mberp,-0.49306712470943909,5) # this may not be exact def test_bei_zeros(self): # Abramowitz & Stegun, Table 9.12 bi = special.bei_zeros(5) assert_array_almost_equal(bi,array([5.02622, 9.45541, 13.89349, 18.33398, 22.77544]),4) def test_beip_zeros(self): bip = special.beip_zeros(5) assert_array_almost_equal(bip,array([3.772673304934953, 8.280987849760042, 12.742147523633703, 17.193431752512542, 21.641143941167325]),8) def test_ber_zeros(self): ber = special.ber_zeros(5) assert_array_almost_equal(ber,array([2.84892, 7.23883, 11.67396, 16.11356, 20.55463]),4) def test_berp_zeros(self): brp = special.berp_zeros(5) assert_array_almost_equal(brp,array([6.03871, 10.51364, 14.96844, 19.41758, 23.86430]),4) def test_kelvin(self): mkelv = special.kelvin(2) assert_array_almost_equal(mkelv,(special.ber(2) + special.bei(2)*1j, special.ker(2) + special.kei(2)*1j, special.berp(2) + special.beip(2)*1j, special.kerp(2) + special.keip(2)*1j),8) def test_kei(self): mkei = special.kei(2) assert_almost_equal(mkei,-0.20240006776470432,5) def test_keip(self): mkeip = special.keip(2) assert_almost_equal(mkeip,0.21980790991960536,5) def test_ker(self): mker = special.ker(2) assert_almost_equal(mker,-0.041664513991509472,5) def test_kerp(self): mkerp = special.kerp(2) assert_almost_equal(mkerp,-0.10660096588105264,5) def test_kei_zeros(self): kei = special.kei_zeros(5) assert_array_almost_equal(kei,array([3.91467, 8.34422, 12.78256, 17.22314, 21.66464]),4) def test_keip_zeros(self): keip = special.keip_zeros(5) assert_array_almost_equal(keip,array([4.93181, 9.40405, 13.85827, 18.30717, 22.75379]),4) # numbers come from 9.9 of A&S pg. 381 def test_kelvin_zeros(self): tmp = special.kelvin_zeros(5) berz,beiz,kerz,keiz,berpz,beipz,kerpz,keipz = tmp assert_array_almost_equal(berz,array([2.84892, 7.23883, 11.67396, 16.11356, 20.55463]),4) assert_array_almost_equal(beiz,array([5.02622, 9.45541, 13.89349, 18.33398, 22.77544]),4) assert_array_almost_equal(kerz,array([1.71854, 6.12728, 10.56294, 15.00269, 19.44382]),4) assert_array_almost_equal(keiz,array([3.91467, 8.34422, 12.78256, 17.22314, 21.66464]),4) assert_array_almost_equal(berpz,array([6.03871, 10.51364, 14.96844, 19.41758, 23.86430]),4) assert_array_almost_equal(beipz,array([3.77267, # table from 1927 had 3.77320 # but this is more accurate 8.28099, 12.74215, 17.19343, 21.64114]),4) assert_array_almost_equal(kerpz,array([2.66584, 7.17212, 11.63218, 16.08312, 20.53068]),4) assert_array_almost_equal(keipz,array([4.93181, 9.40405, 13.85827, 18.30717, 22.75379]),4) def test_ker_zeros(self): ker = special.ker_zeros(5) assert_array_almost_equal(ker,array([1.71854, 6.12728, 10.56294, 15.00269, 19.44381]),4) def test_kerp_zeros(self): kerp = special.kerp_zeros(5) assert_array_almost_equal(kerp,array([2.66584, 7.17212, 11.63218, 16.08312, 20.53068]),4) class TestBernoulli(TestCase): def test_bernoulli(self): brn = special.bernoulli(5) assert_array_almost_equal(brn,array([1.0000, -0.5000, 0.1667, 0.0000, -0.0333, 0.0000]),4) class TestBeta(TestCase): def test_beta(self): bet = special.beta(2,4) betg = (special.gamma(2)*special.gamma(4))/special.gamma(6) assert_almost_equal(bet,betg,8) def test_betaln(self): betln = special.betaln(2,4) bet = log(abs(special.beta(2,4))) assert_almost_equal(betln,bet,8) def test_betainc(self): btinc = special.betainc(1,1,.2) assert_almost_equal(btinc,0.2,8) def test_betaincinv(self): y = special.betaincinv(2,4,.5) comp = special.betainc(2,4,y) assert_almost_equal(comp,.5,5) class TestCombinatorics(TestCase): def test_comb(self): assert_array_almost_equal(special.comb([10, 10], [3, 4]), [120., 210.]) assert_almost_equal(special.comb(10, 3), 120.) assert_equal(special.comb(10, 3, exact=True), 120) assert_equal(special.comb(10, 3, exact=True, repetition=True), 220) def test_comb_with_np_int64(self): n = 70 k = 30 np_n = np.int64(n) np_k = np.int64(k) assert_equal(special.comb(np_n, np_k, exact=True), special.comb(n, k, exact=True)) def test_comb_zeros(self): assert_equal(special.comb(2, 3, exact=True), 0) assert_equal(special.comb(-1, 3, exact=True), 0) assert_equal(special.comb(2, -1, exact=True), 0) assert_equal(special.comb(2, -1, exact=False), 0) assert_array_almost_equal(special.comb([2, -1, 2, 10], [3, 3, -1, 3]), [0., 0., 0., 120.]) def test_perm(self): assert_array_almost_equal(special.perm([10, 10], [3, 4]), [720., 5040.]) assert_almost_equal(special.perm(10, 3), 720.) assert_equal(special.perm(10, 3, exact=True), 720) def test_perm_zeros(self): assert_equal(special.perm(2, 3, exact=True), 0) assert_equal(special.perm(-1, 3, exact=True), 0) assert_equal(special.perm(2, -1, exact=True), 0) assert_equal(special.perm(2, -1, exact=False), 0) assert_array_almost_equal(special.perm([2, -1, 2, 10], [3, 3, -1, 3]), [0., 0., 0., 720.]) class TestTrigonometric(TestCase): def test_cbrt(self): cb = special.cbrt(27) cbrl = 27**(1.0/3.0) assert_approx_equal(cb,cbrl) def test_cbrtmore(self): cb1 = special.cbrt(27.9) cbrl1 = 27.9**(1.0/3.0) assert_almost_equal(cb1,cbrl1,8) def test_cosdg(self): cdg = special.cosdg(90) cdgrl = cos(pi/2.0) assert_almost_equal(cdg,cdgrl,8) def test_cosdgmore(self): cdgm = special.cosdg(30) cdgmrl = cos(pi/6.0) assert_almost_equal(cdgm,cdgmrl,8) def test_cosm1(self): cs = (special.cosm1(0),special.cosm1(.3),special.cosm1(pi/10)) csrl = (cos(0)-1,cos(.3)-1,cos(pi/10)-1) assert_array_almost_equal(cs,csrl,8) def test_cotdg(self): ct = special.cotdg(30) ctrl = tan(pi/6.0)**(-1) assert_almost_equal(ct,ctrl,8) def test_cotdgmore(self): ct1 = special.cotdg(45) ctrl1 = tan(pi/4.0)**(-1) assert_almost_equal(ct1,ctrl1,8) def test_specialpoints(self): assert_almost_equal(special.cotdg(45), 1.0, 14) assert_almost_equal(special.cotdg(-45), -1.0, 14) assert_almost_equal(special.cotdg(90), 0.0, 14) assert_almost_equal(special.cotdg(-90), 0.0, 14) assert_almost_equal(special.cotdg(135), -1.0, 14) assert_almost_equal(special.cotdg(-135), 1.0, 14) assert_almost_equal(special.cotdg(225), 1.0, 14) assert_almost_equal(special.cotdg(-225), -1.0, 14) assert_almost_equal(special.cotdg(270), 0.0, 14) assert_almost_equal(special.cotdg(-270), 0.0, 14) assert_almost_equal(special.cotdg(315), -1.0, 14) assert_almost_equal(special.cotdg(-315), 1.0, 14) assert_almost_equal(special.cotdg(765), 1.0, 14) def test_sinc(self): # the sinc implementation and more extensive sinc tests are in numpy assert_array_equal(special.sinc([0]), 1) assert_equal(special.sinc(0.0), 1.0) def test_sindg(self): sn = special.sindg(90) assert_equal(sn,1.0) def test_sindgmore(self): snm = special.sindg(30) snmrl = sin(pi/6.0) assert_almost_equal(snm,snmrl,8) snm1 = special.sindg(45) snmrl1 = sin(pi/4.0) assert_almost_equal(snm1,snmrl1,8) class TestTandg(TestCase): def test_tandg(self): tn = special.tandg(30) tnrl = tan(pi/6.0) assert_almost_equal(tn,tnrl,8) def test_tandgmore(self): tnm = special.tandg(45) tnmrl = tan(pi/4.0) assert_almost_equal(tnm,tnmrl,8) tnm1 = special.tandg(60) tnmrl1 = tan(pi/3.0) assert_almost_equal(tnm1,tnmrl1,8) def test_specialpoints(self): assert_almost_equal(special.tandg(0), 0.0, 14) assert_almost_equal(special.tandg(45), 1.0, 14) assert_almost_equal(special.tandg(-45), -1.0, 14) assert_almost_equal(special.tandg(135), -1.0, 14) assert_almost_equal(special.tandg(-135), 1.0, 14) assert_almost_equal(special.tandg(180), 0.0, 14) assert_almost_equal(special.tandg(-180), 0.0, 14) assert_almost_equal(special.tandg(225), 1.0, 14) assert_almost_equal(special.tandg(-225), -1.0, 14) assert_almost_equal(special.tandg(315), -1.0, 14) assert_almost_equal(special.tandg(-315), 1.0, 14) class TestEllip(TestCase): def test_ellipj_nan(self): """Regression test for #912.""" special.ellipj(0.5, np.nan) def test_ellipj(self): el = special.ellipj(0.2,0) rel = [sin(0.2),cos(0.2),1.0,0.20] assert_array_almost_equal(el,rel,13) def test_ellipk(self): elk = special.ellipk(.2) assert_almost_equal(elk,1.659623598610528,11) assert_equal(special.ellipkm1(0.0), np.inf) assert_equal(special.ellipkm1(1.0), pi/2) assert_equal(special.ellipkm1(np.inf), 0.0) assert_equal(special.ellipkm1(np.nan), np.nan) assert_equal(special.ellipkm1(-1), np.nan) assert_allclose(special.ellipk(-10), 0.7908718902387385) def test_ellipkinc(self): elkinc = special.ellipkinc(pi/2,.2) elk = special.ellipk(0.2) assert_almost_equal(elkinc,elk,15) alpha = 20*pi/180 phi = 45*pi/180 m = sin(alpha)**2 elkinc = special.ellipkinc(phi,m) assert_almost_equal(elkinc,0.79398143,8) # From pg. 614 of A & S assert_equal(special.ellipkinc(pi/2, 0.0), pi/2) assert_equal(special.ellipkinc(pi/2, 1.0), np.inf) assert_equal(special.ellipkinc(pi/2, -np.inf), 0.0) assert_equal(special.ellipkinc(pi/2, np.nan), np.nan) assert_equal(special.ellipkinc(pi/2, 2), np.nan) assert_equal(special.ellipkinc(0, 0.5), 0.0) assert_equal(special.ellipkinc(np.inf, 0.5), np.inf) assert_equal(special.ellipkinc(-np.inf, 0.5), -np.inf) assert_equal(special.ellipkinc(np.inf, np.inf), np.nan) assert_equal(special.ellipkinc(np.inf, -np.inf), np.nan) assert_equal(special.ellipkinc(-np.inf, -np.inf), np.nan) assert_equal(special.ellipkinc(-np.inf, np.inf), np.nan) assert_equal(special.ellipkinc(np.nan, 0.5), np.nan) assert_equal(special.ellipkinc(np.nan, np.nan), np.nan) assert_allclose(special.ellipkinc(0.38974112035318718, 1), 0.4, rtol=1e-14) assert_allclose(special.ellipkinc(1.5707, -10), 0.79084284661724946) def test_ellipkinc_2(self): # Regression test for gh-3550 # ellipkinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value mbad = 0.68359375000000011 phi = 0.9272952180016123 m = np.nextafter(mbad, 0) mvals = [] for j in range(10): mvals.append(m) m = np.nextafter(m, 1) f = special.ellipkinc(phi, mvals) assert_array_almost_equal_nulp(f, 1.0259330100195334 * np.ones_like(f), 1) # this bug also appears at phi + n * pi for at least small n f1 = special.ellipkinc(phi + pi, mvals) assert_array_almost_equal_nulp(f1, 5.1296650500976675 * np.ones_like(f1), 2) def test_ellipkinc_singular(self): # ellipkinc(phi, 1) has closed form and is finite only for phi in (-pi/2, pi/2) xlog = np.logspace(-300, -17, 25) xlin = np.linspace(1e-17, 0.1, 25) xlin2 = np.linspace(0.1, pi/2, 25, endpoint=False) assert_allclose(special.ellipkinc(xlog, 1), np.arcsinh(np.tan(xlog)), rtol=1e14) assert_allclose(special.ellipkinc(xlin, 1), np.arcsinh(np.tan(xlin)), rtol=1e14) assert_allclose(special.ellipkinc(xlin2, 1), np.arcsinh(np.tan(xlin2)), rtol=1e14) assert_equal(special.ellipkinc(np.pi/2, 1), np.inf) assert_allclose(special.ellipkinc(-xlog, 1), np.arcsinh(np.tan(-xlog)), rtol=1e14) assert_allclose(special.ellipkinc(-xlin, 1), np.arcsinh(np.tan(-xlin)), rtol=1e14) assert_allclose(special.ellipkinc(-xlin2, 1), np.arcsinh(np.tan(-xlin2)), rtol=1e14) assert_equal(special.ellipkinc(-np.pi/2, 1), np.inf) def test_ellipe(self): ele = special.ellipe(.2) assert_almost_equal(ele,1.4890350580958529,8) assert_equal(special.ellipe(0.0), pi/2) assert_equal(special.ellipe(1.0), 1.0) assert_equal(special.ellipe(-np.inf), np.inf) assert_equal(special.ellipe(np.nan), np.nan) assert_equal(special.ellipe(2), np.nan) assert_allclose(special.ellipe(-10), 3.6391380384177689) def test_ellipeinc(self): eleinc = special.ellipeinc(pi/2,.2) ele = special.ellipe(0.2) assert_almost_equal(eleinc,ele,14) # pg 617 of A & S alpha, phi = 52*pi/180,35*pi/180 m = sin(alpha)**2 eleinc = special.ellipeinc(phi,m) assert_almost_equal(eleinc, 0.58823065, 8) assert_equal(special.ellipeinc(pi/2, 0.0), pi/2) assert_equal(special.ellipeinc(pi/2, 1.0), 1.0) assert_equal(special.ellipeinc(pi/2, -np.inf), np.inf) assert_equal(special.ellipeinc(pi/2, np.nan), np.nan) assert_equal(special.ellipeinc(pi/2, 2), np.nan) assert_equal(special.ellipeinc(0, 0.5), 0.0) assert_equal(special.ellipeinc(np.inf, 0.5), np.inf) assert_equal(special.ellipeinc(-np.inf, 0.5), -np.inf) assert_equal(special.ellipeinc(np.inf, -np.inf), np.inf) assert_equal(special.ellipeinc(-np.inf, -np.inf), -np.inf) assert_equal(special.ellipeinc(np.inf, np.inf), np.nan) assert_equal(special.ellipeinc(-np.inf, np.inf), np.nan) assert_equal(special.ellipeinc(np.nan, 0.5), np.nan) assert_equal(special.ellipeinc(np.nan, np.nan), np.nan) assert_allclose(special.ellipeinc(1.5707, -10), 3.6388185585822876) def test_ellipeinc_2(self): # Regression test for gh-3550 # ellipeinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value mbad = 0.68359375000000011 phi = 0.9272952180016123 m = np.nextafter(mbad, 0) mvals = [] for j in range(10): mvals.append(m) m = np.nextafter(m, 1) f = special.ellipeinc(phi, mvals) assert_array_almost_equal_nulp(f, 0.84442884574781019 * np.ones_like(f), 2) # this bug also appears at phi + n * pi for at least small n f1 = special.ellipeinc(phi + pi, mvals) assert_array_almost_equal_nulp(f1, 3.3471442287390509 * np.ones_like(f1), 4) class TestErf(TestCase): def test_erf(self): er = special.erf(.25) assert_almost_equal(er,0.2763263902,8) def test_erf_zeros(self): erz = special.erf_zeros(5) erzr = array([1.45061616+1.88094300j, 2.24465928+2.61657514j, 2.83974105+3.17562810j, 3.33546074+3.64617438j, 3.76900557+4.06069723j]) assert_array_almost_equal(erz,erzr,4) def _check_variant_func(self, func, other_func, rtol, atol=0): np.random.seed(1234) n = 10000 x = np.random.pareto(0.02, n) * (2*np.random.randint(0, 2, n) - 1) y = np.random.pareto(0.02, n) * (2*np.random.randint(0, 2, n) - 1) z = x + 1j*y old_errors = np.seterr(all='ignore') try: w = other_func(z) w_real = other_func(x).real mask = np.isfinite(w) w = w[mask] z = z[mask] mask = np.isfinite(w_real) w_real = w_real[mask] x = x[mask] # test both real and complex variants assert_func_equal(func, w, z, rtol=rtol, atol=atol) assert_func_equal(func, w_real, x, rtol=rtol, atol=atol) finally: np.seterr(**old_errors) def test_erfc_consistent(self): self._check_variant_func( cephes.erfc, lambda z: 1 - cephes.erf(z), rtol=1e-12, atol=1e-14 # <- the test function loses precision ) def test_erfcx_consistent(self): self._check_variant_func( cephes.erfcx, lambda z: np.exp(z*z) * cephes.erfc(z), rtol=1e-12 ) def test_erfi_consistent(self): self._check_variant_func( cephes.erfi, lambda z: -1j * cephes.erf(1j*z), rtol=1e-12 ) def test_dawsn_consistent(self): self._check_variant_func( cephes.dawsn, lambda z: sqrt(pi)/2 * np.exp(-z*z) * cephes.erfi(z), rtol=1e-12 ) def test_erfcinv(self): i = special.erfcinv(1) # Use assert_array_equal instead of assert_equal, so the comparsion # of -0.0 and 0.0 doesn't fail. assert_array_equal(i, 0) def test_erfinv(self): i = special.erfinv(0) assert_equal(i,0) def test_errprint(self): a = special.errprint() b = 1-a # a is the state 1-a inverts state c = special.errprint(b) # returns last state 'a' assert_equal(a,c) d = special.errprint(a) # returns to original state assert_equal(d,b) # makes sure state was returned # assert_equal(d,1-a) class TestEuler(TestCase): def test_euler(self): eu0 = special.euler(0) eu1 = special.euler(1) eu2 = special.euler(2) # just checking segfaults assert_almost_equal(eu0[0],1,8) assert_almost_equal(eu2[2],-1,8) eu24 = special.euler(24) mathworld = [1,1,5,61,1385,50521,2702765,199360981, 19391512145,2404879675441, 370371188237525,69348874393137901, 15514534163557086905] correct = zeros((25,),'d') for k in range(0,13): if (k % 2): correct[2*k] = -float(mathworld[k]) else: correct[2*k] = float(mathworld[k]) olderr = np.seterr(all='ignore') try: err = nan_to_num((eu24-correct)/correct) errmax = max(err) finally: np.seterr(**olderr) assert_almost_equal(errmax, 0.0, 14) class TestExp(TestCase): def test_exp2(self): ex = special.exp2(2) exrl = 2**2 assert_equal(ex,exrl) def test_exp2more(self): exm = special.exp2(2.5) exmrl = 2**(2.5) assert_almost_equal(exm,exmrl,8) def test_exp10(self): ex = special.exp10(2) exrl = 10**2 assert_approx_equal(ex,exrl) def test_exp10more(self): exm = special.exp10(2.5) exmrl = 10**(2.5) assert_almost_equal(exm,exmrl,8) def test_expm1(self): ex = (special.expm1(2),special.expm1(3),special.expm1(4)) exrl = (exp(2)-1,exp(3)-1,exp(4)-1) assert_array_almost_equal(ex,exrl,8) def test_expm1more(self): ex1 = (special.expm1(2),special.expm1(2.1),special.expm1(2.2)) exrl1 = (exp(2)-1,exp(2.1)-1,exp(2.2)-1) assert_array_almost_equal(ex1,exrl1,8) class TestFactorialFunctions(TestCase): def test_factorial(self): assert_array_almost_equal([6., 24., 120.], special.factorial([3, 4, 5], exact=False)) assert_equal(special.factorial(5, exact=True), 120) def test_factorial2(self): assert_array_almost_equal([105., 384., 945.], special.factorial2([7, 8, 9], exact=False)) assert_equal(special.factorial2(7, exact=True), 105) def test_factorialk(self): assert_equal(special.factorialk(5, 1, exact=True), 120) assert_equal(special.factorialk(5, 3, exact=True), 10) class TestFresnel(TestCase): def test_fresnel(self): frs = array(special.fresnel(.5)) assert_array_almost_equal(frs,array([0.064732432859999287, 0.49234422587144644]),8) # values from pg 329 Table 7.11 of A & S # slightly corrected in 4th decimal place def test_fresnel_zeros(self): szo, czo = special.fresnel_zeros(5) assert_array_almost_equal(szo, array([2.0093+0.2885j, 2.8335+0.2443j, 3.4675+0.2185j, 4.0026+0.2009j, 4.4742+0.1877j]),3) assert_array_almost_equal(czo, array([1.7437+0.3057j, 2.6515+0.2529j, 3.3204+0.2240j, 3.8757+0.2047j, 4.3611+0.1907j]),3) vals1 = special.fresnel(szo)[0] vals2 = special.fresnel(czo)[1] assert_array_almost_equal(vals1,0,14) assert_array_almost_equal(vals2,0,14) def test_fresnelc_zeros(self): szo, czo = special.fresnel_zeros(6) frc = special.fresnelc_zeros(6) assert_array_almost_equal(frc,czo,12) def test_fresnels_zeros(self): szo, czo = special.fresnel_zeros(5) frs = special.fresnels_zeros(5) assert_array_almost_equal(frs,szo,12) class TestGamma(TestCase): def test_gamma(self): gam = special.gamma(5) assert_equal(gam,24.0) def test_gammaln(self): gamln = special.gammaln(3) lngam = log(special.gamma(3)) assert_almost_equal(gamln,lngam,8) def test_gammainc(self): gama = special.gammainc(.5,.5) assert_almost_equal(gama,.7,1) def test_gammaincnan(self): gama = special.gammainc(-1,1) assert_(isnan(gama)) def test_gammainczero(self): # bad arg but zero integration limit gama = special.gammainc(-1,0) assert_equal(gama,0.0) def test_gammaincc(self): gicc = special.gammaincc(.5,.5) greal = 1 - special.gammainc(.5,.5) assert_almost_equal(gicc,greal,8) def test_gammainccnan(self): gama = special.gammaincc(-1,1) assert_(isnan(gama)) def test_gammainccinv(self): gccinv = special.gammainccinv(.5,.5) gcinv = special.gammaincinv(.5,.5) assert_almost_equal(gccinv,gcinv,8) @with_special_errors def test_gammaincinv(self): y = special.gammaincinv(.4,.4) x = special.gammainc(.4,y) assert_almost_equal(x,0.4,1) y = special.gammainc(10, 0.05) x = special.gammaincinv(10, 2.5715803516000736e-20) assert_almost_equal(0.05, x, decimal=10) assert_almost_equal(y, 2.5715803516000736e-20, decimal=10) x = special.gammaincinv(50, 8.20754777388471303050299243573393e-18) assert_almost_equal(11.0, x, decimal=10) @with_special_errors def test_975(self): # Regression test for ticket #975 -- switch point in algorithm # check that things work OK at the point, immediately next floats # around it, and a bit further away pts = [0.25, np.nextafter(0.25, 0), 0.25 - 1e-12, np.nextafter(0.25, 1), 0.25 + 1e-12] for xp in pts: y = special.gammaincinv(.4, xp) x = special.gammainc(0.4, y) assert_tol_equal(x, xp, rtol=1e-12) def test_rgamma(self): rgam = special.rgamma(8) rlgam = 1/special.gamma(8) assert_almost_equal(rgam,rlgam,8) def test_infinity(self): assert_(np.isinf(special.gamma(-1))) assert_equal(special.rgamma(-1), 0) class TestHankel(TestCase): def test_negv1(self): assert_almost_equal(special.hankel1(-3,2), -special.hankel1(3,2), 14) def test_hankel1(self): hank1 = special.hankel1(1,.1) hankrl = (special.jv(1,.1) + special.yv(1,.1)*1j) assert_almost_equal(hank1,hankrl,8) def test_negv1e(self): assert_almost_equal(special.hankel1e(-3,2), -special.hankel1e(3,2), 14) def test_hankel1e(self): hank1e = special.hankel1e(1,.1) hankrle = special.hankel1(1,.1)*exp(-.1j) assert_almost_equal(hank1e,hankrle,8) def test_negv2(self): assert_almost_equal(special.hankel2(-3,2), -special.hankel2(3,2), 14) def test_hankel2(self): hank2 = special.hankel2(1,.1) hankrl2 = (special.jv(1,.1) - special.yv(1,.1)*1j) assert_almost_equal(hank2,hankrl2,8) def test_neg2e(self): assert_almost_equal(special.hankel2e(-3,2), -special.hankel2e(3,2), 14) def test_hankl2e(self): hank2e = special.hankel2e(1,.1) hankrl2e = special.hankel2e(1,.1) assert_almost_equal(hank2e,hankrl2e,8) class TestHyper(TestCase): def test_h1vp(self): h1 = special.h1vp(1,.1) h1real = (special.jvp(1,.1) + special.yvp(1,.1)*1j) assert_almost_equal(h1,h1real,8) def test_h2vp(self): h2 = special.h2vp(1,.1) h2real = (special.jvp(1,.1) - special.yvp(1,.1)*1j) assert_almost_equal(h2,h2real,8) def test_hyp0f1(self): # scalar input assert_allclose(special.hyp0f1(2.5, 0.5), 1.21482702689997, rtol=1e-12) assert_allclose(special.hyp0f1(2.5, 0), 1.0, rtol=1e-15) # float input, expected values match mpmath x = special.hyp0f1(3.0, [-1.5, -1, 0, 1, 1.5]) expected = np.array([0.58493659229143, 0.70566805723127, 1.0, 1.37789689539747, 1.60373685288480]) assert_allclose(x, expected, rtol=1e-12) # complex input x = special.hyp0f1(3.0, np.array([-1.5, -1, 0, 1, 1.5]) + 0.j) assert_allclose(x, expected.astype(complex), rtol=1e-12) # test broadcasting x1 = [0.5, 1.5, 2.5] x2 = [0, 1, 0.5] x = special.hyp0f1(x1, x2) expected = [1.0, 1.8134302039235093, 1.21482702689997] assert_allclose(x, expected, rtol=1e-12) x = special.hyp0f1(np.row_stack([x1] * 2), x2) assert_allclose(x, np.row_stack([expected] * 2), rtol=1e-12) assert_raises(ValueError, special.hyp0f1, np.row_stack([x1] * 3), [0, 1]) def test_hyp1f1(self): hyp1 = special.hyp1f1(.1,.1,.3) assert_almost_equal(hyp1, 1.3498588075760032,7) # test contributed by Moritz Deger (2008-05-29) # http://projects.scipy.org/scipy/scipy/ticket/659 # reference data obtained from mathematica [ a, b, x, m(a,b,x)]: # produced with test_hyp1f1.nb ref_data = array([[-8.38132975e+00, -1.28436461e+01, -2.91081397e+01, 1.04178330e+04], [2.91076882e+00, -6.35234333e+00, -1.27083993e+01, 6.68132725e+00], [-1.42938258e+01, 1.80869131e-01, 1.90038728e+01, 1.01385897e+05], [5.84069088e+00, 1.33187908e+01, 2.91290106e+01, 1.59469411e+08], [-2.70433202e+01, -1.16274873e+01, -2.89582384e+01, 1.39900152e+24], [4.26344966e+00, -2.32701773e+01, 1.91635759e+01, 6.13816915e+21], [1.20514340e+01, -3.40260240e+00, 7.26832235e+00, 1.17696112e+13], [2.77372955e+01, -1.99424687e+00, 3.61332246e+00, 3.07419615e+13], [1.50310939e+01, -2.91198675e+01, -1.53581080e+01, -3.79166033e+02], [1.43995827e+01, 9.84311196e+00, 1.93204553e+01, 2.55836264e+10], [-4.08759686e+00, 1.34437025e+01, -1.42072843e+01, 1.70778449e+01], [8.05595738e+00, -1.31019838e+01, 1.52180721e+01, 3.06233294e+21], [1.81815804e+01, -1.42908793e+01, 9.57868793e+00, -2.84771348e+20], [-2.49671396e+01, 1.25082843e+01, -1.71562286e+01, 2.36290426e+07], [2.67277673e+01, 1.70315414e+01, 6.12701450e+00, 7.77917232e+03], [2.49565476e+01, 2.91694684e+01, 6.29622660e+00, 2.35300027e+02], [6.11924542e+00, -1.59943768e+00, 9.57009289e+00, 1.32906326e+11], [-1.47863653e+01, 2.41691301e+01, -1.89981821e+01, 2.73064953e+03], [2.24070483e+01, -2.93647433e+00, 8.19281432e+00, -6.42000372e+17], [8.04042600e-01, 1.82710085e+01, -1.97814534e+01, 5.48372441e-01], [1.39590390e+01, 1.97318686e+01, 2.37606635e+00, 5.51923681e+00], [-4.66640483e+00, -2.00237930e+01, 7.40365095e+00, 4.50310752e+00], [2.76821999e+01, -6.36563968e+00, 1.11533984e+01, -9.28725179e+23], [-2.56764457e+01, 1.24544906e+00, 1.06407572e+01, 1.25922076e+01], [3.20447808e+00, 1.30874383e+01, 2.26098014e+01, 2.03202059e+04], [-1.24809647e+01, 4.15137113e+00, -2.92265700e+01, 2.39621411e+08], [2.14778108e+01, -2.35162960e+00, -1.13758664e+01, 4.46882152e-01], [-9.85469168e+00, -3.28157680e+00, 1.67447548e+01, -1.07342390e+07], [1.08122310e+01, -2.47353236e+01, -1.15622349e+01, -2.91733796e+03], [-2.67933347e+01, -3.39100709e+00, 2.56006986e+01, -5.29275382e+09], [-8.60066776e+00, -8.02200924e+00, 1.07231926e+01, 1.33548320e+06], [-1.01724238e-01, -1.18479709e+01, -2.55407104e+01, 1.55436570e+00], [-3.93356771e+00, 2.11106818e+01, -2.57598485e+01, 2.13467840e+01], [3.74750503e+00, 1.55687633e+01, -2.92841720e+01, 1.43873509e-02], [6.99726781e+00, 2.69855571e+01, -1.63707771e+01, 3.08098673e-02], [-2.31996011e+01, 3.47631054e+00, 9.75119815e-01, 1.79971073e-02], [2.38951044e+01, -2.91460190e+01, -2.50774708e+00, 9.56934814e+00], [1.52730825e+01, 5.77062507e+00, 1.21922003e+01, 1.32345307e+09], [1.74673917e+01, 1.89723426e+01, 4.94903250e+00, 9.90859484e+01], [1.88971241e+01, 2.86255413e+01, 5.52360109e-01, 1.44165360e+00], [1.02002319e+01, -1.66855152e+01, -2.55426235e+01, 6.56481554e+02], [-1.79474153e+01, 1.22210200e+01, -1.84058212e+01, 8.24041812e+05], [-1.36147103e+01, 1.32365492e+00, -7.22375200e+00, 9.92446491e+05], [7.57407832e+00, 2.59738234e+01, -1.34139168e+01, 3.64037761e-02], [2.21110169e+00, 1.28012666e+01, 1.62529102e+01, 1.33433085e+02], [-2.64297569e+01, -1.63176658e+01, -1.11642006e+01, -2.44797251e+13], [-2.46622944e+01, -3.02147372e+00, 8.29159315e+00, -3.21799070e+05], [-1.37215095e+01, -1.96680183e+01, 2.91940118e+01, 3.21457520e+12], [-5.45566105e+00, 2.81292086e+01, 1.72548215e-01, 9.66973000e-01], [-1.55751298e+00, -8.65703373e+00, 2.68622026e+01, -3.17190834e+16], [2.45393609e+01, -2.70571903e+01, 1.96815505e+01, 1.80708004e+37], [5.77482829e+00, 1.53203143e+01, 2.50534322e+01, 1.14304242e+06], [-1.02626819e+01, 2.36887658e+01, -2.32152102e+01, 7.28965646e+02], [-1.30833446e+00, -1.28310210e+01, 1.87275544e+01, -9.33487904e+12], [5.83024676e+00, -1.49279672e+01, 2.44957538e+01, -7.61083070e+27], [-2.03130747e+01, 2.59641715e+01, -2.06174328e+01, 4.54744859e+04], [1.97684551e+01, -2.21410519e+01, -2.26728740e+01, 3.53113026e+06], [2.73673444e+01, 2.64491725e+01, 1.57599882e+01, 1.07385118e+07], [5.73287971e+00, 1.21111904e+01, 1.33080171e+01, 2.63220467e+03], [-2.82751072e+01, 2.08605881e+01, 9.09838900e+00, -6.60957033e-07], [1.87270691e+01, -1.74437016e+01, 1.52413599e+01, 6.59572851e+27], [6.60681457e+00, -2.69449855e+00, 9.78972047e+00, -2.38587870e+12], [1.20895561e+01, -2.51355765e+01, 2.30096101e+01, 7.58739886e+32], [-2.44682278e+01, 2.10673441e+01, -1.36705538e+01, 4.54213550e+04], [-4.50665152e+00, 3.72292059e+00, -4.83403707e+00, 2.68938214e+01], [-7.46540049e+00, -1.08422222e+01, -1.72203805e+01, -2.09402162e+02], [-2.00307551e+01, -7.50604431e+00, -2.78640020e+01, 4.15985444e+19], [1.99890876e+01, 2.20677419e+01, -2.51301778e+01, 1.23840297e-09], [2.03183823e+01, -7.66942559e+00, 2.10340070e+01, 1.46285095e+31], [-2.90315825e+00, -2.55785967e+01, -9.58779316e+00, 2.65714264e-01], [2.73960829e+01, -1.80097203e+01, -2.03070131e+00, 2.52908999e+02], [-2.11708058e+01, -2.70304032e+01, 2.48257944e+01, 3.09027527e+08], [2.21959758e+01, 4.00258675e+00, -1.62853977e+01, -9.16280090e-09], [1.61661840e+01, -2.26845150e+01, 2.17226940e+01, -8.24774394e+33], [-3.35030306e+00, 1.32670581e+00, 9.39711214e+00, -1.47303163e+01], [7.23720726e+00, -2.29763909e+01, 2.34709682e+01, -9.20711735e+29], [2.71013568e+01, 1.61951087e+01, -7.11388906e-01, 2.98750911e-01], [8.40057933e+00, -7.49665220e+00, 2.95587388e+01, 6.59465635e+29], [-1.51603423e+01, 1.94032322e+01, -7.60044357e+00, 1.05186941e+02], [-8.83788031e+00, -2.72018313e+01, 1.88269907e+00, 1.81687019e+00], [-1.87283712e+01, 5.87479570e+00, -1.91210203e+01, 2.52235612e+08], [-5.61338513e-01, 2.69490237e+01, 1.16660111e-01, 9.97567783e-01], [-5.44354025e+00, -1.26721408e+01, -4.66831036e+00, 1.06660735e-01], [-2.18846497e+00, 2.33299566e+01, 9.62564397e+00, 3.03842061e-01], [6.65661299e+00, -2.39048713e+01, 1.04191807e+01, 4.73700451e+13], [-2.57298921e+01, -2.60811296e+01, 2.74398110e+01, -5.32566307e+11], [-1.11431826e+01, -1.59420160e+01, -1.84880553e+01, -1.01514747e+02], [6.50301931e+00, 2.59859051e+01, -2.33270137e+01, 1.22760500e-02], [-1.94987891e+01, -2.62123262e+01, 3.90323225e+00, 1.71658894e+01], [7.26164601e+00, -1.41469402e+01, 2.81499763e+01, -2.50068329e+31], [-1.52424040e+01, 2.99719005e+01, -2.85753678e+01, 1.31906693e+04], [5.24149291e+00, -1.72807223e+01, 2.22129493e+01, 2.50748475e+25], [3.63207230e-01, -9.54120862e-02, -2.83874044e+01, 9.43854939e-01], [-2.11326457e+00, -1.25707023e+01, 1.17172130e+00, 1.20812698e+00], [2.48513582e+00, 1.03652647e+01, -1.84625148e+01, 6.47910997e-02], [2.65395942e+01, 2.74794672e+01, 1.29413428e+01, 2.89306132e+05], [-9.49445460e+00, 1.59930921e+01, -1.49596331e+01, 3.27574841e+02], [-5.89173945e+00, 9.96742426e+00, 2.60318889e+01, -3.15842908e-01], [-1.15387239e+01, -2.21433107e+01, -2.17686413e+01, 1.56724718e-01], [-5.30592244e+00, -2.42752190e+01, 1.29734035e+00, 1.31985534e+00]]) for a,b,c,expected in ref_data: result = special.hyp1f1(a,b,c) assert_(abs(expected - result)/expected < 1e-4) def test_hyp1f1_gh2957(self): hyp1 = special.hyp1f1(0.5, 1.5, -709.7827128933) hyp2 = special.hyp1f1(0.5, 1.5, -709.7827128934) assert_almost_equal(hyp1, hyp2, 12) def test_hyp1f1_gh2282(self): hyp = special.hyp1f1(0.5, 1.5, -1000) assert_almost_equal(hyp, 0.028024956081989643, 12) def test_hyp1f2(self): pass def test_hyp2f0(self): pass def test_hyp2f1(self): # a collection of special cases taken from AMS 55 values = [[0.5, 1, 1.5, 0.2**2, 0.5/0.2*log((1+0.2)/(1-0.2))], [0.5, 1, 1.5, -0.2**2, 1./0.2*arctan(0.2)], [1, 1, 2, 0.2, -1/0.2*log(1-0.2)], [3, 3.5, 1.5, 0.2**2, 0.5/0.2/(-5)*((1+0.2)**(-5)-(1-0.2)**(-5))], [-3, 3, 0.5, sin(0.2)**2, cos(2*3*0.2)], [3, 4, 8, 1, special.gamma(8)*special.gamma(8-4-3)/special.gamma(8-3)/special.gamma(8-4)], [3, 2, 3-2+1, -1, 1./2**3*sqrt(pi) * special.gamma(1+3-2)/special.gamma(1+0.5*3-2)/special.gamma(0.5+0.5*3)], [5, 2, 5-2+1, -1, 1./2**5*sqrt(pi) * special.gamma(1+5-2)/special.gamma(1+0.5*5-2)/special.gamma(0.5+0.5*5)], [4, 0.5+4, 1.5-2*4, -1./3, (8./9)**(-2*4)*special.gamma(4./3) * special.gamma(1.5-2*4)/special.gamma(3./2)/special.gamma(4./3-2*4)], # and some others # ticket #424 [1.5, -0.5, 1.0, -10.0, 4.1300097765277476484], # negative integer a or b, with c-a-b integer and x > 0.9 [-2,3,1,0.95,0.715], [2,-3,1,0.95,-0.007], [-6,3,1,0.95,0.0000810625], [2,-5,1,0.95,-0.000029375], # huge negative integers (10, -900, 10.5, 0.99, 1.91853705796607664803709475658e-24), (10, -900, -10.5, 0.99, 3.54279200040355710199058559155e-18), ] for i, (a, b, c, x, v) in enumerate(values): cv = special.hyp2f1(a, b, c, x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_hyp3f0(self): pass def test_hyperu(self): val1 = special.hyperu(1,0.1,100) assert_almost_equal(val1,0.0098153,7) a,b = [0.3,0.6,1.2,-2.7],[1.5,3.2,-0.4,-3.2] a,b = asarray(a), asarray(b) z = 0.5 hypu = special.hyperu(a,b,z) hprl = (pi/sin(pi*b))*(special.hyp1f1(a,b,z) / (special.gamma(1+a-b)*special.gamma(b)) - z**(1-b)*special.hyp1f1(1+a-b,2-b,z) / (special.gamma(a)*special.gamma(2-b))) assert_array_almost_equal(hypu,hprl,12) def test_hyperu_gh2287(self): assert_almost_equal(special.hyperu(1, 1.5, 20.2), 0.048360918656699191, 12) class TestBessel(TestCase): def test_itj0y0(self): it0 = array(special.itj0y0(.2)) assert_array_almost_equal(it0,array([0.19933433254006822, -0.34570883800412566]),8) def test_it2j0y0(self): it2 = array(special.it2j0y0(.2)) assert_array_almost_equal(it2,array([0.0049937546274601858, -0.43423067011231614]),8) def test_negv_iv(self): assert_equal(special.iv(3,2), special.iv(-3,2)) def test_j0(self): oz = special.j0(.1) ozr = special.jn(0,.1) assert_almost_equal(oz,ozr,8) def test_j1(self): o1 = special.j1(.1) o1r = special.jn(1,.1) assert_almost_equal(o1,o1r,8) def test_jn(self): jnnr = special.jn(1,.2) assert_almost_equal(jnnr,0.099500832639235995,8) def test_negv_jv(self): assert_almost_equal(special.jv(-3,2), -special.jv(3,2), 14) def test_jv(self): values = [[0, 0.1, 0.99750156206604002], [2./3, 1e-8, 0.3239028506761532e-5], [2./3, 1e-10, 0.1503423854873779e-6], [3.1, 1e-10, 0.1711956265409013e-32], [2./3, 4.0, -0.2325440850267039], ] for i, (v, x, y) in enumerate(values): yc = special.jv(v, x) assert_almost_equal(yc, y, 8, err_msg='test #%d' % i) def test_negv_jve(self): assert_almost_equal(special.jve(-3,2), -special.jve(3,2), 14) def test_jve(self): jvexp = special.jve(1,.2) assert_almost_equal(jvexp,0.099500832639235995,8) jvexp1 = special.jve(1,.2+1j) z = .2+1j jvexpr = special.jv(1,z)*exp(-abs(z.imag)) assert_almost_equal(jvexp1,jvexpr,8) def test_jn_zeros(self): jn0 = special.jn_zeros(0,5) jn1 = special.jn_zeros(1,5) assert_array_almost_equal(jn0,array([2.4048255577, 5.5200781103, 8.6537279129, 11.7915344391, 14.9309177086]),4) assert_array_almost_equal(jn1,array([3.83171, 7.01559, 10.17347, 13.32369, 16.47063]),4) jn102 = special.jn_zeros(102,5) assert_tol_equal(jn102, array([110.89174935992040343, 117.83464175788308398, 123.70194191713507279, 129.02417238949092824, 134.00114761868422559]), rtol=1e-13) jn301 = special.jn_zeros(301,5) assert_tol_equal(jn301, array([313.59097866698830153, 323.21549776096288280, 331.22338738656748796, 338.39676338872084500, 345.03284233056064157]), rtol=1e-13) def test_jn_zeros_slow(self): jn0 = special.jn_zeros(0, 300) assert_tol_equal(jn0[260-1], 816.02884495068867280, rtol=1e-13) assert_tol_equal(jn0[280-1], 878.86068707124422606, rtol=1e-13) assert_tol_equal(jn0[300-1], 941.69253065317954064, rtol=1e-13) jn10 = special.jn_zeros(10, 300) assert_tol_equal(jn10[260-1], 831.67668514305631151, rtol=1e-13) assert_tol_equal(jn10[280-1], 894.51275095371316931, rtol=1e-13) assert_tol_equal(jn10[300-1], 957.34826370866539775, rtol=1e-13) jn3010 = special.jn_zeros(3010,5) assert_tol_equal(jn3010, array([3036.86590780927, 3057.06598526482, 3073.66360690272, 3088.37736494778, 3101.86438139042]), rtol=1e-8) def test_jnjnp_zeros(self): jn = special.jn def jnp(n, x): return (jn(n-1,x) - jn(n+1,x))/2 for nt in range(1, 30): z, n, m, t = special.jnjnp_zeros(nt) for zz, nn, tt in zip(z, n, t): if tt == 0: assert_allclose(jn(nn, zz), 0, atol=1e-6) elif tt == 1: assert_allclose(jnp(nn, zz), 0, atol=1e-6) else: raise AssertionError("Invalid t return for nt=%d" % nt) def test_jnp_zeros(self): jnp = special.jnp_zeros(1,5) assert_array_almost_equal(jnp, array([1.84118, 5.33144, 8.53632, 11.70600, 14.86359]),4) jnp = special.jnp_zeros(443,5) assert_tol_equal(special.jvp(443, jnp), 0, atol=1e-15) def test_jnyn_zeros(self): jnz = special.jnyn_zeros(1,5) assert_array_almost_equal(jnz,(array([3.83171, 7.01559, 10.17347, 13.32369, 16.47063]), array([1.84118, 5.33144, 8.53632, 11.70600, 14.86359]), array([2.19714, 5.42968, 8.59601, 11.74915, 14.89744]), array([3.68302, 6.94150, 10.12340, 13.28576, 16.44006])),5) def test_jvp(self): jvprim = special.jvp(2,2) jv0 = (special.jv(1,2)-special.jv(3,2))/2 assert_almost_equal(jvprim,jv0,10) def test_k0(self): ozk = special.k0(.1) ozkr = special.kv(0,.1) assert_almost_equal(ozk,ozkr,8) def test_k0e(self): ozke = special.k0e(.1) ozker = special.kve(0,.1) assert_almost_equal(ozke,ozker,8) def test_k1(self): o1k = special.k1(.1) o1kr = special.kv(1,.1) assert_almost_equal(o1k,o1kr,8) def test_k1e(self): o1ke = special.k1e(.1) o1ker = special.kve(1,.1) assert_almost_equal(o1ke,o1ker,8) def test_jacobi(self): a = 5*rand() - 1 b = 5*rand() - 1 P0 = special.jacobi(0,a,b) P1 = special.jacobi(1,a,b) P2 = special.jacobi(2,a,b) P3 = special.jacobi(3,a,b) assert_array_almost_equal(P0.c,[1],13) assert_array_almost_equal(P1.c,array([a+b+2,a-b])/2.0,13) cp = [(a+b+3)*(a+b+4), 4*(a+b+3)*(a+2), 4*(a+1)*(a+2)] p2c = [cp[0],cp[1]-2*cp[0],cp[2]-cp[1]+cp[0]] assert_array_almost_equal(P2.c,array(p2c)/8.0,13) cp = [(a+b+4)*(a+b+5)*(a+b+6),6*(a+b+4)*(a+b+5)*(a+3), 12*(a+b+4)*(a+2)*(a+3),8*(a+1)*(a+2)*(a+3)] p3c = [cp[0],cp[1]-3*cp[0],cp[2]-2*cp[1]+3*cp[0],cp[3]-cp[2]+cp[1]-cp[0]] assert_array_almost_equal(P3.c,array(p3c)/48.0,13) def test_kn(self): kn1 = special.kn(0,.2) assert_almost_equal(kn1,1.7527038555281462,8) def test_negv_kv(self): assert_equal(special.kv(3.0, 2.2), special.kv(-3.0, 2.2)) def test_kv0(self): kv0 = special.kv(0,.2) assert_almost_equal(kv0, 1.7527038555281462, 10) def test_kv1(self): kv1 = special.kv(1,0.2) assert_almost_equal(kv1, 4.775972543220472, 10) def test_kv2(self): kv2 = special.kv(2,0.2) assert_almost_equal(kv2, 49.51242928773287, 10) def test_kn_largeorder(self): assert_allclose(special.kn(32, 1), 1.7516596664574289e+43) def test_kv_largearg(self): assert_equal(special.kv(0, 1e19), 0) def test_negv_kve(self): assert_equal(special.kve(3.0, 2.2), special.kve(-3.0, 2.2)) def test_kve(self): kve1 = special.kve(0,.2) kv1 = special.kv(0,.2)*exp(.2) assert_almost_equal(kve1,kv1,8) z = .2+1j kve2 = special.kve(0,z) kv2 = special.kv(0,z)*exp(z) assert_almost_equal(kve2,kv2,8) def test_kvp_v0n1(self): z = 2.2 assert_almost_equal(-special.kv(1,z), special.kvp(0,z, n=1), 10) def test_kvp_n1(self): v = 3. z = 2.2 xc = -special.kv(v+1,z) + v/z*special.kv(v,z) x = special.kvp(v,z, n=1) assert_almost_equal(xc, x, 10) # this function (kvp) is broken def test_kvp_n2(self): v = 3. z = 2.2 xc = (z**2+v**2-v)/z**2 * special.kv(v,z) + special.kv(v+1,z)/z x = special.kvp(v, z, n=2) assert_almost_equal(xc, x, 10) def test_y0(self): oz = special.y0(.1) ozr = special.yn(0,.1) assert_almost_equal(oz,ozr,8) def test_y1(self): o1 = special.y1(.1) o1r = special.yn(1,.1) assert_almost_equal(o1,o1r,8) def test_y0_zeros(self): yo,ypo = special.y0_zeros(2) zo,zpo = special.y0_zeros(2,complex=1) all = r_[yo,zo] allval = r_[ypo,zpo] assert_array_almost_equal(abs(special.yv(0.0,all)),0.0,11) assert_array_almost_equal(abs(special.yv(1,all)-allval),0.0,11) def test_y1_zeros(self): y1 = special.y1_zeros(1) assert_array_almost_equal(y1,(array([2.19714]),array([0.52079])),5) def test_y1p_zeros(self): y1p = special.y1p_zeros(1,complex=1) assert_array_almost_equal(y1p,(array([0.5768+0.904j]), array([-0.7635+0.5892j])),3) def test_yn_zeros(self): an = special.yn_zeros(4,2) assert_array_almost_equal(an,array([5.64515, 9.36162]),5) an = special.yn_zeros(443,5) assert_tol_equal(an, [450.13573091578090314, 463.05692376675001542, 472.80651546418663566, 481.27353184725625838, 488.98055964441374646], rtol=1e-15) def test_ynp_zeros(self): ao = special.ynp_zeros(0,2) assert_array_almost_equal(ao,array([2.19714133, 5.42968104]),6) ao = special.ynp_zeros(43,5) assert_tol_equal(special.yvp(43, ao), 0, atol=1e-15) ao = special.ynp_zeros(443,5) assert_tol_equal(special.yvp(443, ao), 0, atol=1e-9) def test_ynp_zeros_large_order(self): ao = special.ynp_zeros(443,5) assert_tol_equal(special.yvp(443, ao), 0, atol=1e-14) def test_yn(self): yn2n = special.yn(1,.2) assert_almost_equal(yn2n,-3.3238249881118471,8) def test_negv_yv(self): assert_almost_equal(special.yv(-3,2), -special.yv(3,2), 14) def test_yv(self): yv2 = special.yv(1,.2) assert_almost_equal(yv2,-3.3238249881118471,8) def test_negv_yve(self): assert_almost_equal(special.yve(-3,2), -special.yve(3,2), 14) def test_yve(self): yve2 = special.yve(1,.2) assert_almost_equal(yve2,-3.3238249881118471,8) yve2r = special.yv(1,.2+1j)*exp(-1) yve22 = special.yve(1,.2+1j) assert_almost_equal(yve22,yve2r,8) def test_yvp(self): yvpr = (special.yv(1,.2) - special.yv(3,.2))/2.0 yvp1 = special.yvp(2,.2) assert_array_almost_equal(yvp1,yvpr,10) def _cephes_vs_amos_points(self): """Yield points at which to compare Cephes implementation to AMOS""" # check several points, including large-amplitude ones for v in [-120, -100.3, -20., -10., -1., -.5, 0., 1., 12.49, 120., 301]: for z in [-1300, -11, -10, -1, 1., 10., 200.5, 401., 600.5, 700.6, 1300, 10003]: yield v, z # check half-integers; these are problematic points at least # for cephes/iv for v in 0.5 + arange(-60, 60): yield v, 3.5 def check_cephes_vs_amos(self, f1, f2, rtol=1e-11, atol=0, skip=None): for v, z in self._cephes_vs_amos_points(): if skip is not None and skip(v, z): continue c1, c2, c3 = f1(v, z), f1(v,z+0j), f2(int(v), z) if np.isinf(c1): assert_(np.abs(c2) >= 1e300, (v, z)) elif np.isnan(c1): assert_(c2.imag != 0, (v, z)) else: assert_tol_equal(c1, c2, err_msg=(v, z), rtol=rtol, atol=atol) if v == int(v): assert_tol_equal(c3, c2, err_msg=(v, z), rtol=rtol, atol=atol) def test_jv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.jv, special.jn, rtol=1e-10, atol=1e-305) def test_yv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305) def test_yv_cephes_vs_amos_only_small_orders(self): skipper = lambda v, z: (abs(v) > 50) self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305, skip=skipper) def test_iv_cephes_vs_amos(self): olderr = np.seterr(all='ignore') try: self.check_cephes_vs_amos(special.iv, special.iv, rtol=5e-9, atol=1e-305) finally: np.seterr(**olderr) @dec.slow def test_iv_cephes_vs_amos_mass_test(self): N = 1000000 np.random.seed(1) v = np.random.pareto(0.5, N) * (-1)**np.random.randint(2, size=N) x = np.random.pareto(0.2, N) * (-1)**np.random.randint(2, size=N) imsk = (np.random.randint(8, size=N) == 0) v[imsk] = v[imsk].astype(int) old_err = np.seterr(all='ignore') try: c1 = special.iv(v, x) c2 = special.iv(v, x+0j) # deal with differences in the inf and zero cutoffs c1[abs(c1) > 1e300] = np.inf c2[abs(c2) > 1e300] = np.inf c1[abs(c1) < 1e-300] = 0 c2[abs(c2) < 1e-300] = 0 dc = abs(c1/c2 - 1) dc[np.isnan(dc)] = 0 finally: np.seterr(**old_err) k = np.argmax(dc) # Most error apparently comes from AMOS and not our implementation; # there are some problems near integer orders there assert_(dc[k] < 2e-7, (v[k], x[k], special.iv(v[k], x[k]), special.iv(v[k], x[k]+0j))) def test_kv_cephes_vs_amos(self): self.check_cephes_vs_amos(special.kv, special.kn, rtol=1e-9, atol=1e-305) self.check_cephes_vs_amos(special.kv, special.kv, rtol=1e-9, atol=1e-305) def test_ticket_623(self): assert_tol_equal(special.jv(3, 4), 0.43017147387562193) assert_tol_equal(special.jv(301, 1300), 0.0183487151115275) assert_tol_equal(special.jv(301, 1296.0682), -0.0224174325312048) def test_ticket_853(self): """Negative-order Bessels""" # cephes assert_tol_equal(special.jv(-1, 1), -0.4400505857449335) assert_tol_equal(special.jv(-2, 1), 0.1149034849319005) assert_tol_equal(special.yv(-1, 1), 0.7812128213002887) assert_tol_equal(special.yv(-2, 1), -1.650682606816255) assert_tol_equal(special.iv(-1, 1), 0.5651591039924851) assert_tol_equal(special.iv(-2, 1), 0.1357476697670383) assert_tol_equal(special.kv(-1, 1), 0.6019072301972347) assert_tol_equal(special.kv(-2, 1), 1.624838898635178) assert_tol_equal(special.jv(-0.5, 1), 0.43109886801837607952) assert_tol_equal(special.yv(-0.5, 1), 0.6713967071418031) assert_tol_equal(special.iv(-0.5, 1), 1.231200214592967) assert_tol_equal(special.kv(-0.5, 1), 0.4610685044478945) # amos assert_tol_equal(special.jv(-1, 1+0j), -0.4400505857449335) assert_tol_equal(special.jv(-2, 1+0j), 0.1149034849319005) assert_tol_equal(special.yv(-1, 1+0j), 0.7812128213002887) assert_tol_equal(special.yv(-2, 1+0j), -1.650682606816255) assert_tol_equal(special.iv(-1, 1+0j), 0.5651591039924851) assert_tol_equal(special.iv(-2, 1+0j), 0.1357476697670383) assert_tol_equal(special.kv(-1, 1+0j), 0.6019072301972347) assert_tol_equal(special.kv(-2, 1+0j), 1.624838898635178) assert_tol_equal(special.jv(-0.5, 1+0j), 0.43109886801837607952) assert_tol_equal(special.jv(-0.5, 1+1j), 0.2628946385649065-0.827050182040562j) assert_tol_equal(special.yv(-0.5, 1+0j), 0.6713967071418031) assert_tol_equal(special.yv(-0.5, 1+1j), 0.967901282890131+0.0602046062142816j) assert_tol_equal(special.iv(-0.5, 1+0j), 1.231200214592967) assert_tol_equal(special.iv(-0.5, 1+1j), 0.77070737376928+0.39891821043561j) assert_tol_equal(special.kv(-0.5, 1+0j), 0.4610685044478945) assert_tol_equal(special.kv(-0.5, 1+1j), 0.06868578341999-0.38157825981268j) assert_tol_equal(special.jve(-0.5,1+0.3j), special.jv(-0.5, 1+0.3j)*exp(-0.3)) assert_tol_equal(special.yve(-0.5,1+0.3j), special.yv(-0.5, 1+0.3j)*exp(-0.3)) assert_tol_equal(special.ive(-0.5,0.3+1j), special.iv(-0.5, 0.3+1j)*exp(-0.3)) assert_tol_equal(special.kve(-0.5,0.3+1j), special.kv(-0.5, 0.3+1j)*exp(0.3+1j)) assert_tol_equal(special.hankel1(-0.5, 1+1j), special.jv(-0.5, 1+1j) + 1j*special.yv(-0.5,1+1j)) assert_tol_equal(special.hankel2(-0.5, 1+1j), special.jv(-0.5, 1+1j) - 1j*special.yv(-0.5,1+1j)) def test_ticket_854(self): """Real-valued Bessel domains""" assert_(isnan(special.jv(0.5, -1))) assert_(isnan(special.iv(0.5, -1))) assert_(isnan(special.yv(0.5, -1))) assert_(isnan(special.yv(1, -1))) assert_(isnan(special.kv(0.5, -1))) assert_(isnan(special.kv(1, -1))) assert_(isnan(special.jve(0.5, -1))) assert_(isnan(special.ive(0.5, -1))) assert_(isnan(special.yve(0.5, -1))) assert_(isnan(special.yve(1, -1))) assert_(isnan(special.kve(0.5, -1))) assert_(isnan(special.kve(1, -1))) assert_(isnan(special.airye(-1)[0:2]).all(), special.airye(-1)) assert_(not isnan(special.airye(-1)[2:4]).any(), special.airye(-1)) def test_ticket_503(self): """Real-valued Bessel I overflow""" assert_tol_equal(special.iv(1, 700), 1.528500390233901e302) assert_tol_equal(special.iv(1000, 1120), 1.301564549405821e301) def test_iv_hyperg_poles(self): assert_tol_equal(special.iv(-0.5, 1), 1.231200214592967) def iv_series(self, v, z, n=200): k = arange(0, n).astype(float_) r = (v+2*k)*log(.5*z) - special.gammaln(k+1) - special.gammaln(v+k+1) r[isnan(r)] = inf r = exp(r) err = abs(r).max() * finfo(float_).eps * n + abs(r[-1])*10 return r.sum(), err def test_i0_series(self): for z in [1., 10., 200.5]: value, err = self.iv_series(0, z) assert_tol_equal(special.i0(z), value, atol=err, err_msg=z) def test_i1_series(self): for z in [1., 10., 200.5]: value, err = self.iv_series(1, z) assert_tol_equal(special.i1(z), value, atol=err, err_msg=z) def test_iv_series(self): for v in [-20., -10., -1., 0., 1., 12.49, 120.]: for z in [1., 10., 200.5, -1+2j]: value, err = self.iv_series(v, z) assert_tol_equal(special.iv(v, z), value, atol=err, err_msg=(v, z)) def test_i0(self): values = [[0.0, 1.0], [1e-10, 1.0], [0.1, 0.9071009258], [0.5, 0.6450352706], [1.0, 0.4657596077], [2.5, 0.2700464416], [5.0, 0.1835408126], [20.0, 0.0897803119], ] for i, (x, v) in enumerate(values): cv = special.i0(x) * exp(-x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_i0e(self): oize = special.i0e(.1) oizer = special.ive(0,.1) assert_almost_equal(oize,oizer,8) def test_i1(self): values = [[0.0, 0.0], [1e-10, 0.4999999999500000e-10], [0.1, 0.0452984468], [0.5, 0.1564208032], [1.0, 0.2079104154], [5.0, 0.1639722669], [20.0, 0.0875062222], ] for i, (x, v) in enumerate(values): cv = special.i1(x) * exp(-x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) def test_i1e(self): oi1e = special.i1e(.1) oi1er = special.ive(1,.1) assert_almost_equal(oi1e,oi1er,8) def test_iti0k0(self): iti0 = array(special.iti0k0(5)) assert_array_almost_equal(iti0,array([31.848667776169801, 1.5673873907283657]),5) def test_it2i0k0(self): it2k = special.it2i0k0(.1) assert_array_almost_equal(it2k,array([0.0012503906973464409, 3.3309450354686687]),6) def test_iv(self): iv1 = special.iv(0,.1)*exp(-.1) assert_almost_equal(iv1,0.90710092578230106,10) def test_negv_ive(self): assert_equal(special.ive(3,2), special.ive(-3,2)) def test_ive(self): ive1 = special.ive(0,.1) iv1 = special.iv(0,.1)*exp(-.1) assert_almost_equal(ive1,iv1,10) def test_ivp0(self): assert_almost_equal(special.iv(1,2), special.ivp(0,2), 10) def test_ivp(self): y = (special.iv(0,2) + special.iv(2,2))/2 x = special.ivp(1,2) assert_almost_equal(x,y,10) class TestLaguerre(TestCase): def test_laguerre(self): lag0 = special.laguerre(0) lag1 = special.laguerre(1) lag2 = special.laguerre(2) lag3 = special.laguerre(3) lag4 = special.laguerre(4) lag5 = special.laguerre(5) assert_array_almost_equal(lag0.c,[1],13) assert_array_almost_equal(lag1.c,[-1,1],13) assert_array_almost_equal(lag2.c,array([1,-4,2])/2.0,13) assert_array_almost_equal(lag3.c,array([-1,9,-18,6])/6.0,13) assert_array_almost_equal(lag4.c,array([1,-16,72,-96,24])/24.0,13) assert_array_almost_equal(lag5.c,array([-1,25,-200,600,-600,120])/120.0,13) def test_genlaguerre(self): k = 5*rand()-0.9 lag0 = special.genlaguerre(0,k) lag1 = special.genlaguerre(1,k) lag2 = special.genlaguerre(2,k) lag3 = special.genlaguerre(3,k) assert_equal(lag0.c,[1]) assert_equal(lag1.c,[-1,k+1]) assert_almost_equal(lag2.c,array([1,-2*(k+2),(k+1.)*(k+2.)])/2.0) assert_almost_equal(lag3.c,array([-1,3*(k+3),-3*(k+2)*(k+3),(k+1)*(k+2)*(k+3)])/6.0) # Base polynomials come from Abrahmowitz and Stegan class TestLegendre(TestCase): def test_legendre(self): leg0 = special.legendre(0) leg1 = special.legendre(1) leg2 = special.legendre(2) leg3 = special.legendre(3) leg4 = special.legendre(4) leg5 = special.legendre(5) assert_equal(leg0.c, [1]) assert_equal(leg1.c, [1,0]) assert_almost_equal(leg2.c, array([3,0,-1])/2.0, decimal=13) assert_almost_equal(leg3.c, array([5,0,-3,0])/2.0) assert_almost_equal(leg4.c, array([35,0,-30,0,3])/8.0) assert_almost_equal(leg5.c, array([63,0,-70,0,15,0])/8.0) class TestLambda(TestCase): def test_lmbda(self): lam = special.lmbda(1,.1) lamr = (array([special.jn(0,.1), 2*special.jn(1,.1)/.1]), array([special.jvp(0,.1), -2*special.jv(1,.1)/.01 + 2*special.jvp(1,.1)/.1])) assert_array_almost_equal(lam,lamr,8) class TestLog1p(TestCase): def test_log1p(self): l1p = (special.log1p(10), special.log1p(11), special.log1p(12)) l1prl = (log(11), log(12), log(13)) assert_array_almost_equal(l1p,l1prl,8) def test_log1pmore(self): l1pm = (special.log1p(1), special.log1p(1.1), special.log1p(1.2)) l1pmrl = (log(2),log(2.1),log(2.2)) assert_array_almost_equal(l1pm,l1pmrl,8) class TestLegendreFunctions(TestCase): def test_clpmn(self): z = 0.5+0.3j clp = special.clpmn(2, 2, z, 3) assert_array_almost_equal(clp, (array([[1.0000, z, 0.5*(3*z*z-1)], [0.0000, sqrt(z*z-1), 3*z*sqrt(z*z-1)], [0.0000, 0.0000, 3*(z*z-1)]]), array([[0.0000, 1.0000, 3*z], [0.0000, z/sqrt(z*z-1), 3*(2*z*z-1)/sqrt(z*z-1)], [0.0000, 0.0000, 6*z]])), 7) def test_clpmn_close_to_real_2(self): eps = 1e-10 m = 1 n = 3 x = 0.5 clp_plus = special.clpmn(m, n, x+1j*eps, 2)[0][m, n] clp_minus = special.clpmn(m, n, x-1j*eps, 2)[0][m, n] assert_array_almost_equal(array([clp_plus, clp_minus]), array([special.lpmv(m, n, x), special.lpmv(m, n, x)]), 7) def test_clpmn_close_to_real_3(self): eps = 1e-10 m = 1 n = 3 x = 0.5 clp_plus = special.clpmn(m, n, x+1j*eps, 3)[0][m, n] clp_minus = special.clpmn(m, n, x-1j*eps, 3)[0][m, n] assert_array_almost_equal(array([clp_plus, clp_minus]), array([special.lpmv(m, n, x)*np.exp(-0.5j*m*np.pi), special.lpmv(m, n, x)*np.exp(0.5j*m*np.pi)]), 7) def test_clpmn_across_unit_circle(self): eps = 1e-7 m = 1 n = 1 x = 1j for type in [2, 3]: assert_almost_equal(special.clpmn(m, n, x+1j*eps, type)[0][m, n], special.clpmn(m, n, x-1j*eps, type)[0][m, n], 6) def test_inf(self): for z in (1, -1): for n in range(4): for m in range(1, n): lp = special.clpmn(m, n, z) assert_(np.isinf(lp[1][1,1:]).all()) lp = special.lpmn(m, n, z) assert_(np.isinf(lp[1][1,1:]).all()) def test_deriv_clpmn(self): # data inside and outside of the unit circle zvals = [0.5+0.5j, -0.5+0.5j, -0.5-0.5j, 0.5-0.5j, 1+1j, -1+1j, -1-1j, 1-1j] m = 2 n = 3 for type in [2, 3]: for z in zvals: for h in [1e-3, 1e-3j]: approx_derivative = (special.clpmn(m, n, z+0.5*h, type)[0] - special.clpmn(m, n, z-0.5*h, type)[0])/h assert_allclose(special.clpmn(m, n, z, type)[1], approx_derivative, rtol=1e-4) def test_lpmn(self): lp = special.lpmn(0,2,.5) assert_array_almost_equal(lp,(array([[1.00000, 0.50000, -0.12500]]), array([[0.00000, 1.00000, 1.50000]])),4) def test_lpn(self): lpnf = special.lpn(2,.5) assert_array_almost_equal(lpnf,(array([1.00000, 0.50000, -0.12500]), array([0.00000, 1.00000, 1.50000])),4) def test_lpmv(self): lp = special.lpmv(0,2,.5) assert_almost_equal(lp,-0.125,7) lp = special.lpmv(0,40,.001) assert_almost_equal(lp,0.1252678976534484,7) # XXX: this is outside the domain of the current implementation, # so ensure it returns a NaN rather than a wrong answer. olderr = np.seterr(all='ignore') try: lp = special.lpmv(-1,-1,.001) finally: np.seterr(**olderr) assert_(lp != 0 or np.isnan(lp)) def test_lqmn(self): lqmnf = special.lqmn(0,2,.5) lqf = special.lqn(2,.5) assert_array_almost_equal(lqmnf[0][0],lqf[0],4) assert_array_almost_equal(lqmnf[1][0],lqf[1],4) def test_lqmn_gt1(self): """algorithm for real arguments changes at 1.0001 test against analytical result for m=2, n=1 """ x0 = 1.0001 delta = 0.00002 for x in (x0-delta, x0+delta): lq = special.lqmn(2, 1, x)[0][-1, -1] expected = 2/(x*x-1) assert_almost_equal(lq, expected) def test_lqmn_shape(self): a, b = special.lqmn(4, 4, 1.1) assert_equal(a.shape, (5, 5)) assert_equal(b.shape, (5, 5)) a, b = special.lqmn(4, 0, 1.1) assert_equal(a.shape, (5, 1)) assert_equal(b.shape, (5, 1)) def test_lqn(self): lqf = special.lqn(2,.5) assert_array_almost_equal(lqf,(array([0.5493, -0.7253, -0.8187]), array([1.3333, 1.216, -0.8427])),4) class TestMathieu(TestCase): def test_mathieu_a(self): pass def test_mathieu_even_coef(self): mc = special.mathieu_even_coef(2,5) # Q not defined broken and cannot figure out proper reporting order def test_mathieu_odd_coef(self): # same problem as above pass class TestFresnelIntegral(TestCase): def test_modfresnelp(self): pass def test_modfresnelm(self): pass class TestOblCvSeq(TestCase): def test_obl_cv_seq(self): obl = special.obl_cv_seq(0,3,1) assert_array_almost_equal(obl,array([-0.348602, 1.393206, 5.486800, 11.492120]),5) class TestParabolicCylinder(TestCase): def test_pbdn_seq(self): pb = special.pbdn_seq(1,.1) assert_array_almost_equal(pb,(array([0.9975, 0.0998]), array([-0.0499, 0.9925])),4) def test_pbdv(self): pbv = special.pbdv(1,.2) derrl = 1/2*(.2)*special.pbdv(1,.2)[0] - special.pbdv(0,.2)[0] def test_pbdv_seq(self): pbn = special.pbdn_seq(1,.1) pbv = special.pbdv_seq(1,.1) assert_array_almost_equal(pbv,(real(pbn[0]),real(pbn[1])),4) def test_pbdv_points(self): # simple case eta = np.linspace(-10, 10, 5) z = 2**(eta/2)*np.sqrt(np.pi)/special.gamma(.5-.5*eta) assert_tol_equal(special.pbdv(eta, 0.)[0], z, rtol=1e-14, atol=1e-14) # some points assert_tol_equal(special.pbdv(10.34, 20.44)[0], 1.3731383034455e-32, rtol=1e-12) assert_tol_equal(special.pbdv(-9.53, 3.44)[0], 3.166735001119246e-8, rtol=1e-12) def test_pbdv_gradient(self): x = np.linspace(-4, 4, 8)[:,None] eta = np.linspace(-10, 10, 5)[None,:] p = special.pbdv(eta, x) eps = 1e-7 + 1e-7*abs(x) dp = (special.pbdv(eta, x + eps)[0] - special.pbdv(eta, x - eps)[0]) / eps / 2. assert_tol_equal(p[1], dp, rtol=1e-6, atol=1e-6) def test_pbvv_gradient(self): x = np.linspace(-4, 4, 8)[:,None] eta = np.linspace(-10, 10, 5)[None,:] p = special.pbvv(eta, x) eps = 1e-7 + 1e-7*abs(x) dp = (special.pbvv(eta, x + eps)[0] - special.pbvv(eta, x - eps)[0]) / eps / 2. assert_tol_equal(p[1], dp, rtol=1e-6, atol=1e-6) class TestPolygamma(TestCase): # from Table 6.2 (pg. 271) of A&S def test_polygamma(self): poly2 = special.polygamma(2,1) poly3 = special.polygamma(3,1) assert_almost_equal(poly2,-2.4041138063,10) assert_almost_equal(poly3,6.4939394023,10) # Test polygamma(0, x) == psi(x) x = [2, 3, 1.1e14] assert_almost_equal(special.polygamma(0, x), special.psi(x)) # Test broadcasting n = [0, 1, 2] x = [0.5, 1.5, 2.5] expected = [-1.9635100260214238, 0.93480220054467933, -0.23620405164172739] assert_almost_equal(special.polygamma(n, x), expected) expected = np.row_stack([expected]*2) assert_almost_equal(special.polygamma(n, np.row_stack([x]*2)), expected) assert_almost_equal(special.polygamma(np.row_stack([n]*2), x), expected) class TestProCvSeq(TestCase): def test_pro_cv_seq(self): prol = special.pro_cv_seq(0,3,1) assert_array_almost_equal(prol,array([0.319000, 2.593084, 6.533471, 12.514462]),5) class TestPsi(TestCase): def test_psi(self): ps = special.psi(1) assert_almost_equal(ps,-0.57721566490153287,8) class TestRadian(TestCase): def test_radian(self): rad = special.radian(90,0,0) assert_almost_equal(rad,pi/2.0,5) def test_radianmore(self): rad1 = special.radian(90,1,60) assert_almost_equal(rad1,pi/2+0.0005816135199345904,5) class TestRiccati(TestCase): def test_riccati_jn(self): jnrl = (special.sph_jn(1,.2)[0]*.2,special.sph_jn(1,.2)[0]+special.sph_jn(1,.2)[1]*.2) ricjn = special.riccati_jn(1,.2) assert_array_almost_equal(ricjn,jnrl,8) def test_riccati_yn(self): ynrl = (special.sph_yn(1,.2)[0]*.2,special.sph_yn(1,.2)[0]+special.sph_yn(1,.2)[1]*.2) ricyn = special.riccati_yn(1,.2) assert_array_almost_equal(ricyn,ynrl,8) class TestRound(TestCase): def test_round(self): rnd = list(map(int,(special.round(10.1),special.round(10.4),special.round(10.5),special.round(10.6)))) # Note: According to the documentation, scipy.special.round is # supposed to round to the nearest even number if the fractional # part is exactly 0.5. On some platforms, this does not appear # to work and thus this test may fail. However, this unit test is # correctly written. rndrl = (10,10,10,11) assert_array_equal(rnd,rndrl) def test_sph_harm(): # Tests derived from tables in # http://en.wikipedia.org/wiki/Table_of_spherical_harmonics sh = special.sph_harm pi = np.pi exp = np.exp sqrt = np.sqrt sin = np.sin cos = np.cos yield (assert_array_almost_equal, sh(0,0,0,0), 0.5/sqrt(pi)) yield (assert_array_almost_equal, sh(-2,2,0.,pi/4), 0.25*sqrt(15./(2.*pi)) * (sin(pi/4))**2.) yield (assert_array_almost_equal, sh(-2,2,0.,pi/2), 0.25*sqrt(15./(2.*pi))) yield (assert_array_almost_equal, sh(2,2,pi,pi/2), 0.25*sqrt(15/(2.*pi)) * exp(0+2.*pi*1j)*sin(pi/2.)**2.) yield (assert_array_almost_equal, sh(2,4,pi/4.,pi/3.), (3./8.)*sqrt(5./(2.*pi)) * exp(0+2.*pi/4.*1j) * sin(pi/3.)**2. * (7.*cos(pi/3.)**2.-1)) yield (assert_array_almost_equal, sh(4,4,pi/8.,pi/6.), (3./16.)*sqrt(35./(2.*pi)) * exp(0+4.*pi/8.*1j)*sin(pi/6.)**4.) def test_sph_harm_ufunc_loop_selection(): # see https://github.com/scipy/scipy/issues/4895 dt = np.dtype(np.complex128) assert_equal(special.sph_harm(0, 0, 0, 0).dtype, dt) assert_equal(special.sph_harm([0], 0, 0, 0).dtype, dt) assert_equal(special.sph_harm(0, [0], 0, 0).dtype, dt) assert_equal(special.sph_harm(0, 0, [0], 0).dtype, dt) assert_equal(special.sph_harm(0, 0, 0, [0]).dtype, dt) assert_equal(special.sph_harm([0], [0], [0], [0]).dtype, dt) class TestSpherical(TestCase): def test_sph_harm(self): # see test_sph_harm function pass def test_sph_in(self): i1n = special.sph_in(1,.2) inp0 = (i1n[0][1]) inp1 = (i1n[0][0] - 2.0/0.2 * i1n[0][1]) assert_array_almost_equal(i1n[0],array([1.0066800127054699381, 0.066933714568029540839]),12) assert_array_almost_equal(i1n[1],[inp0,inp1],12) def test_sph_inkn(self): spikn = r_[special.sph_in(1,.2) + special.sph_kn(1,.2)] inkn = r_[special.sph_inkn(1,.2)] assert_array_almost_equal(inkn,spikn,10) def test_sph_in_kn_order0(self): x = 1. sph_i0 = special.sph_in(0, x) sph_i0_expected = np.array([np.sinh(x)/x, np.cosh(x)/x-np.sinh(x)/x**2]) assert_array_almost_equal(r_[sph_i0], sph_i0_expected) sph_k0 = special.sph_kn(0, x) sph_k0_expected = np.array([0.5*pi*exp(-x)/x, -0.5*pi*exp(-x)*(1/x+1/x**2)]) assert_array_almost_equal(r_[sph_k0], sph_k0_expected) sph_i0k0 = special.sph_inkn(0, x) assert_array_almost_equal(r_[sph_i0+sph_k0], r_[sph_i0k0], 10) def test_sph_jn(self): s1 = special.sph_jn(2,.2) s10 = -s1[0][1] s11 = s1[0][0]-2.0/0.2*s1[0][1] s12 = s1[0][1]-3.0/0.2*s1[0][2] assert_array_almost_equal(s1[0],[0.99334665397530607731, 0.066400380670322230863, 0.0026590560795273856680],12) assert_array_almost_equal(s1[1],[s10,s11,s12],12) def test_sph_jnyn(self): jnyn = r_[special.sph_jn(1,.2) + special.sph_yn(1,.2)] # tuple addition jnyn1 = r_[special.sph_jnyn(1,.2)] assert_array_almost_equal(jnyn1,jnyn,9) def test_sph_kn(self): kn = special.sph_kn(2,.2) kn0 = -kn[0][1] kn1 = -kn[0][0]-2.0/0.2*kn[0][1] kn2 = -kn[0][1]-3.0/0.2*kn[0][2] assert_array_almost_equal(kn[0],[6.4302962978445670140, 38.581777787067402086, 585.15696310385559829],12) assert_array_almost_equal(kn[1],[kn0,kn1,kn2],9) def test_sph_yn(self): sy1 = special.sph_yn(2,.2)[0][2] sy2 = special.sph_yn(0,.2)[0][0] sphpy = (special.sph_yn(1,.2)[0][0]-2*special.sph_yn(2,.2)[0][2])/3 # correct derivative value assert_almost_equal(sy1,-377.52483,5) # previous values in the system assert_almost_equal(sy2,-4.9003329,5) sy3 = special.sph_yn(1,.2)[1][1] assert_almost_equal(sy3,sphpy,4) # compare correct derivative val. (correct =-system val). class TestStruve(object): def _series(self, v, z, n=100): """Compute Struve function & error estimate from its power series.""" k = arange(0, n) r = (-1)**k * (.5*z)**(2*k+v+1)/special.gamma(k+1.5)/special.gamma(k+v+1.5) err = abs(r).max() * finfo(float_).eps * n return r.sum(), err def test_vs_series(self): """Check Struve function versus its power series""" for v in [-20, -10, -7.99, -3.4, -1, 0, 1, 3.4, 12.49, 16]: for z in [1, 10, 19, 21, 30]: value, err = self._series(v, z) assert_tol_equal(special.struve(v, z), value, rtol=0, atol=err), (v, z) def test_some_values(self): assert_tol_equal(special.struve(-7.99, 21), 0.0467547614113, rtol=1e-7) assert_tol_equal(special.struve(-8.01, 21), 0.0398716951023, rtol=1e-8) assert_tol_equal(special.struve(-3.0, 200), 0.0142134427432, rtol=1e-12) assert_tol_equal(special.struve(-8.0, -41), 0.0192469727846, rtol=1e-11) assert_equal(special.struve(-12, -41), -special.struve(-12, 41)) assert_equal(special.struve(+12, -41), -special.struve(+12, 41)) assert_equal(special.struve(-11, -41), +special.struve(-11, 41)) assert_equal(special.struve(+11, -41), +special.struve(+11, 41)) assert_(isnan(special.struve(-7.1, -1))) assert_(isnan(special.struve(-10.1, -1))) def test_regression_679(self): """Regression test for #679""" assert_tol_equal(special.struve(-1.0, 20 - 1e-8), special.struve(-1.0, 20 + 1e-8)) assert_tol_equal(special.struve(-2.0, 20 - 1e-8), special.struve(-2.0, 20 + 1e-8)) assert_tol_equal(special.struve(-4.3, 20 - 1e-8), special.struve(-4.3, 20 + 1e-8)) def test_chi2_smalldf(): assert_almost_equal(special.chdtr(0.6,3), 0.957890536704110) def test_chi2c_smalldf(): assert_almost_equal(special.chdtrc(0.6,3), 1-0.957890536704110) def test_chi2_inv_smalldf(): assert_almost_equal(special.chdtri(0.6,1-0.957890536704110), 3) def test_agm_simple(): assert_allclose(special.agm(24, 6), 13.4581714817) assert_allclose(special.agm(1e30, 1), 2.2292230559453832047768593e28) def test_legacy(): with warnings.catch_warnings(): warnings.simplefilter("ignore", RuntimeWarning) # Legacy behavior: truncating arguments to integers assert_equal(special.bdtrc(1, 2, 0.3), special.bdtrc(1.8, 2.8, 0.3)) assert_equal(special.bdtr(1, 2, 0.3), special.bdtr(1.8, 2.8, 0.3)) assert_equal(special.bdtri(1, 2, 0.3), special.bdtri(1.8, 2.8, 0.3)) assert_equal(special.expn(1, 0.3), special.expn(1.8, 0.3)) assert_equal(special.hyp2f0(1, 2, 0.3, 1), special.hyp2f0(1, 2, 0.3, 1.8)) assert_equal(special.nbdtrc(1, 2, 0.3), special.nbdtrc(1.8, 2.8, 0.3)) assert_equal(special.nbdtr(1, 2, 0.3), special.nbdtr(1.8, 2.8, 0.3)) assert_equal(special.nbdtri(1, 2, 0.3), special.nbdtri(1.8, 2.8, 0.3)) assert_equal(special.pdtrc(1, 0.3), special.pdtrc(1.8, 0.3)) assert_equal(special.pdtr(1, 0.3), special.pdtr(1.8, 0.3)) assert_equal(special.pdtri(1, 0.3), special.pdtri(1.8, 0.3)) assert_equal(special.kn(1, 0.3), special.kn(1.8, 0.3)) assert_equal(special.yn(1, 0.3), special.yn(1.8, 0.3)) assert_equal(special.smirnov(1, 0.3), special.smirnov(1.8, 0.3)) assert_equal(special.smirnovi(1, 0.3), special.smirnovi(1.8, 0.3)) @with_special_errors def test_error_raising(): assert_raises(special.SpecialFunctionWarning, special.iv, 1, 1e99j) def test_xlogy(): def xfunc(x, y): if x == 0 and not np.isnan(y): return x else: return x*np.log(y) z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0)], dtype=float) z2 = np.r_[z1, [(0, 1j), (1, 1j)]] w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1]) assert_func_equal(special.xlogy, w1, z1, rtol=1e-13, atol=1e-13) w2 = np.vectorize(xfunc)(z2[:,0], z2[:,1]) assert_func_equal(special.xlogy, w2, z2, rtol=1e-13, atol=1e-13) def test_xlog1py(): def xfunc(x, y): if x == 0 and not np.isnan(y): return x else: return x * np.log1p(y) z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0), (1, 1e-30)], dtype=float) w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1]) assert_func_equal(special.xlog1py, w1, z1, rtol=1e-13, atol=1e-13) def test_entr(): def xfunc(x): if x < 0: return -np.inf else: return -special.xlogy(x, x) values = (0, 0.5, 1.0, np.inf) signs = [-1, 1] arr = [] for sgn, v in itertools.product(signs, values): arr.append(sgn * v) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z) assert_func_equal(special.entr, w, z, rtol=1e-13, atol=1e-13) def test_kl_div(): def xfunc(x, y): if x < 0 or y < 0 or (y == 0 and x != 0): # extension of natural domain to preserve convexity return np.inf elif np.isposinf(x) or np.isposinf(y): # limits within the natural domain return np.inf elif x == 0: return y else: return special.xlogy(x, x/y) - x + y values = (0, 0.5, 1.0) signs = [-1, 1] arr = [] for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values): arr.append((sgna*va, sgnb*vb)) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.kl_div, w, z, rtol=1e-13, atol=1e-13) def test_rel_entr(): def xfunc(x, y): if x > 0 and y > 0: return special.xlogy(x, x/y) elif x == 0 and y >= 0: return 0 else: return np.inf values = (0, 0.5, 1.0) signs = [-1, 1] arr = [] for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values): arr.append((sgna*va, sgnb*vb)) z = np.array(arr, dtype=float) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.rel_entr, w, z, rtol=1e-13, atol=1e-13) def test_huber(): assert_equal(special.huber(-1, 1.5), np.inf) assert_allclose(special.huber(2, 1.5), 0.5 * np.square(1.5)) assert_allclose(special.huber(2, 2.5), 2 * (2.5 - 0.5 * 2)) def xfunc(delta, r): if delta < 0: return np.inf elif np.abs(r) < delta: return 0.5 * np.square(r) else: return delta * (np.abs(r) - 0.5 * delta) z = np.random.randn(10, 2) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.huber, w, z, rtol=1e-13, atol=1e-13) def test_pseudo_huber(): def xfunc(delta, r): if delta < 0: return np.inf elif (not delta) or (not r): return 0 else: return delta**2 * (np.sqrt(1 + (r/delta)**2) - 1) z = np.array(np.random.randn(10, 2).tolist() + [[0, 0.5], [0.5, 0]]) w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) assert_func_equal(special.pseudo_huber, w, z, rtol=1e-13, atol=1e-13) if __name__ == "__main__": run_module_suite()
bsd-3-clause
junaidk/gitinspector
gitinspector/extensions.py
51
2927
# coding: utf-8 # # Copyright © 2012-2014 Ejwa Software. All rights reserved. # # This file is part of gitinspector. # # gitinspector 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. # # gitinspector 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 gitinspector. If not, see <http://www.gnu.org/licenses/>. from __future__ import print_function from __future__ import unicode_literals from localization import N_ from outputable import Outputable import terminal import textwrap DEFAULT_EXTENSIONS = ["java", "c", "cc", "cpp", "h", "hh", "hpp", "py", "glsl", "rb", "js", "sql"] __extensions__ = DEFAULT_EXTENSIONS __located_extensions__ = set() def get(): return __extensions__ def define(string): global __extensions__ __extensions__ = string.split(",") def add_located(string): if len(string) > 0: __located_extensions__.add(string) EXTENSIONS_INFO_TEXT = N_("The extensions below were found in the repository history") EXTENSIONS_MARKED_TEXT = N_("(extensions used during statistical analysis are marked)") class Extensions(Outputable): def output_html(self): if __located_extensions__: extensions_xml = "<div><div class=\"box\">" extensions_xml += "<p>{0} {1}.</p><p>".format(_(EXTENSIONS_INFO_TEXT), _(EXTENSIONS_MARKED_TEXT)) for i in __located_extensions__: if i in __extensions__: extensions_xml += "<strong>" + i + "</strong>" else: extensions_xml += i extensions_xml += " " extensions_xml += "</p></div></div>" print(extensions_xml) def output_text(self): if __located_extensions__: print("\n" + textwrap.fill("{0} {1}:".format(_(EXTENSIONS_INFO_TEXT), _(EXTENSIONS_MARKED_TEXT)), width=terminal.get_size()[0])) for i in __located_extensions__: if i in __extensions__: print("[" + terminal.__bold__ + i + terminal.__normal__ + "]", end=" ") else: print (i, end=" ") print("") def output_xml(self): if __located_extensions__: message_xml = "\t\t<message>" + _(EXTENSIONS_INFO_TEXT) + "</message>\n" used_extensions_xml = "" unused_extensions_xml = "" for i in __located_extensions__: if i in __extensions__: used_extensions_xml += "\t\t\t<extension>" + i + "</extension>\n" else: unused_extensions_xml += "\t\t\t<extension>" + i + "</extension>\n" print("\t<extensions>\n" + message_xml + "\t\t<used>\n" + used_extensions_xml + "\t\t</used>\n" + "\t\t<unused>\n" + unused_extensions_xml + "\t\t</unused>\n" + "\t</extensions>")
gpl-3.0
tornadozou/tensorflow
tensorflow/contrib/training/python/training/training_test.py
44
23611
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tf.contrib.training.training.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import numpy as np from tensorflow.contrib.framework.python.ops import variables as variables_lib from tensorflow.contrib.layers.python.layers import layers from tensorflow.contrib.training.python.training import training from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import random_seed from tensorflow.python.ops import gradients_impl from tensorflow.python.ops import math_ops from tensorflow.python.ops import variables as variables_lib2 from tensorflow.python.ops.losses import losses from tensorflow.python.platform import gfile from tensorflow.python.platform import test from tensorflow.python.training import basic_session_run_hooks from tensorflow.python.training import gradient_descent from tensorflow.python.training import monitored_session from tensorflow.python.training import saver as saver_lib # pylint: enable=g-import-not-at-top def logistic_classifier(inputs): return layers.fully_connected(inputs, 1, activation_fn=math_ops.sigmoid) def batchnorm_classifier(inputs): inputs = layers.batch_norm(inputs, decay=0.1, fused=False) return layers.fully_connected(inputs, 1, activation_fn=math_ops.sigmoid) class ClipGradsTest(test.TestCase): def testClipGrads(self): xs = variables_lib2.Variable(0.0) ys = xs * 4.0 grads = gradients_impl.gradients([ys], [xs]) gradients_to_variables = list(zip(grads, [xs])) clipped_gradients_to_variables = training.clip_gradient_norms( gradients_to_variables, 3.0) with self.test_session() as session: session.run(variables_lib2.global_variables_initializer()) self.assertAlmostEqual(4.0, gradients_to_variables[0][0].eval()) self.assertAlmostEqual(3.0, clipped_gradients_to_variables[0][0].eval()) def testClipGradsFn(self): xs = variables_lib2.Variable(0.0) ys = xs * 4.0 grads = gradients_impl.gradients([ys], [xs]) gradients_to_variables = list(zip(grads, [xs])) clipped_gradients_to_variables = training.clip_gradient_norms_fn(3.0)( gradients_to_variables) with self.test_session() as session: session.run(variables_lib2.global_variables_initializer()) self.assertAlmostEqual(4.0, gradients_to_variables[0][0].eval()) self.assertAlmostEqual(3.0, clipped_gradients_to_variables[0][0].eval()) class CreateTrainOpTest(test.TestCase): def setUp(self): np.random.seed(0) # Create an easy training set: self._inputs = np.random.rand(16, 4).astype(np.float32) self._labels = np.random.randint(0, 2, size=(16, 1)).astype(np.float32) def testTrainOpInCollection(self): with ops.Graph().as_default(): tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = batchnorm_classifier(tf_inputs) loss = losses.log_loss(tf_labels, tf_predictions) optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = training.create_train_op(loss, optimizer) # Make sure the training op was recorded in the proper collection self.assertTrue(train_op in ops.get_collection(ops.GraphKeys.TRAIN_OP)) def testUseUpdateOps(self): with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) expected_mean = np.mean(self._inputs, axis=(0)) expected_var = np.var(self._inputs, axis=(0)) tf_predictions = batchnorm_classifier(tf_inputs) loss = losses.log_loss(tf_labels, tf_predictions) optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = training.create_train_op(loss, optimizer) moving_mean = variables_lib.get_variables_by_name('moving_mean')[0] moving_variance = variables_lib.get_variables_by_name('moving_variance')[ 0] with self.test_session() as session: # Initialize all variables session.run(variables_lib2.global_variables_initializer()) mean, variance = session.run([moving_mean, moving_variance]) # After initialization moving_mean == 0 and moving_variance == 1. self.assertAllClose(mean, [0] * 4) self.assertAllClose(variance, [1] * 4) for _ in range(10): session.run(train_op) mean = moving_mean.eval() variance = moving_variance.eval() # After 10 updates with decay 0.1 moving_mean == expected_mean and # moving_variance == expected_var. self.assertAllClose(mean, expected_mean) self.assertAllClose(variance, expected_var) def testEmptyUpdateOps(self): with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = batchnorm_classifier(tf_inputs) loss = losses.log_loss(tf_labels, tf_predictions) optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = training.create_train_op(loss, optimizer, update_ops=[]) moving_mean = variables_lib.get_variables_by_name('moving_mean')[0] moving_variance = variables_lib.get_variables_by_name('moving_variance')[ 0] with self.test_session() as session: # Initialize all variables session.run(variables_lib2.global_variables_initializer()) mean, variance = session.run([moving_mean, moving_variance]) # After initialization moving_mean == 0 and moving_variance == 1. self.assertAllClose(mean, [0] * 4) self.assertAllClose(variance, [1] * 4) for _ in range(10): session.run(train_op) mean = moving_mean.eval() variance = moving_variance.eval() # Since we skip update_ops the moving_vars are not updated. self.assertAllClose(mean, [0] * 4) self.assertAllClose(variance, [1] * 4) def testGlobalStepIsIncrementedByDefault(self): with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = batchnorm_classifier(tf_inputs) loss = losses.log_loss(tf_labels, tf_predictions) optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = training.create_train_op(loss, optimizer) global_step = variables_lib.get_or_create_global_step() with self.test_session() as session: # Initialize all variables session.run(variables_lib2.global_variables_initializer()) for _ in range(10): session.run(train_op) # After 10 updates global_step should be 10. self.assertAllClose(global_step.eval(), 10) def testGlobalStepNotIncrementedWhenSetToNone(self): with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = batchnorm_classifier(tf_inputs) loss = losses.log_loss(tf_labels, tf_predictions) optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = training.create_train_op(loss, optimizer, global_step=None) global_step = variables_lib.get_or_create_global_step() with self.test_session() as session: # Initialize all variables session.run(variables_lib2.global_variables_initializer()) for _ in range(10): session.run(train_op) # Since train_op don't use global_step it shouldn't change. self.assertAllClose(global_step.eval(), 0) class TrainBatchNormClassifierTest(test.TestCase): def setUp(self): # Create an easy training set: np.random.seed(0) self._inputs = np.zeros((16, 4)) self._labels = np.random.randint(0, 2, size=(16, 1)).astype(np.float32) for i in range(16): j = int(2 * self._labels[i] + np.random.randint(0, 2)) self._inputs[i, j] = 1 def testTrainWithNoInitAssignCanAchieveZeroLoss(self): with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = batchnorm_classifier(tf_inputs) losses.log_loss(tf_labels, tf_predictions) total_loss = losses.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = training.create_train_op(total_loss, optimizer) loss = training.train( train_op, None, hooks=[basic_session_run_hooks.StopAtStepHook(num_steps=300)], save_summaries_steps=None, save_checkpoint_secs=None) self.assertLess(loss, .1) class TrainTest(test.TestCase): def setUp(self): # Create an easy training set: np.random.seed(0) self._inputs = np.zeros((16, 4)) self._labels = np.random.randint(0, 2, size=(16, 1)).astype(np.float32) for i in range(16): j = int(2 * self._labels[i] + np.random.randint(0, 2)) self._inputs[i, j] = 1 def testCanAchieveZeroLoss(self): with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = logistic_classifier(tf_inputs) losses.log_loss(tf_labels, tf_predictions) total_loss = losses.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = training.create_train_op(total_loss, optimizer) loss = training.train( train_op, None, hooks=[basic_session_run_hooks.StopAtStepHook(num_steps=300)], save_summaries_steps=None, save_checkpoint_secs=None) self.assertIsNotNone(loss) self.assertLess(loss, .015) def testTrainWithLocalVariable(self): with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) local_multiplier = variables_lib.local_variable(1.0) tf_predictions = logistic_classifier(tf_inputs) * local_multiplier losses.log_loss(tf_labels, tf_predictions) total_loss = losses.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = training.create_train_op(total_loss, optimizer) loss = training.train( train_op, None, hooks=[basic_session_run_hooks.StopAtStepHook(num_steps=300)], save_summaries_steps=None, save_checkpoint_secs=None) self.assertIsNotNone(loss) self.assertLess(loss, .015) def testResumeTrainAchievesRoughlyTheSameLoss(self): number_of_steps = [300, 1, 5] logdir = os.path.join(self.get_temp_dir(), 'resume_train_same_loss') for i in range(len(number_of_steps)): with ops.Graph().as_default(): random_seed.set_random_seed(i) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = logistic_classifier(tf_inputs) losses.log_loss(tf_labels, tf_predictions) total_loss = losses.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = training.create_train_op(total_loss, optimizer) saver = saver_lib.Saver() loss = training.train( train_op, logdir, hooks=[ basic_session_run_hooks.StopAtStepHook( num_steps=number_of_steps[i]), basic_session_run_hooks.CheckpointSaverHook( logdir, save_steps=50, saver=saver), ], save_checkpoint_secs=None, save_summaries_steps=None) self.assertIsNotNone(loss) self.assertLess(loss, .015) def create_train_op(self, learning_rate=1.0, gradient_multiplier=1.0): tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = logistic_classifier(tf_inputs) losses.log_loss(tf_labels, tf_predictions) total_loss = losses.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer( learning_rate=learning_rate) def transform_grads_fn(grads): if gradient_multiplier != 1.0: variables = variables_lib2.trainable_variables() gradient_multipliers = {var: gradient_multiplier for var in variables} with ops.name_scope('multiply_grads'): return training.multiply_gradients(grads, gradient_multipliers) else: return grads return training.create_train_op( total_loss, optimizer, transform_grads_fn=transform_grads_fn) def testTrainWithInitFromCheckpoint(self): logdir1 = os.path.join(self.get_temp_dir(), 'tmp_logs1/') logdir2 = os.path.join(self.get_temp_dir(), 'tmp_logs2/') if gfile.Exists(logdir1): # For running on jenkins. gfile.DeleteRecursively(logdir1) if gfile.Exists(logdir2): # For running on jenkins. gfile.DeleteRecursively(logdir2) # First, train the model one step (make sure the error is high). with ops.Graph().as_default(): random_seed.set_random_seed(0) train_op = self.create_train_op() saver = saver_lib.Saver() loss = training.train( train_op, logdir1, hooks=[ basic_session_run_hooks.CheckpointSaverHook( logdir1, save_steps=1, saver=saver), basic_session_run_hooks.StopAtStepHook(num_steps=1), ], save_checkpoint_secs=None, save_summaries_steps=None) self.assertGreater(loss, .5) # Next, train the model to convergence. with ops.Graph().as_default(): random_seed.set_random_seed(1) train_op = self.create_train_op() saver = saver_lib.Saver() loss = training.train( train_op, logdir1, hooks=[ basic_session_run_hooks.CheckpointSaverHook( logdir1, save_steps=300, saver=saver), basic_session_run_hooks.StopAtStepHook(num_steps=300), ], save_checkpoint_secs=None, save_summaries_steps=None) self.assertIsNotNone(loss) self.assertLess(loss, .02) # Finally, advance the model a single step and validate that the loss is # still low. with ops.Graph().as_default(): random_seed.set_random_seed(2) train_op = self.create_train_op() model_variables = variables_lib2.global_variables() model_path = saver_lib.latest_checkpoint(logdir1) assign_fn = variables_lib.assign_from_checkpoint_fn( model_path, model_variables) def init_fn(_, session): assign_fn(session) loss = training.train( train_op, None, scaffold=monitored_session.Scaffold(init_fn=init_fn), hooks=[basic_session_run_hooks.StopAtStepHook(num_steps=1)], save_checkpoint_secs=None, save_summaries_steps=None) self.assertIsNotNone(loss) self.assertLess(loss, .02) def ModelLoss(self): tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = logistic_classifier(tf_inputs) losses.log_loss(tf_labels, tf_predictions) return losses.get_total_loss() def testTrainAllVarsHasLowerLossThanTrainSubsetOfVars(self): logdir = os.path.join(self.get_temp_dir(), 'tmp_logs3/') if gfile.Exists(logdir): # For running on jenkins. gfile.DeleteRecursively(logdir) # First, train only the weights of the model. with ops.Graph().as_default(): random_seed.set_random_seed(0) total_loss = self.ModelLoss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) weights = variables_lib.get_variables_by_name('weights') train_op = training.create_train_op( total_loss, optimizer, variables_to_train=weights) saver = saver_lib.Saver() loss = training.train( train_op, logdir, hooks=[ basic_session_run_hooks.CheckpointSaverHook( logdir, save_steps=200, saver=saver), basic_session_run_hooks.StopAtStepHook(num_steps=200), ], save_checkpoint_secs=None, save_summaries_steps=None) self.assertGreater(loss, .015) self.assertLess(loss, .05) # Next, train the biases of the model. with ops.Graph().as_default(): random_seed.set_random_seed(1) total_loss = self.ModelLoss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) biases = variables_lib.get_variables_by_name('biases') train_op = training.create_train_op( total_loss, optimizer, variables_to_train=biases) saver = saver_lib.Saver() loss = training.train( train_op, logdir, hooks=[ basic_session_run_hooks.CheckpointSaverHook( logdir, save_steps=300, saver=saver), basic_session_run_hooks.StopAtStepHook(num_steps=300), ], save_checkpoint_secs=None, save_summaries_steps=None) self.assertGreater(loss, .015) self.assertLess(loss, .05) # Finally, train both weights and bias to get lower loss. with ops.Graph().as_default(): random_seed.set_random_seed(2) total_loss = self.ModelLoss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = training.create_train_op(total_loss, optimizer) saver = saver_lib.Saver() loss = training.train( train_op, logdir, hooks=[ basic_session_run_hooks.StopAtStepHook(num_steps=400), ], save_checkpoint_secs=None, save_summaries_steps=None) self.assertIsNotNone(loss) self.assertLess(loss, .015) def testTrainingSubsetsOfVariablesOnlyUpdatesThoseVariables(self): # First, train only the weights of the model. with ops.Graph().as_default(): random_seed.set_random_seed(0) total_loss = self.ModelLoss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) weights, biases = variables_lib.get_variables() train_op = training.create_train_op(total_loss, optimizer) train_weights = training.create_train_op( total_loss, optimizer, variables_to_train=[weights]) train_biases = training.create_train_op( total_loss, optimizer, variables_to_train=[biases]) with self.test_session() as session: # Initialize the variables. session.run(variables_lib2.global_variables_initializer()) # Get the initial weights and biases values. weights_values, biases_values = session.run([weights, biases]) self.assertGreater(np.linalg.norm(weights_values), 0) self.assertAlmostEqual(np.linalg.norm(biases_values), 0) # Update weights and biases. loss = session.run(train_op) self.assertGreater(loss, .5) new_weights, new_biases = session.run([weights, biases]) # Check that the weights and biases have been updated. self.assertGreater(np.linalg.norm(weights_values - new_weights), 0) self.assertGreater(np.linalg.norm(biases_values - new_biases), 0) weights_values, biases_values = new_weights, new_biases # Update only weights. loss = session.run(train_weights) self.assertGreater(loss, .5) new_weights, new_biases = session.run([weights, biases]) # Check that the weights have been updated, but biases have not. self.assertGreater(np.linalg.norm(weights_values - new_weights), 0) self.assertAlmostEqual(np.linalg.norm(biases_values - new_biases), 0) weights_values = new_weights # Update only biases. loss = session.run(train_biases) self.assertGreater(loss, .5) new_weights, new_biases = session.run([weights, biases]) # Check that the biases have been updated, but weights have not. self.assertAlmostEqual(np.linalg.norm(weights_values - new_weights), 0) self.assertGreater(np.linalg.norm(biases_values - new_biases), 0) def testTrainWithAlteredGradients(self): # Use the same learning rate but different gradient multipliers # to train two models. Model with equivalently larger learning # rate (i.e., learning_rate * gradient_multiplier) has smaller # training loss. multipliers = [1., 1000.] number_of_steps = 10 learning_rate = 0.001 # First, train the model with equivalently smaller learning rate. with ops.Graph().as_default(): random_seed.set_random_seed(0) train_op = self.create_train_op( learning_rate=learning_rate, gradient_multiplier=multipliers[0]) loss0 = training.train( train_op, None, hooks=[ basic_session_run_hooks.StopAtStepHook(num_steps=number_of_steps), ], save_checkpoint_secs=None, save_summaries_steps=None) self.assertIsNotNone(loss0) self.assertGreater(loss0, .5) # Second, train the model with equivalently larger learning rate. with ops.Graph().as_default(): random_seed.set_random_seed(0) train_op = self.create_train_op( learning_rate=learning_rate, gradient_multiplier=multipliers[1]) loss1 = training.train( train_op, None, hooks=[ basic_session_run_hooks.StopAtStepHook(num_steps=number_of_steps), ], save_checkpoint_secs=None, save_summaries_steps=None) self.assertIsNotNone(loss1) self.assertLess(loss1, .5) # The loss of the model trained with larger learning rate should # be smaller. self.assertGreater(loss0, loss1) if __name__ == '__main__': test.main()
apache-2.0
samdroid-apps/sugar
src/jarabe/frame/zoomtoolbar.py
13
4263
# Copyright (C) 2006-2007 Red Hat, Inc. # Copyright (C) 2009 Simon Schampijer # # 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 St, Fifth Floor, Boston, MA 02110-1301 USA from gettext import gettext as _ import logging from gi.repository import GLib from gi.repository import Gtk from gi.repository import GObject from sugar3.graphics import style from sugar3.graphics.palette import Palette from sugar3.graphics.radiotoolbutton import RadioToolButton from jarabe.frame.frameinvoker import FrameWidgetInvoker from jarabe.model import shell class ZoomToolbar(Gtk.Toolbar): __gsignals__ = { 'level-clicked': (GObject.SignalFlags.RUN_FIRST, None, ([])) } def __init__(self): Gtk.Toolbar.__init__(self) # we shouldn't be mirrored in RTL locales self.set_direction(Gtk.TextDirection.LTR) # ask not to be collapsed if possible self.set_size_request(4 * style.GRID_CELL_SIZE, -1) self._mesh_button = self._add_button('zoom-neighborhood', _('Neighborhood'), _('F1'), shell.ShellModel.ZOOM_MESH) self._groups_button = self._add_button('zoom-groups', _('Group'), _('F2'), shell.ShellModel.ZOOM_GROUP) self._home_button = self._add_button('zoom-home', _('Home'), _('F3'), shell.ShellModel.ZOOM_HOME) self._activity_button = \ self._add_button('zoom-activity', _('Activity'), _('F4'), shell.ShellModel.ZOOM_ACTIVITY) shell_model = shell.get_model() self._set_zoom_level(shell_model.zoom_level) shell_model.zoom_level_changed.connect(self.__zoom_level_changed_cb) def _add_button(self, icon_name, label, accelerator, zoom_level): if self.get_children(): group = self.get_children()[0] else: group = None button = RadioToolButton(icon_name=icon_name, group=group, accelerator=accelerator) button.connect('clicked', self.__level_clicked_cb, zoom_level) self.add(button) button.show() palette = Palette(GLib.markup_escape_text(label)) palette.props.invoker = FrameWidgetInvoker(button) palette.set_group_id('frame') button.set_palette(palette) return button def __level_clicked_cb(self, button, level): if not button.get_active(): return shell.get_model().set_zoom_level(level) self.emit('level-clicked') def __zoom_level_changed_cb(self, **kwargs): self._set_zoom_level(kwargs['new_level']) def _set_zoom_level(self, new_level): logging.debug('new zoom level: %r', new_level) if new_level == shell.ShellModel.ZOOM_MESH: self._mesh_button.props.active = True elif new_level == shell.ShellModel.ZOOM_GROUP: self._groups_button.props.active = True elif new_level == shell.ShellModel.ZOOM_HOME: self._home_button.props.active = True elif new_level == shell.ShellModel.ZOOM_ACTIVITY: self._activity_button.props.active = True else: raise ValueError('Invalid zoom level: %r' % (new_level))
gpl-2.0
patriciolobos/desa8
openerp/addons/portal_sale/__openerp__.py
380
2183
# -*- 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/>. # ############################################################################## { 'name': 'Portal Sale', 'version': '0.1', 'category': 'Tools', 'complexity': 'easy', 'description': """ This module adds a Sales menu to your portal as soon as sale and portal are installed. ====================================================================================== After installing this module, portal users will be able to access their own documents via the following menus: - Quotations - Sale Orders - Delivery Orders - Products (public ones) - Invoices - Payments/Refunds If online payment acquirers are configured, portal users will also be given the opportunity to pay online on their Sale Orders and Invoices that are not paid yet. Paypal is included by default, you simply need to configure a Paypal account in the Accounting/Invoicing settings. """, 'author': 'OpenERP SA', 'depends': ['sale', 'portal', 'payment'], 'data': [ 'security/portal_security.xml', 'portal_sale_view.xml', 'portal_sale_data.xml', 'res_config_view.xml', 'security/ir.model.access.csv', ], 'auto_install': True, 'category': 'Hidden', } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
SergeyPirogov/ghost
node_modules/grunt-docker/node_modules/docker/node_modules/pygmentize-bundled/vendor/pygments/scripts/find_error.py
117
5927
#!/usr/bin/python # -*- coding: utf-8 -*- """ Lexing error finder ~~~~~~~~~~~~~~~~~~~ For the source files given on the command line, display the text where Error tokens are being generated, along with some context. :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import sys, os # always prefer Pygments from source if exists srcpath = os.path.join(os.path.dirname(__file__), '..') if os.path.isdir(os.path.join(srcpath, 'pygments')): sys.path.insert(0, srcpath) from pygments.lexer import RegexLexer from pygments.lexers import get_lexer_for_filename, get_lexer_by_name from pygments.token import Error, Text, _TokenType from pygments.cmdline import _parse_options class DebuggingRegexLexer(RegexLexer): """Make the state stack, position and current match instance attributes.""" def get_tokens_unprocessed(self, text, stack=('root',)): """ Split ``text`` into (tokentype, text) pairs. ``stack`` is the inital stack (default: ``['root']``) """ self.pos = 0 tokendefs = self._tokens self.statestack = list(stack) statetokens = tokendefs[self.statestack[-1]] while 1: for rexmatch, action, new_state in statetokens: self.m = m = rexmatch(text, self.pos) if m: if type(action) is _TokenType: yield self.pos, action, m.group() else: for item in action(self, m): yield item self.pos = m.end() if new_state is not None: # state transition if isinstance(new_state, tuple): for state in new_state: if state == '#pop': self.statestack.pop() elif state == '#push': self.statestack.append(self.statestack[-1]) else: self.statestack.append(state) elif isinstance(new_state, int): # pop del self.statestack[new_state:] elif new_state == '#push': self.statestack.append(self.statestack[-1]) else: assert False, 'wrong state def: %r' % new_state statetokens = tokendefs[self.statestack[-1]] break else: try: if text[self.pos] == '\n': # at EOL, reset state to 'root' self.pos += 1 self.statestack = ['root'] statetokens = tokendefs['root'] yield self.pos, Text, u'\n' continue yield self.pos, Error, text[self.pos] self.pos += 1 except IndexError: break def main(fn, lexer=None, options={}): if lexer is not None: lx = get_lexer_by_name(lexer) else: try: lx = get_lexer_for_filename(os.path.basename(fn), **options) except ValueError: try: name, rest = fn.split('_', 1) lx = get_lexer_by_name(name, **options) except ValueError: raise AssertionError('no lexer found for file %r' % fn) debug_lexer = False # does not work for e.g. ExtendedRegexLexers if lx.__class__.__bases__ == (RegexLexer,): lx.__class__.__bases__ = (DebuggingRegexLexer,) debug_lexer = True elif lx.__class__.__bases__ == (DebuggingRegexLexer,): # already debugged before debug_lexer = True lno = 1 text = file(fn, 'U').read() text = text.strip('\n') + '\n' tokens = [] states = [] def show_token(tok, state): reprs = map(repr, tok) print ' ' + reprs[1] + ' ' + ' ' * (29-len(reprs[1])) + reprs[0], if debug_lexer: print ' ' + ' ' * (29-len(reprs[0])) + repr(state), print for type, val in lx.get_tokens(text): lno += val.count('\n') if type == Error: print 'Error parsing', fn, 'on line', lno print 'Previous tokens' + (debug_lexer and ' and states' or '') + ':' if showall: for tok, state in map(None, tokens, states): show_token(tok, state) else: for i in range(max(len(tokens) - num, 0), len(tokens)): show_token(tokens[i], states[i]) print 'Error token:' l = len(repr(val)) print ' ' + repr(val), if debug_lexer and hasattr(lx, 'statestack'): print ' ' * (60-l) + repr(lx.statestack), print print return 1 tokens.append((type, val)) if debug_lexer: if hasattr(lx, 'statestack'): states.append(lx.statestack[:]) else: states.append(None) if showall: for tok, state in map(None, tokens, states): show_token(tok, state) return 0 num = 10 showall = False lexer = None options = {} if __name__ == '__main__': import getopt opts, args = getopt.getopt(sys.argv[1:], 'n:l:aO:') for opt, val in opts: if opt == '-n': num = int(val) elif opt == '-a': showall = True elif opt == '-l': lexer = val elif opt == '-O': options = _parse_options([val]) ret = 0 for f in args: ret += main(f, lexer, options) sys.exit(bool(ret))
mit
hryamzik/ansible
test/units/plugins/lookup/test_aws_ssm.py
40
6486
# # (c) 2017 Michael De La Rue # # 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) import pytest from copy import copy from ansible.errors import AnsibleError import ansible.plugins.lookup.aws_ssm as aws_ssm try: import boto3 from botocore.exceptions import ClientError except ImportError: pytestmark = pytest.mark.skip("This test requires the boto3 and botocore Python libraries") simple_variable_success_response = { 'Parameters': [ { 'Name': 'simple_variable', 'Type': 'String', 'Value': 'simplevalue', 'Version': 1 } ], 'InvalidParameters': [], 'ResponseMetadata': { 'RequestId': '12121212-3434-5656-7878-9a9a9a9a9a9a', 'HTTPStatusCode': 200, 'HTTPHeaders': { 'x-amzn-requestid': '12121212-3434-5656-7878-9a9a9a9a9a9a', 'content-type': 'application/x-amz-json-1.1', 'content-length': '116', 'date': 'Tue, 23 Jan 2018 11:04:27 GMT' }, 'RetryAttempts': 0 } } path_success_response = copy(simple_variable_success_response) path_success_response['Parameters'] = [ {'Name': '/testpath/too', 'Type': 'String', 'Value': 'simple_value_too', 'Version': 1}, {'Name': '/testpath/won', 'Type': 'String', 'Value': 'simple_value_won', 'Version': 1} ] missing_variable_response = copy(simple_variable_success_response) missing_variable_response['Parameters'] = [] missing_variable_response['InvalidParameters'] = ['missing_variable'] some_missing_variable_response = copy(simple_variable_success_response) some_missing_variable_response['Parameters'] = [ {'Name': 'simple', 'Type': 'String', 'Value': 'simple_value', 'Version': 1}, {'Name': '/testpath/won', 'Type': 'String', 'Value': 'simple_value_won', 'Version': 1} ] some_missing_variable_response['InvalidParameters'] = ['missing_variable'] dummy_credentials = {} dummy_credentials['boto_profile'] = None dummy_credentials['aws_secret_key'] = "notasecret" dummy_credentials['aws_access_key'] = "notakey" dummy_credentials['aws_security_token'] = None dummy_credentials['region'] = 'eu-west-1' def test_lookup_variable(mocker): lookup = aws_ssm.LookupModule() lookup._load_name = "aws_ssm" boto3_double = mocker.MagicMock() boto3_double.Session.return_value.client.return_value.get_parameters.return_value = simple_variable_success_response boto3_client_double = boto3_double.Session.return_value.client with mocker.patch.object(boto3, 'session', boto3_double): retval = lookup.run(["simple_variable"], {}, **dummy_credentials) assert(retval[0] == "simplevalue") boto3_client_double.assert_called_with('ssm', 'eu-west-1', aws_access_key_id='notakey', aws_secret_access_key="notasecret", aws_session_token=None) def test_path_lookup_variable(mocker): lookup = aws_ssm.LookupModule() lookup._load_name = "aws_ssm" boto3_double = mocker.MagicMock() get_path_fn = boto3_double.Session.return_value.client.return_value.get_parameters_by_path get_path_fn.return_value = path_success_response boto3_client_double = boto3_double.Session.return_value.client with mocker.patch.object(boto3, 'session', boto3_double): args = copy(dummy_credentials) args["bypath"] = 'true' retval = lookup.run(["/testpath"], {}, **args) assert(retval[0]["/testpath/won"] == "simple_value_won") assert(retval[0]["/testpath/too"] == "simple_value_too") boto3_client_double.assert_called_with('ssm', 'eu-west-1', aws_access_key_id='notakey', aws_secret_access_key="notasecret", aws_session_token=None) get_path_fn.assert_called_with(Path="/testpath", Recursive=False, WithDecryption=True) def test_return_none_for_missing_variable(mocker): """ during jinja2 templates, we can't shouldn't normally raise exceptions since this blocks the ability to use defaults. for this reason we return ```None``` for missing variables """ lookup = aws_ssm.LookupModule() lookup._load_name = "aws_ssm" boto3_double = mocker.MagicMock() boto3_double.Session.return_value.client.return_value.get_parameters.return_value = missing_variable_response with mocker.patch.object(boto3, 'session', boto3_double): retval = lookup.run(["missing_variable"], {}, **dummy_credentials) assert(retval[0] is None) def test_match_retvals_to_call_params_even_with_some_missing_variables(mocker): """ If we get a complex list of variables with some missing and some not, we still have to return a list which matches with the original variable list. """ lookup = aws_ssm.LookupModule() lookup._load_name = "aws_ssm" boto3_double = mocker.MagicMock() boto3_double.Session.return_value.client.return_value.get_parameters.return_value = some_missing_variable_response with mocker.patch.object(boto3, 'session', boto3_double): retval = lookup.run(["simple", "missing_variable", "/testpath/won", "simple"], {}, **dummy_credentials) assert(retval == ["simple_value", None, "simple_value_won", "simple_value"]) error_response = {'Error': {'Code': 'ResourceNotFoundException', 'Message': 'Fake Testing Error'}} operation_name = 'FakeOperation' def test_warn_denied_variable(mocker): lookup = aws_ssm.LookupModule() lookup._load_name = "aws_ssm" boto3_double = mocker.MagicMock() boto3_double.Session.return_value.client.return_value.get_parameters.side_effect = ClientError(error_response, operation_name) with pytest.raises(AnsibleError): with mocker.patch.object(boto3, 'session', boto3_double): lookup.run(["denied_variable"], {}, **dummy_credentials)
gpl-3.0
laszlocsomor/tensorflow
tensorflow/python/framework/errors.py
141
2322
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Exception types for TensorFlow errors.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=unused-import from tensorflow.python.framework import errors_impl as _impl # pylint: enable=unused-import # go/tf-wildcard-import # pylint: disable=wildcard-import from tensorflow.python.framework.errors_impl import * # pylint: enable=wildcard-import from tensorflow.python.util.all_util import remove_undocumented # These are referenced in client/client_lib.py. # Unfortunately, we can't import client_lib to examine # the references, since it would create a dependency cycle. _allowed_symbols = [ "AbortedError", "AlreadyExistsError", "CancelledError", "DataLossError", "DeadlineExceededError", "FailedPreconditionError", "InternalError", "InvalidArgumentError", "NotFoundError", "OpError", "OutOfRangeError", "PermissionDeniedError", "ResourceExhaustedError", "UnauthenticatedError", "UnavailableError", "UnimplementedError", "UnknownError", "error_code_from_exception_type", "exception_type_from_error_code", "raise_exception_on_not_ok_status", # Scalars that have no docstrings: "OK", "CANCELLED", "UNKNOWN", "INVALID_ARGUMENT", "DEADLINE_EXCEEDED", "NOT_FOUND", "ALREADY_EXISTS", "PERMISSION_DENIED", "UNAUTHENTICATED", "RESOURCE_EXHAUSTED", "FAILED_PRECONDITION", "ABORTED", "OUT_OF_RANGE", "UNIMPLEMENTED", "INTERNAL", "UNAVAILABLE", "DATA_LOSS", ] remove_undocumented(__name__, _allowed_symbols)
apache-2.0
zhouzhenghui/python-for-android
python-build/python-libs/gdata/src/gdata/tlslite/__init__.py
409
1129
""" TLS Lite is a free python library that implements SSL v3, TLS v1, and TLS v1.1. TLS Lite supports non-traditional authentication methods such as SRP, shared keys, and cryptoIDs, in addition to X.509 certificates. TLS Lite is pure python, however it can access OpenSSL, cryptlib, pycrypto, and GMPY for faster crypto operations. TLS Lite integrates with httplib, xmlrpclib, poplib, imaplib, smtplib, SocketServer, asyncore, and Twisted. To use, do:: from tlslite.api import * Then use the L{tlslite.TLSConnection.TLSConnection} class with a socket, or use one of the integration classes in L{tlslite.integration}. @version: 0.3.8 """ __version__ = "0.3.8" __all__ = ["api", "BaseDB", "Checker", "constants", "errors", "FileObject", "HandshakeSettings", "mathtls", "messages", "Session", "SessionCache", "SharedKeyDB", "TLSConnection", "TLSRecordLayer", "VerifierDB", "X509", "X509CertChain", "integration", "utils"]
apache-2.0
potatolondon/django-nonrel-1-4
django/template/response.py
93
6205
from django.http import HttpResponse from django.template import loader, Context, RequestContext class ContentNotRenderedError(Exception): pass class SimpleTemplateResponse(HttpResponse): rendering_attrs = ['template_name', 'context_data', '_post_render_callbacks'] def __init__(self, template, context=None, mimetype=None, status=None, content_type=None): # It would seem obvious to call these next two members 'template' and # 'context', but those names are reserved as part of the test Client # API. To avoid the name collision, we use tricky-to-debug problems self.template_name = template self.context_data = context self._post_render_callbacks = [] # content argument doesn't make sense here because it will be replaced # with rendered template so we always pass empty string in order to # prevent errors and provide shorter signature. super(SimpleTemplateResponse, self).__init__('', mimetype, status, content_type) # _is_rendered tracks whether the template and context has been baked # into a final response. # Super __init__ doesn't know any better than to set self.content to # the empty string we just gave it, which wrongly sets _is_rendered # True, so we initialize it to False after the call to super __init__. self._is_rendered = False def __getstate__(self): """Pickling support function. Ensures that the object can't be pickled before it has been rendered, and that the pickled state only includes rendered data, not the data used to construct the response. """ obj_dict = self.__dict__.copy() if not self._is_rendered: raise ContentNotRenderedError('The response content must be ' 'rendered before it can be pickled.') for attr in self.rendering_attrs: if attr in obj_dict: del obj_dict[attr] return obj_dict def resolve_template(self, template): "Accepts a template object, path-to-template or list of paths" if isinstance(template, (list, tuple)): return loader.select_template(template) elif isinstance(template, basestring): return loader.get_template(template) else: return template def resolve_context(self, context): """Converts context data into a full Context object (assuming it isn't already a Context object). """ if isinstance(context, Context): return context else: return Context(context) @property def rendered_content(self): """Returns the freshly rendered content for the template and context described by the TemplateResponse. This *does not* set the final content of the response. To set the response content, you must either call render(), or set the content explicitly using the value of this property. """ template = self.resolve_template(self.template_name) context = self.resolve_context(self.context_data) content = template.render(context) return content def add_post_render_callback(self, callback): """Adds a new post-rendering callback. If the response has already been rendered, invoke the callback immediately. """ if self._is_rendered: callback(self) else: self._post_render_callbacks.append(callback) def render(self): """Renders (thereby finalizing) the content of the response. If the content has already been rendered, this is a no-op. Returns the baked response instance. """ retval = self if not self._is_rendered: self._set_content(self.rendered_content) for post_callback in self._post_render_callbacks: newretval = post_callback(retval) if newretval is not None: retval = newretval return retval @property def is_rendered(self): return self._is_rendered def __iter__(self): if not self._is_rendered: raise ContentNotRenderedError('The response content must be ' 'rendered before it can be iterated over.') return super(SimpleTemplateResponse, self).__iter__() def _get_content(self): if not self._is_rendered: raise ContentNotRenderedError('The response content must be ' 'rendered before it can be accessed.') return super(SimpleTemplateResponse, self)._get_content() def _set_content(self, value): """Sets the content for the response """ super(SimpleTemplateResponse, self)._set_content(value) self._is_rendered = True content = property(_get_content, _set_content) class TemplateResponse(SimpleTemplateResponse): rendering_attrs = SimpleTemplateResponse.rendering_attrs + \ ['_request', '_current_app'] def __init__(self, request, template, context=None, mimetype=None, status=None, content_type=None, current_app=None): # self.request gets over-written by django.test.client.Client - and # unlike context_data and template_name the _request should not # be considered part of the public API. self._request = request # As a convenience we'll allow callers to provide current_app without # having to avoid needing to create the RequestContext directly self._current_app = current_app super(TemplateResponse, self).__init__( template, context, mimetype, status, content_type) def resolve_context(self, context): """Convert context data into a full RequestContext object (assuming it isn't already a Context object). """ if isinstance(context, Context): return context return RequestContext(self._request, context, current_app=self._current_app)
bsd-3-clause
gechr/ansible-modules-extras
files/blockinfile.py
5
10001
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2014, 2015 YAEGASHI Takeshi <yaegashi@debian.org> # # 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/>. DOCUMENTATION = """ --- module: blockinfile author: - 'YAEGASHI Takeshi (@yaegashi)' extends_documentation_fragment: - files - validate short_description: Insert/update/remove a text block surrounded by marker lines. version_added: '2.0' description: - This module will insert/update/remove a block of multi-line text surrounded by customizable marker lines. notes: - This module supports check mode. - When using 'with_*' loops be aware that if you do not set a unique mark the block will be overwritten on each iteration. options: dest: aliases: [ name, destfile ] required: true description: - The file to modify. state: required: false choices: [ present, absent ] default: present description: - Whether the block should be there or not. marker: required: false default: '# {mark} ANSIBLE MANAGED BLOCK' description: - The marker line template. "{mark}" will be replaced with "BEGIN" or "END". block: aliases: [ content ] required: false default: '' description: - The text to insert inside the marker lines. If it's missing or an empty string, the block will be removed as if C(state) were specified to C(absent). insertafter: required: false default: EOF description: - If specified, the block will be inserted after the last match of specified regular expression. A special value is available; C(EOF) for inserting the block at the end of the file. If specified regular expresion has no matches, C(EOF) will be used instead. choices: [ 'EOF', '*regex*' ] insertbefore: required: false default: None description: - If specified, the block will be inserted before the last match of specified regular expression. A special value is available; C(BOF) for inserting the block at the beginning of the file. If specified regular expresion has no matches, the block will be inserted at the end of the file. choices: [ 'BOF', '*regex*' ] create: required: false default: 'no' choices: [ 'yes', 'no' ] description: - Create a new file if it doesn't exist. backup: required: false default: 'no' choices: [ 'yes', 'no' ] description: - Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly. follow: required: false default: "no" choices: [ "yes", "no" ] description: - 'This flag indicates that filesystem links, if they exist, should be followed.' version_added: "2.1" """ EXAMPLES = r""" - name: insert/update "Match User" configuation block in /etc/ssh/sshd_config blockinfile: dest: /etc/ssh/sshd_config block: | Match User ansible-agent PasswordAuthentication no - name: insert/update eth0 configuration stanza in /etc/network/interfaces (it might be better to copy files into /etc/network/interfaces.d/) blockinfile: dest: /etc/network/interfaces block: | iface eth0 inet static address 192.168.0.1 netmask 255.255.255.0 - name: insert/update HTML surrounded by custom markers after <body> line blockinfile: dest: /var/www/html/index.html marker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->" insertafter: "<body>" content: | <h1>Welcome to {{ansible_hostname}}</h1> <p>Last updated on {{ansible_date_time.iso8601}}</p> - name: remove HTML as well as surrounding markers blockinfile: dest: /var/www/html/index.html marker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->" content: "" - name: Add mappings to /etc/hosts blockinfile: dest: /etc/hosts block: | {{item.ip}} {{item.name}} marker: "# {mark} ANSIBLE MANAGED BLOCK {{item.name}}" with_items: - { name: host1, ip: 10.10.1.10 } - { name: host2, ip: 10.10.1.11 } - { name: host3, ip: 10.10.1.12 } """ import re import os import tempfile def write_changes(module, contents, dest): tmpfd, tmpfile = tempfile.mkstemp() f = os.fdopen(tmpfd, 'wb') f.write(contents) f.close() validate = module.params.get('validate', None) valid = not validate if validate: if "%s" not in validate: module.fail_json(msg="validate must contain %%s: %s" % (validate)) (rc, out, err) = module.run_command(validate % tmpfile) valid = rc == 0 if rc != 0: module.fail_json(msg='failed to validate: ' 'rc:%s error:%s' % (rc, err)) if valid: module.atomic_move(tmpfile, dest, unsafe_writes=module.params['unsafe_writes']) def check_file_attrs(module, changed, message): file_args = module.load_file_common_arguments(module.params) if module.set_file_attributes_if_different(file_args, False): if changed: message += " and " changed = True message += "ownership, perms or SE linux context changed" return message, changed def main(): module = AnsibleModule( argument_spec=dict( dest=dict(required=True, aliases=['name', 'destfile'], type='path'), state=dict(default='present', choices=['absent', 'present']), marker=dict(default='# {mark} ANSIBLE MANAGED BLOCK', type='str'), block=dict(default='', type='str', aliases=['content']), insertafter=dict(default=None), insertbefore=dict(default=None), create=dict(default=False, type='bool'), backup=dict(default=False, type='bool'), validate=dict(default=None, type='str'), ), mutually_exclusive=[['insertbefore', 'insertafter']], add_file_common_args=True, supports_check_mode=True ) params = module.params dest = params['dest'] if module.boolean(params.get('follow', None)): dest = os.path.realpath(dest) if os.path.isdir(dest): module.fail_json(rc=256, msg='Destination %s is a directory !' % dest) path_exists = os.path.exists(dest) if not path_exists: if not module.boolean(params['create']): module.fail_json(rc=257, msg='Destination %s does not exist !' % dest) original = None lines = [] else: f = open(dest, 'rb') original = f.read() f.close() lines = original.splitlines() insertbefore = params['insertbefore'] insertafter = params['insertafter'] block = params['block'] marker = params['marker'] present = params['state'] == 'present' if not present and not path_exists: module.exit_json(changed=False, msg="File not present") if insertbefore is None and insertafter is None: insertafter = 'EOF' if insertafter not in (None, 'EOF'): insertre = re.compile(insertafter) elif insertbefore not in (None, 'BOF'): insertre = re.compile(insertbefore) else: insertre = None marker0 = re.sub(r'{mark}', 'BEGIN', marker) marker1 = re.sub(r'{mark}', 'END', marker) if present and block: # Escape seqeuences like '\n' need to be handled in Ansible 1.x if module.ansible_version.startswith('1.'): block = re.sub('', block, '') blocklines = [marker0] + block.splitlines() + [marker1] else: blocklines = [] n0 = n1 = None for i, line in enumerate(lines): if line.startswith(marker0): n0 = i if line.startswith(marker1): n1 = i if None in (n0, n1): n0 = None if insertre is not None: for i, line in enumerate(lines): if insertre.search(line): n0 = i if n0 is None: n0 = len(lines) elif insertafter is not None: n0 += 1 elif insertbefore is not None: n0 = 0 # insertbefore=BOF else: n0 = len(lines) # insertafter=EOF elif n0 < n1: lines[n0:n1+1] = [] else: lines[n1:n0+1] = [] n0 = n1 lines[n0:n0] = blocklines if lines: result = '\n'.join(lines) if original and original.endswith('\n'): result += '\n' else: result = '' if original == result: msg = '' changed = False elif original is None: msg = 'File created' changed = True elif not blocklines: msg = 'Block removed' changed = True else: msg = 'Block inserted' changed = True if changed and not module.check_mode: if module.boolean(params['backup']) and path_exists: module.backup_local(dest) write_changes(module, result, dest) if module.check_mode and not path_exists: module.exit_json(changed=changed, msg=msg) msg, changed = check_file_attrs(module, changed, msg) module.exit_json(changed=changed, msg=msg) # import module snippets from ansible.module_utils.basic import * from ansible.module_utils.splitter import * if __name__ == '__main__': main()
gpl-3.0
obsoleter/suds
suds/umx/__init__.py
1
1849
# This program is free software; you can redistribute it and/or modify # it under the terms of the (LGPL) GNU Lesser General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library Lesser General Public License for more details at # ( http://www.gnu.org/licenses/lgpl.html ). # # You should have received a copy of the GNU Lesser General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # written by: Jeff Ortel ( jortel@redhat.com ) """ Provides modules containing classes to support unmarshalling (XML). """ from suds.sudsobject import Object class Content(Object): """ @ivar node: The content source node. @type node: L{sax.element.Element} @ivar data: The (optional) content data. @type data: L{Object} @ivar text: The (optional) content (xml) text. @type text: basestring """ extensions = [] def __init__(self, node, **kwargs): Object.__init__(self) self.node = node self.data = None self.text = None for k,v in list(kwargs.items()): setattr(self, k, v) def __getattr__(self, name): if name not in self.__dict__: if name in self.extensions: v = None setattr(self, name, v) else: raise AttributeError('Content has no attribute %s' % name) else: v = self.__dict__[name] return v
lgpl-3.0
rahul67/hue
desktop/core/ext-py/pysqlite/pysqlite2/test/userfunctions.py
45
13317
#-*- coding: ISO-8859-1 -*- # pysqlite2/test/userfunctions.py: tests for user-defined functions and # aggregates. # # Copyright (C) 2005-2007 Gerhard Häring <gh@ghaering.de> # # This file is part of pysqlite. # # This software is provided 'as-is', without any express or implied # warranty. In no event will the authors be held liable for any damages # arising from the use of this software. # # Permission is granted to anyone to use this software for any purpose, # including commercial applications, and to alter it and redistribute it # freely, subject to the following restrictions: # # 1. The origin of this software must not be misrepresented; you must not # claim that you wrote the original software. If you use this software # in a product, an acknowledgment in the product documentation would be # appreciated but is not required. # 2. Altered source versions must be plainly marked as such, and must not be # misrepresented as being the original software. # 3. This notice may not be removed or altered from any source distribution. import unittest import pysqlite2.dbapi2 as sqlite def func_returntext(): return "foo" def func_returnunicode(): return u"bar" def func_returnint(): return 42 def func_returnfloat(): return 3.14 def func_returnnull(): return None def func_returnblob(): return buffer("blob") def func_raiseexception(): 5/0 def func_isstring(v): return type(v) is unicode def func_isint(v): return type(v) is int def func_isfloat(v): return type(v) is float def func_isnone(v): return type(v) is type(None) def func_isblob(v): return type(v) is buffer class AggrNoStep: def __init__(self): pass def finalize(self): return 1 class AggrNoFinalize: def __init__(self): pass def step(self, x): pass class AggrExceptionInInit: def __init__(self): 5/0 def step(self, x): pass def finalize(self): pass class AggrExceptionInStep: def __init__(self): pass def step(self, x): 5/0 def finalize(self): return 42 class AggrExceptionInFinalize: def __init__(self): pass def step(self, x): pass def finalize(self): 5/0 class AggrCheckType: def __init__(self): self.val = None def step(self, whichType, val): theType = {"str": unicode, "int": int, "float": float, "None": type(None), "blob": buffer} self.val = int(theType[whichType] is type(val)) def finalize(self): return self.val class AggrSum: def __init__(self): self.val = 0.0 def step(self, val): self.val += val def finalize(self): return self.val class FunctionTests(unittest.TestCase): def setUp(self): self.con = sqlite.connect(":memory:") self.con.create_function("returntext", 0, func_returntext) self.con.create_function("returnunicode", 0, func_returnunicode) self.con.create_function("returnint", 0, func_returnint) self.con.create_function("returnfloat", 0, func_returnfloat) self.con.create_function("returnnull", 0, func_returnnull) self.con.create_function("returnblob", 0, func_returnblob) self.con.create_function("raiseexception", 0, func_raiseexception) self.con.create_function("isstring", 1, func_isstring) self.con.create_function("isint", 1, func_isint) self.con.create_function("isfloat", 1, func_isfloat) self.con.create_function("isnone", 1, func_isnone) self.con.create_function("isblob", 1, func_isblob) def tearDown(self): self.con.close() def CheckFuncErrorOnCreate(self): try: self.con.create_function("bla", -100, lambda x: 2*x) self.fail("should have raised an OperationalError") except sqlite.OperationalError: pass def CheckFuncRefCount(self): def getfunc(): def f(): return 1 return f f = getfunc() globals()["foo"] = f # self.con.create_function("reftest", 0, getfunc()) self.con.create_function("reftest", 0, f) cur = self.con.cursor() cur.execute("select reftest()") def CheckFuncReturnText(self): cur = self.con.cursor() cur.execute("select returntext()") val = cur.fetchone()[0] self.failUnlessEqual(type(val), unicode) self.failUnlessEqual(val, "foo") def CheckFuncReturnUnicode(self): cur = self.con.cursor() cur.execute("select returnunicode()") val = cur.fetchone()[0] self.failUnlessEqual(type(val), unicode) self.failUnlessEqual(val, u"bar") def CheckFuncReturnInt(self): cur = self.con.cursor() cur.execute("select returnint()") val = cur.fetchone()[0] self.failUnlessEqual(type(val), int) self.failUnlessEqual(val, 42) def CheckFuncReturnFloat(self): cur = self.con.cursor() cur.execute("select returnfloat()") val = cur.fetchone()[0] self.failUnlessEqual(type(val), float) if val < 3.139 or val > 3.141: self.fail("wrong value") def CheckFuncReturnNull(self): cur = self.con.cursor() cur.execute("select returnnull()") val = cur.fetchone()[0] self.failUnlessEqual(type(val), type(None)) self.failUnlessEqual(val, None) def CheckFuncReturnBlob(self): cur = self.con.cursor() cur.execute("select returnblob()") val = cur.fetchone()[0] self.failUnlessEqual(type(val), buffer) self.failUnlessEqual(val, buffer("blob")) def CheckFuncException(self): cur = self.con.cursor() try: cur.execute("select raiseexception()") cur.fetchone() self.fail("should have raised OperationalError") except sqlite.OperationalError, e: self.failUnlessEqual(e.args[0], 'user-defined function raised exception') def CheckParamString(self): cur = self.con.cursor() cur.execute("select isstring(?)", ("foo",)) val = cur.fetchone()[0] self.failUnlessEqual(val, 1) def CheckParamInt(self): cur = self.con.cursor() cur.execute("select isint(?)", (42,)) val = cur.fetchone()[0] self.failUnlessEqual(val, 1) def CheckParamFloat(self): cur = self.con.cursor() cur.execute("select isfloat(?)", (3.14,)) val = cur.fetchone()[0] self.failUnlessEqual(val, 1) def CheckParamNone(self): cur = self.con.cursor() cur.execute("select isnone(?)", (None,)) val = cur.fetchone()[0] self.failUnlessEqual(val, 1) def CheckParamBlob(self): cur = self.con.cursor() cur.execute("select isblob(?)", (buffer("blob"),)) val = cur.fetchone()[0] self.failUnlessEqual(val, 1) class AggregateTests(unittest.TestCase): def setUp(self): self.con = sqlite.connect(":memory:") cur = self.con.cursor() cur.execute(""" create table test( t text, i integer, f float, n, b blob ) """) cur.execute("insert into test(t, i, f, n, b) values (?, ?, ?, ?, ?)", ("foo", 5, 3.14, None, buffer("blob"),)) self.con.create_aggregate("nostep", 1, AggrNoStep) self.con.create_aggregate("nofinalize", 1, AggrNoFinalize) self.con.create_aggregate("excInit", 1, AggrExceptionInInit) self.con.create_aggregate("excStep", 1, AggrExceptionInStep) self.con.create_aggregate("excFinalize", 1, AggrExceptionInFinalize) self.con.create_aggregate("checkType", 2, AggrCheckType) self.con.create_aggregate("mysum", 1, AggrSum) def tearDown(self): #self.cur.close() #self.con.close() pass def CheckAggrErrorOnCreate(self): try: self.con.create_function("bla", -100, AggrSum) self.fail("should have raised an OperationalError") except sqlite.OperationalError: pass def CheckAggrNoStep(self): cur = self.con.cursor() try: cur.execute("select nostep(t) from test") self.fail("should have raised an AttributeError") except AttributeError, e: self.failUnlessEqual(e.args[0], "AggrNoStep instance has no attribute 'step'") def CheckAggrNoFinalize(self): cur = self.con.cursor() try: cur.execute("select nofinalize(t) from test") val = cur.fetchone()[0] self.fail("should have raised an OperationalError") except sqlite.OperationalError, e: self.failUnlessEqual(e.args[0], "user-defined aggregate's 'finalize' method raised error") def CheckAggrExceptionInInit(self): cur = self.con.cursor() try: cur.execute("select excInit(t) from test") val = cur.fetchone()[0] self.fail("should have raised an OperationalError") except sqlite.OperationalError, e: self.failUnlessEqual(e.args[0], "user-defined aggregate's '__init__' method raised error") def CheckAggrExceptionInStep(self): cur = self.con.cursor() try: cur.execute("select excStep(t) from test") val = cur.fetchone()[0] self.fail("should have raised an OperationalError") except sqlite.OperationalError, e: self.failUnlessEqual(e.args[0], "user-defined aggregate's 'step' method raised error") def CheckAggrExceptionInFinalize(self): cur = self.con.cursor() try: cur.execute("select excFinalize(t) from test") val = cur.fetchone()[0] self.fail("should have raised an OperationalError") except sqlite.OperationalError, e: self.failUnlessEqual(e.args[0], "user-defined aggregate's 'finalize' method raised error") def CheckAggrCheckParamStr(self): cur = self.con.cursor() cur.execute("select checkType('str', ?)", ("foo",)) val = cur.fetchone()[0] self.failUnlessEqual(val, 1) def CheckAggrCheckParamInt(self): cur = self.con.cursor() cur.execute("select checkType('int', ?)", (42,)) val = cur.fetchone()[0] self.failUnlessEqual(val, 1) def CheckAggrCheckParamFloat(self): cur = self.con.cursor() cur.execute("select checkType('float', ?)", (3.14,)) val = cur.fetchone()[0] self.failUnlessEqual(val, 1) def CheckAggrCheckParamNone(self): cur = self.con.cursor() cur.execute("select checkType('None', ?)", (None,)) val = cur.fetchone()[0] self.failUnlessEqual(val, 1) def CheckAggrCheckParamBlob(self): cur = self.con.cursor() cur.execute("select checkType('blob', ?)", (buffer("blob"),)) val = cur.fetchone()[0] self.failUnlessEqual(val, 1) def CheckAggrCheckAggrSum(self): cur = self.con.cursor() cur.execute("delete from test") cur.executemany("insert into test(i) values (?)", [(10,), (20,), (30,)]) cur.execute("select mysum(i) from test") val = cur.fetchone()[0] self.failUnlessEqual(val, 60) def authorizer_cb(action, arg1, arg2, dbname, source): if action != sqlite.SQLITE_SELECT: return sqlite.SQLITE_DENY if arg2 == 'c2' or arg1 == 't2': return sqlite.SQLITE_DENY return sqlite.SQLITE_OK class AuthorizerTests(unittest.TestCase): def setUp(self): self.con = sqlite.connect(":memory:") self.con.executescript(""" create table t1 (c1, c2); create table t2 (c1, c2); insert into t1 (c1, c2) values (1, 2); insert into t2 (c1, c2) values (4, 5); """) # For our security test: self.con.execute("select c2 from t2") self.con.set_authorizer(authorizer_cb) def tearDown(self): pass def CheckTableAccess(self): try: self.con.execute("select * from t2") except sqlite.DatabaseError, e: if not e.args[0].endswith("prohibited"): self.fail("wrong exception text: %s" % e.args[0]) return self.fail("should have raised an exception due to missing privileges") def CheckColumnAccess(self): try: self.con.execute("select c2 from t1") except sqlite.DatabaseError, e: if not e.args[0].endswith("prohibited"): self.fail("wrong exception text: %s" % e.args[0]) return self.fail("should have raised an exception due to missing privileges") def suite(): function_suite = unittest.makeSuite(FunctionTests, "Check") aggregate_suite = unittest.makeSuite(AggregateTests, "Check") authorizer_suite = unittest.makeSuite(AuthorizerTests, "Check") return unittest.TestSuite((function_suite, aggregate_suite, authorizer_suite)) def test(): runner = unittest.TextTestRunner() runner.run(suite()) if __name__ == "__main__": test()
apache-2.0
kjc88/sl4a
python/src/Lib/test/test_memoryio.py
55
14313
"""Unit tests for memory-based file-like objects. StringIO -- for unicode strings BytesIO -- for bytes """ from __future__ import unicode_literals import unittest from test import test_support import io import sys import array try: import _bytesio has_c_implementation = True except ImportError: has_c_implementation = False class MemoryTestMixin: def write_ops(self, f, t): self.assertEqual(f.write(t("blah.")), 5) self.assertEqual(f.seek(0), 0) self.assertEqual(f.write(t("Hello.")), 6) self.assertEqual(f.tell(), 6) self.assertEqual(f.seek(5), 5) self.assertEqual(f.tell(), 5) self.assertEqual(f.write(t(" world\n\n\n")), 9) self.assertEqual(f.seek(0), 0) self.assertEqual(f.write(t("h")), 1) self.assertEqual(f.truncate(12), 12) self.assertEqual(f.tell(), 12) def test_write(self): buf = self.buftype("hello world\n") memio = self.ioclass(buf) self.write_ops(memio, self.buftype) self.assertEqual(memio.getvalue(), buf) memio = self.ioclass() self.write_ops(memio, self.buftype) self.assertEqual(memio.getvalue(), buf) self.assertRaises(TypeError, memio.write, None) memio.close() self.assertRaises(ValueError, memio.write, self.buftype("")) def test_writelines(self): buf = self.buftype("1234567890") memio = self.ioclass() self.assertEqual(memio.writelines([buf] * 100), None) self.assertEqual(memio.getvalue(), buf * 100) memio.writelines([]) self.assertEqual(memio.getvalue(), buf * 100) memio = self.ioclass() self.assertRaises(TypeError, memio.writelines, [buf] + [1]) self.assertEqual(memio.getvalue(), buf) self.assertRaises(TypeError, memio.writelines, None) memio.close() self.assertRaises(ValueError, memio.writelines, []) def test_writelines_error(self): memio = self.ioclass() def error_gen(): yield self.buftype('spam') raise KeyboardInterrupt self.assertRaises(KeyboardInterrupt, memio.writelines, error_gen()) def test_truncate(self): buf = self.buftype("1234567890") memio = self.ioclass(buf) self.assertRaises(ValueError, memio.truncate, -1) memio.seek(6) self.assertEqual(memio.truncate(), 6) self.assertEqual(memio.getvalue(), buf[:6]) self.assertEqual(memio.truncate(4), 4) self.assertEqual(memio.getvalue(), buf[:4]) self.assertEqual(memio.tell(), 4) memio.write(buf) self.assertEqual(memio.getvalue(), buf[:4] + buf) pos = memio.tell() self.assertEqual(memio.truncate(None), pos) self.assertEqual(memio.tell(), pos) self.assertRaises(TypeError, memio.truncate, '0') memio.close() self.assertRaises(ValueError, memio.truncate, 0) def test_init(self): buf = self.buftype("1234567890") memio = self.ioclass(buf) self.assertEqual(memio.getvalue(), buf) memio = self.ioclass(None) self.assertEqual(memio.getvalue(), self.EOF) memio.__init__(buf * 2) self.assertEqual(memio.getvalue(), buf * 2) memio.__init__(buf) self.assertEqual(memio.getvalue(), buf) def test_read(self): buf = self.buftype("1234567890") memio = self.ioclass(buf) self.assertEqual(memio.read(0), self.EOF) self.assertEqual(memio.read(1), buf[:1]) self.assertEqual(memio.read(4), buf[1:5]) self.assertEqual(memio.read(900), buf[5:]) self.assertEqual(memio.read(), self.EOF) memio.seek(0) self.assertEqual(memio.read(), buf) self.assertEqual(memio.read(), self.EOF) self.assertEqual(memio.tell(), 10) memio.seek(0) self.assertEqual(memio.read(-1), buf) memio.seek(0) self.assertEqual(type(memio.read()), type(buf)) memio.seek(100) self.assertEqual(type(memio.read()), type(buf)) memio.seek(0) self.assertEqual(memio.read(None), buf) self.assertRaises(TypeError, memio.read, '') memio.close() self.assertRaises(ValueError, memio.read) def test_readline(self): buf = self.buftype("1234567890\n") memio = self.ioclass(buf * 2) self.assertEqual(memio.readline(0), self.EOF) self.assertEqual(memio.readline(), buf) self.assertEqual(memio.readline(), buf) self.assertEqual(memio.readline(), self.EOF) memio.seek(0) self.assertEqual(memio.readline(5), buf[:5]) self.assertEqual(memio.readline(5), buf[5:10]) self.assertEqual(memio.readline(5), buf[10:15]) memio.seek(0) self.assertEqual(memio.readline(-1), buf) memio.seek(0) self.assertEqual(memio.readline(0), self.EOF) buf = self.buftype("1234567890\n") memio = self.ioclass((buf * 3)[:-1]) self.assertEqual(memio.readline(), buf) self.assertEqual(memio.readline(), buf) self.assertEqual(memio.readline(), buf[:-1]) self.assertEqual(memio.readline(), self.EOF) memio.seek(0) self.assertEqual(type(memio.readline()), type(buf)) self.assertEqual(memio.readline(None), buf) self.assertRaises(TypeError, memio.readline, '') memio.close() self.assertRaises(ValueError, memio.readline) def test_readlines(self): buf = self.buftype("1234567890\n") memio = self.ioclass(buf * 10) self.assertEqual(memio.readlines(), [buf] * 10) memio.seek(5) self.assertEqual(memio.readlines(), [buf[5:]] + [buf] * 9) memio.seek(0) self.assertEqual(memio.readlines(15), [buf] * 2) memio.seek(0) self.assertEqual(memio.readlines(-1), [buf] * 10) memio.seek(0) self.assertEqual(memio.readlines(0), [buf] * 10) memio.seek(0) self.assertEqual(type(memio.readlines()[0]), type(buf)) memio.seek(0) self.assertEqual(memio.readlines(None), [buf] * 10) self.assertRaises(TypeError, memio.readlines, '') memio.close() self.assertRaises(ValueError, memio.readlines) def test_iterator(self): buf = self.buftype("1234567890\n") memio = self.ioclass(buf * 10) self.assertEqual(iter(memio), memio) self.failUnless(hasattr(memio, '__iter__')) self.failUnless(hasattr(memio, 'next')) i = 0 for line in memio: self.assertEqual(line, buf) i += 1 self.assertEqual(i, 10) memio.seek(0) i = 0 for line in memio: self.assertEqual(line, buf) i += 1 self.assertEqual(i, 10) memio = self.ioclass(buf * 2) memio.close() self.assertRaises(ValueError, memio.next) def test_getvalue(self): buf = self.buftype("1234567890") memio = self.ioclass(buf) self.assertEqual(memio.getvalue(), buf) memio.read() self.assertEqual(memio.getvalue(), buf) self.assertEqual(type(memio.getvalue()), type(buf)) memio = self.ioclass(buf * 1000) self.assertEqual(memio.getvalue()[-3:], self.buftype("890")) memio = self.ioclass(buf) memio.close() self.assertRaises(ValueError, memio.getvalue) def test_seek(self): buf = self.buftype("1234567890") memio = self.ioclass(buf) memio.read(5) self.assertRaises(ValueError, memio.seek, -1) self.assertRaises(ValueError, memio.seek, 1, -1) self.assertRaises(ValueError, memio.seek, 1, 3) self.assertEqual(memio.seek(0), 0) self.assertEqual(memio.seek(0, 0), 0) self.assertEqual(memio.read(), buf) self.assertEqual(memio.seek(3), 3) self.assertEqual(memio.seek(0, 1), 3) self.assertEqual(memio.read(), buf[3:]) self.assertEqual(memio.seek(len(buf)), len(buf)) self.assertEqual(memio.read(), self.EOF) memio.seek(len(buf) + 1) self.assertEqual(memio.read(), self.EOF) self.assertEqual(memio.seek(0, 2), len(buf)) self.assertEqual(memio.read(), self.EOF) memio.close() self.assertRaises(ValueError, memio.seek, 0) def test_overseek(self): buf = self.buftype("1234567890") memio = self.ioclass(buf) self.assertEqual(memio.seek(len(buf) + 1), 11) self.assertEqual(memio.read(), self.EOF) self.assertEqual(memio.tell(), 11) self.assertEqual(memio.getvalue(), buf) memio.write(self.EOF) self.assertEqual(memio.getvalue(), buf) memio.write(buf) self.assertEqual(memio.getvalue(), buf + self.buftype('\0') + buf) def test_tell(self): buf = self.buftype("1234567890") memio = self.ioclass(buf) self.assertEqual(memio.tell(), 0) memio.seek(5) self.assertEqual(memio.tell(), 5) memio.seek(10000) self.assertEqual(memio.tell(), 10000) memio.close() self.assertRaises(ValueError, memio.tell) def test_flush(self): buf = self.buftype("1234567890") memio = self.ioclass(buf) self.assertEqual(memio.flush(), None) def test_flags(self): memio = self.ioclass() self.assertEqual(memio.writable(), True) self.assertEqual(memio.readable(), True) self.assertEqual(memio.seekable(), True) self.assertEqual(memio.isatty(), False) self.assertEqual(memio.closed, False) memio.close() self.assertEqual(memio.writable(), True) self.assertEqual(memio.readable(), True) self.assertEqual(memio.seekable(), True) self.assertRaises(ValueError, memio.isatty) self.assertEqual(memio.closed, True) def test_subclassing(self): buf = self.buftype("1234567890") def test1(): class MemIO(self.ioclass): pass m = MemIO(buf) return m.getvalue() def test2(): class MemIO(self.ioclass): def __init__(me, a, b): self.ioclass.__init__(me, a) m = MemIO(buf, None) return m.getvalue() self.assertEqual(test1(), buf) self.assertEqual(test2(), buf) class PyBytesIOTest(MemoryTestMixin, unittest.TestCase): @staticmethod def buftype(s): return s.encode("ascii") ioclass = io._BytesIO EOF = b"" def test_read1(self): buf = self.buftype("1234567890") memio = self.ioclass(buf) self.assertRaises(TypeError, memio.read1) self.assertEqual(memio.read(), buf) def test_readinto(self): buf = self.buftype("1234567890") memio = self.ioclass(buf) b = bytearray(b"hello") self.assertEqual(memio.readinto(b), 5) self.assertEqual(b, b"12345") self.assertEqual(memio.readinto(b), 5) self.assertEqual(b, b"67890") self.assertEqual(memio.readinto(b), 0) self.assertEqual(b, b"67890") b = bytearray(b"hello world") memio.seek(0) self.assertEqual(memio.readinto(b), 10) self.assertEqual(b, b"1234567890d") b = bytearray(b"") memio.seek(0) self.assertEqual(memio.readinto(b), 0) self.assertEqual(b, b"") self.assertRaises(TypeError, memio.readinto, '') a = array.array(b'b', map(ord, b"hello world")) memio = self.ioclass(buf) memio.readinto(a) self.assertEqual(a.tostring(), b"1234567890d") memio.close() self.assertRaises(ValueError, memio.readinto, b) def test_relative_seek(self): buf = self.buftype("1234567890") memio = self.ioclass(buf) self.assertEqual(memio.seek(-1, 1), 0) self.assertEqual(memio.seek(3, 1), 3) self.assertEqual(memio.seek(-4, 1), 0) self.assertEqual(memio.seek(-1, 2), 9) self.assertEqual(memio.seek(1, 1), 10) self.assertEqual(memio.seek(1, 2), 11) memio.seek(-3, 2) self.assertEqual(memio.read(), buf[-3:]) memio.seek(0) memio.seek(1, 1) self.assertEqual(memio.read(), buf[1:]) def test_unicode(self): memio = self.ioclass() self.assertRaises(TypeError, self.ioclass, "1234567890") self.assertRaises(TypeError, memio.write, "1234567890") self.assertRaises(TypeError, memio.writelines, ["1234567890"]) def test_bytes_array(self): buf = b"1234567890" a = array.array(b'b', map(ord, buf)) memio = self.ioclass(a) self.assertEqual(memio.getvalue(), buf) self.assertEqual(memio.write(a), 10) self.assertEqual(memio.getvalue(), buf) class PyStringIOTest(MemoryTestMixin, unittest.TestCase): buftype = unicode ioclass = io.StringIO EOF = "" def test_relative_seek(self): memio = self.ioclass() self.assertRaises(IOError, memio.seek, -1, 1) self.assertRaises(IOError, memio.seek, 3, 1) self.assertRaises(IOError, memio.seek, -3, 1) self.assertRaises(IOError, memio.seek, -1, 2) self.assertRaises(IOError, memio.seek, 1, 1) self.assertRaises(IOError, memio.seek, 1, 2) # XXX: For the Python version of io.StringIO, this is highly # dependent on the encoding used for the underlying buffer. # def test_widechar(self): # buf = self.buftype("\U0002030a\U00020347") # memio = self.ioclass(buf) # # self.assertEqual(memio.getvalue(), buf) # self.assertEqual(memio.write(buf), len(buf)) # self.assertEqual(memio.tell(), len(buf)) # self.assertEqual(memio.getvalue(), buf) # self.assertEqual(memio.write(buf), len(buf)) # self.assertEqual(memio.tell(), len(buf) * 2) # self.assertEqual(memio.getvalue(), buf + buf) if has_c_implementation: class CBytesIOTest(PyBytesIOTest): ioclass = io.BytesIO def test_main(): tests = [PyBytesIOTest, PyStringIOTest] if has_c_implementation: tests.extend([CBytesIOTest]) test_support.run_unittest(*tests) if __name__ == '__main__': test_main()
apache-2.0
flipchan/LayerProx
setup.openbsd.py
1
1342
#!/usr/bin/env python # coding: utf-8 #openbsd python setup.py import os from setuptools import setup if os.name == 'nt': import py2exe setup(name='marionette-tg', console=['bin/marionette_client','bin/marionette_server'], scripts=['bin/marionette_client','bin/marionette_server'], test_suite='marionette_tg', packages=['marionette_tg','marionette_tg.plugins','marionette_tg.executables'], package_data={'marionette_tg': ['marionette.conf','formats/*.mar','formats/*.py']}, zipfile="marionette.zip", options={"py2exe": { "bundle_files": 2, "optimize": 0, "compressed": True, "includes": [ 'marionette_tg.plugins._channel', 'marionette_tg.plugins._fte', 'marionette_tg.plugins._io', 'marionette_tg.plugins._model', 'marionette_tg.plugins._tg', ], "dll_excludes": ["w9xpopen.exe"], } }, include_package_data=True, install_requires=[''], version='0.0.3', description='Marionette rebuild', long_description='layerProx rebuild of marionette', author='Filip kalebo', author_email='flipchan@riseup.net', url='https://github.com/flipchan/layerProx')
apache-2.0
google-research/google-research
perturbations/perturbations_test.py
1
5591
# coding=utf-8 # Copyright 2021 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Tests for differentiable_programming.perturbations.""" from absl.testing import parameterized import tensorflow.compat.v2 as tf from perturbations import perturbations def reduce_sign_any(input_tensor, axis=-1): """A logical or of the signs of a tensor along an axis. Args: input_tensor: Tensor<float> of any shape. axis: the axis along which we want to compute a logical or of the signs of the values. Returns: A Tensor<float>, which as the same shape as the input tensor, but without the axis on which we reduced. """ boolean_sign = tf.math.reduce_any( tf.cast((tf.sign(input_tensor) + 1) / 2.0, dtype=tf.bool), axis=axis) return tf.cast(boolean_sign, dtype=input_tensor.dtype) * 2.0 - 1.0 class PerturbationsTest(parameterized.TestCase, tf.test.TestCase): """Testing the perturbations module.""" def setUp(self): super(PerturbationsTest, self).setUp() tf.random.set_seed(0) @parameterized.parameters([perturbations._GUMBEL, perturbations._NORMAL]) def test_sample_noise_with_gradients(self, noise): shape = (3, 2, 4) samples, gradients = perturbations.sample_noise_with_gradients(noise, shape) self.assertAllEqual(samples.shape, shape) self.assertAllEqual(gradients.shape, shape) def test_sample_noise_with_gradients_raise(self): with self.assertRaises(ValueError): _, _ = perturbations.sample_noise_with_gradients('unknown', (3, 2, 4)) @parameterized.parameters([1e-3, 1e-2, 1e-1]) def test_perturbed_reduce_sign_any(self, sigma): input_tensor = tf.constant([[-0.3, -1.2, 1.6], [-0.4, -2.4, -1.0]]) soft_reduce_any = perturbations.perturbed(reduce_sign_any, sigma=sigma) output_tensor = soft_reduce_any(input_tensor, axis=-1) self.assertAllClose(output_tensor, [1.0, -1.0]) def test_perturbed_reduce_sign_any_gradients(self): # We choose a point where the gradient should be above noise, that is # to say the distance to 0 along one direction is about sigma. sigma = 0.1 input_tensor = tf.constant( [[-0.6, -1.2, 0.5 * sigma], [-2 * sigma, -2.4, -1.0]]) soft_reduce_any = perturbations.perturbed(reduce_sign_any, sigma=sigma) with tf.GradientTape() as tape: tape.watch(input_tensor) output_tensor = soft_reduce_any(input_tensor) gradient = tape.gradient(output_tensor, input_tensor) # The two values that could change the soft logical or should be the one # with real positive impact on the final values. self.assertAllGreater(gradient[0, 2], 0.0) self.assertAllGreater(gradient[1, 0], 0.0) # The value that is more on the fence should bring more gradient than any # other one. self.assertAllLessEqual(gradient, gradient[0, 2].numpy()) def test_unbatched_rank_one_raise(self): with self.assertRaises(ValueError): input_tensor = tf.constant([-0.6, -0.5, 0.5]) dim = len(input_tensor) n = 10000000 argmax = lambda t: tf.one_hot(tf.argmax(t, 1), dim) soft_argmax = perturbations.perturbed(argmax, sigma=0.5, num_samples=n) _ = soft_argmax(input_tensor) def test_perturbed_argmax_gradients_without_minibatch(self): input_tensor = tf.constant([-0.6, -0.5, 0.5]) dim = len(input_tensor) eps = 1e-2 n = 10000000 argmax = lambda t: tf.one_hot(tf.argmax(t, 1), dim) soft_argmax = perturbations.perturbed( argmax, sigma=0.5, num_samples=n, batched=False) norm_argmax = lambda t: tf.reduce_sum(tf.square(soft_argmax(t))) w = tf.random.normal(input_tensor.shape) w /= tf.linalg.norm(w) var = tf.Variable(input_tensor) with tf.GradientTape() as tape: value = norm_argmax(var) grad = tape.gradient(value, var) grad = tf.reshape(grad, input_tensor.shape) value_minus = norm_argmax(input_tensor - eps * w) value_plus = norm_argmax(input_tensor + eps * w) lhs = tf.reduce_sum(w * grad) rhs = (value_plus - value_minus) * 1./(2*eps) self.assertAllLess(tf.abs(lhs - rhs), 0.05) def test_perturbed_argmax_gradients_with_minibatch(self): input_tensor = tf.constant([[-0.6, -0.7, 0.5], [0.9, -0.6, -0.5]]) dim = len(input_tensor) eps = 1e-2 n = 10000000 argmax = lambda t: tf.one_hot(tf.argmax(t, -1), dim) soft_argmax = perturbations.perturbed(argmax, sigma=2.5, num_samples=n) norm_argmax = lambda t: tf.reduce_sum(tf.square(soft_argmax(t))) w = tf.random.normal(input_tensor.shape) w /= tf.linalg.norm(w) var = tf.Variable(input_tensor) with tf.GradientTape() as tape: value = norm_argmax(var) grad = tape.gradient(value, var) grad = tf.reshape(grad, input_tensor.shape) value_minus = norm_argmax(input_tensor - eps * w) value_plus = norm_argmax(input_tensor + eps * w) lhs = tf.reduce_sum(w * grad) rhs = (value_plus - value_minus) * 1./(2*eps) self.assertAllLess(tf.abs(lhs - rhs), 0.05) if __name__ == '__main__': tf.enable_v2_behavior() tf.test.main()
apache-2.0
kobolabs/calibre
src/calibre/gui2/preferences/save_template.py
4
3143
#!/usr/bin/env python # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import with_statement __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from PyQt4.Qt import QWidget, pyqtSignal from calibre.gui2 import error_dialog, question_dialog from calibre.gui2.preferences.save_template_ui import Ui_Form from calibre.library.save_to_disk import FORMAT_ARG_DESCS, preprocess_template from calibre.utils.formatter import validation_formatter from calibre.gui2.dialogs.template_dialog import TemplateDialog class SaveTemplate(QWidget, Ui_Form): changed_signal = pyqtSignal() def __init__(self, *args): QWidget.__init__(self, *args) Ui_Form.__init__(self) self.setupUi(self) def initialize(self, name, default, help): variables = sorted(FORMAT_ARG_DESCS.keys()) rows = [] for var in variables: rows.append(u'<tr><td>%s</td><td>&nbsp;</td><td>%s</td></tr>'% (var, FORMAT_ARG_DESCS[var])) rows.append(u'<tr><td>%s&nbsp;</td><td>&nbsp;</td><td>%s</td></tr>'%( _('Any custom field'), _('The lookup name of any custom field (these names begin with "#").'))) table = u'<table>%s</table>'%(u'\n'.join(rows)) self.template_variables.setText(table) self.opt_template.initialize(name+'_template_history', default, help) self.opt_template.editTextChanged.connect(self.changed) self.opt_template.currentIndexChanged.connect(self.changed) self.option_name = name self.open_editor.clicked.connect(self.do_open_editor) def do_open_editor(self): t = TemplateDialog(self, self.opt_template.text()) t.setWindowTitle(_('Edit template')) if t.exec_(): self.opt_template.set_value(t.rule[1]) def changed(self, *args): self.changed_signal.emit() def validate(self): ''' Do a syntax check on the format string. Doing a semantic check (verifying that the fields exist) is not useful in the presence of custom fields, because they may or may not exist. ''' tmpl = preprocess_template(self.opt_template.text()) try: t = validation_formatter.validate(tmpl) if t.find(validation_formatter._validation_string) < 0: return question_dialog(self, _('Constant template'), _('The template contains no {fields}, so all ' 'books will have the same name. Is this OK?')) except Exception as err: error_dialog(self, _('Invalid template'), '<p>'+_('The template %s is invalid:')%tmpl + \ '<br>'+str(err), show=True) return False return True def set_value(self, val): self.opt_template.set_value(val) def save_settings(self, config, name): val = unicode(self.opt_template.text()) config.set(name, val) self.opt_template.save_history(self.option_name+'_template_history')
gpl-3.0
ddboline/pylearn2
pylearn2/distributions/tests/test_mnd.py
49
1777
import numpy as np from pylearn2.distributions.mnd import MND from theano import function from pylearn2.testing.skip import skip_if_no_scipy def test_seed_same(): """Verifies that two MNDs initialized with the same seed produce the same samples """ skip_if_no_scipy() rng = np.random.RandomState([1,2,3]) #the number in the argument here is the limit on #seed value seed = rng.randint(2147462579) dim = 3 mu = rng.randn(dim) rank = dim X = rng.randn(rank,dim) cov = np.dot(X.T,X) mnd1 = MND( sigma = cov, mu = mu, seed = seed) num_samples = 5 rd1 = mnd1.random_design_matrix(num_samples) rd1 = function([],rd1)() mnd2 = MND( sigma = cov, mu = mu, seed = seed) rd2 = mnd2.random_design_matrix(num_samples) rd2 = function([],rd2)() assert np.all(rd1 == rd2) def test_seed_diff(): """Verifies that two MNDs initialized with different seeds produce samples that differ at least somewhat (theoretically the samples could match even under valid behavior but this is extremely unlikely)""" skip_if_no_scipy() rng = np.random.RandomState([1,2,3]) #the number in the argument here is the limit on #seed value, and we subtract 1 so it will be #possible to add 1 to it for the second MND seed = rng.randint(2147462579) -1 dim = 3 mu = rng.randn(dim) rank = dim X = rng.randn(rank,dim) cov = np.dot(X.T,X) mnd1 = MND( sigma = cov, mu = mu, seed = seed) num_samples = 5 rd1 = mnd1.random_design_matrix(num_samples) rd1 = function([],rd1)() mnd2 = MND( sigma = cov, mu = mu, seed = seed + 1) rd2 = mnd2.random_design_matrix(num_samples) rd2 = function([],rd2)() assert np.any(rd1 != rd2)
bsd-3-clause
robgjansen/libutp
parse_log.py
17
7954
import os, sys, time # usage: parse_log.py log-file [socket-index to focus on] socket_filter = None if len(sys.argv) >= 3: socket_filter = sys.argv[2].strip() if socket_filter == None: print "scanning for socket with the most packets" file = open(sys.argv[1], 'rb') sockets = {} for l in file: if not 'our_delay' in l: continue try: a = l.strip().split(" ") socket_index = a[1][:-1] except: continue # msvc's runtime library doesn't prefix pointers # with '0x' # if socket_index[:2] != '0x': # continue if socket_index in sockets: sockets[socket_index] += 1 else: sockets[socket_index] = 1 items = sockets.items() items.sort(lambda x, y: y[1] - x[1]) count = 0 for i in items: print '%s: %d' % (i[0], i[1]) count += 1 if count > 5: break file.close() socket_filter = items[0][0] print '\nfocusing on socket %s' % socket_filter file = open(sys.argv[1], 'rb') out_file = 'utp.out%s' % socket_filter; out = open(out_file, 'wb') delay_samples = 'dots lc rgb "blue"' delay_base = 'steps lw 2 lc rgb "purple"' target_delay = 'steps lw 2 lc rgb "red"' off_target = 'dots lc rgb "blue"' cwnd = 'steps lc rgb "green"' window_size = 'steps lc rgb "sea-green"' rtt = 'lines lc rgb "light-blue"' metrics = { 'our_delay':['our delay (ms)', 'x1y2', delay_samples], 'upload_rate':['send rate (B/s)', 'x1y1', 'lines'], 'max_window':['cwnd (B)', 'x1y1', cwnd], 'target_delay':['target delay (ms)', 'x1y2', target_delay], 'cur_window':['bytes in-flight (B)', 'x1y1', window_size], 'cur_window_packets':['number of packets in-flight', 'x1y2', 'steps'], 'packet_size':['current packet size (B)', 'x1y2', 'steps'], 'rtt':['rtt (ms)', 'x1y2', rtt], 'off_target':['off-target (ms)', 'x1y2', off_target], 'delay_sum':['delay sum (ms)', 'x1y2', 'steps'], 'their_delay':['their delay (ms)', 'x1y2', delay_samples], 'get_microseconds':['clock (us)', 'x1y1', 'steps'], 'wnduser':['advertised window size (B)', 'x1y1', 'steps'], 'delay_base':['delay base (us)', 'x1y1', delay_base], 'their_delay_base':['their delay base (us)', 'x1y1', delay_base], 'their_actual_delay':['their actual delay (us)', 'x1y1', delay_samples], 'actual_delay':['actual_delay (us)', 'x1y1', delay_samples] } histogram_quantization = 1 socket_index = None columns = [] begin = None title = "-" packet_loss = 0 packet_timeout = 0 delay_histogram = {} window_size = {'0': 0, '1': 0} # [35301484] 0x00ec1190: actual_delay:1021583 our_delay:102 their_delay:-1021345 off_target:297 max_window:2687 upload_rate:18942 delay_base:1021481154 delay_sum:-1021242 target_delay:400 acked_bytes:1441 cur_window:2882 scaled_gain:2.432 counter = 0 print "reading log file" for l in file: if "UTP_Connect" in l: title = l[:-2] if socket_filter != None: title += ' socket: %s' % socket_filter else: title += ' sum of all sockets' continue try: a = l.strip().split(" ") t = a[0][1:-1] socket_index = a[1][:-1] except: continue # if socket_index[:2] != '0x': # continue if socket_filter != None and socket_index != socket_filter: continue counter += 1 if (counter % 300 == 0): print "\r%d " % counter, if "lost." in l: packet_loss = packet_loss + 1 continue if "Packet timeout" in l: packet_timeout = packet_timeout + 1 continue if "our_delay:" not in l: continue # used for Logf timestamps # t, m = t.split(".") # t = time.strptime(t, "%H:%M:%S") # t = list(t) # t[0] += 107 # t = tuple(t) # m = float(m) # m /= 1000.0 # t = time.mktime(t) + m # used for tick count timestamps t = int(t) if begin is None: begin = t t = t - begin # print time. Convert from milliseconds to seconds print >>out, '%f\t' % (float(t)/1000.), #if t > 200000: # break fill_columns = not columns for i in a[2:]: try: n, v = i.split(':') except: continue v = float(v) if n == "our_delay": bucket = v / histogram_quantization delay_histogram[bucket] = 1 + delay_histogram.get(bucket, 0) if not n in metrics: continue if fill_columns: columns.append(n) if n == "max_window": window_size[socket_index] = v print >>out, '%f\t' % int(reduce(lambda a,b: a+b, window_size.values())), else: print >>out, '%f\t' % v, print >>out, float(packet_loss * 8000), float(packet_timeout * 8000) packet_loss = 0 packet_timeout = 0 out.close() out = open('%s.histogram' % out_file, 'wb') for d,f in delay_histogram.iteritems(): print >>out, float(d*histogram_quantization) + histogram_quantization / 2, f out.close() plot = [ { 'data': ['upload_rate', 'max_window', 'cur_window', 'wnduser', 'cur_window_packets', 'packet_size', 'rtt'], 'title': 'send-packet-size', 'y1': 'Bytes', 'y2': 'Time (ms)' }, { 'data': ['our_delay', 'max_window', 'target_delay', 'cur_window', 'wnduser', 'cur_window_packets'], 'title': 'uploading', 'y1': 'Bytes', 'y2': 'Time (ms)' }, { 'data': ['our_delay', 'max_window', 'target_delay', 'cur_window', 'cur_window_packets'], 'title': 'uploading_packets', 'y1': 'Bytes', 'y2': 'Time (ms)' }, { 'data': ['get_microseconds'], 'title': 'timer', 'y1': 'Time microseconds', 'y2': 'Time (ms)' }, { 'data': ['their_delay', 'target_delay', 'rtt'], 'title': 'their_delay', 'y1': '', 'y2': 'Time (ms)' }, { 'data': ['their_actual_delay','their_delay_base'], 'title': 'their_delay_base', 'y1': 'Time (us)', 'y2': '' }, { 'data': ['our_delay', 'target_delay', 'rtt'], 'title': 'our-delay', 'y1': '', 'y2': 'Time (ms)' }, { 'data': ['actual_delay', 'delay_base'], 'title': 'our_delay_base', 'y1': 'Time (us)', 'y2': '' } ] out = open('utp.gnuplot', 'w+') files = '' #print >>out, 'set xtics 0, 20' print >>out, "set term png size 1280,800" print >>out, 'set output "%s.delays.png"' % out_file print >>out, 'set xrange [0:250]' print >>out, 'set xlabel "delay (ms)"' print >>out, 'set boxwidth 1' print >>out, 'set style fill solid' print >>out, 'set ylabel "number of packets"' print >>out, 'plot "%s.histogram" using 1:2 with boxes' % out_file print >>out, "set style data steps" #print >>out, "set yrange [0:*]" print >>out, "set y2range [*:*]" files += out_file + '.delays.png ' #set hidden3d #set title "Peer bandwidth distribution" #set xlabel "Ratio" for p in plot: print >>out, 'set title "%s %s"' % (p['title'], title) print >>out, 'set xlabel "time (s)"' print >>out, 'set ylabel "%s"' % p['y1'] print >>out, "set tics nomirror" print >>out, 'set y2tics' print >>out, 'set y2label "%s"' % p['y2'] print >>out, 'set xrange [0:*]' print >>out, "set key box" print >>out, "set term png size 1280,800" print >>out, 'set output "%s-%s.png"' % (out_file, p['title']) files += '%s-%s.png ' % (out_file, p['title']) comma = '' print >>out, "plot", for c in p['data']: if not c in metrics: continue i = columns.index(c) print >>out, '%s"%s" using 1:%d title "%s-%s" axes %s with %s' % (comma, out_file, i + 2, metrics[c][0], metrics[c][1], metrics[c][1], metrics[c][2]), comma = ', ' print >>out, '' out.close() os.system("gnuplot utp.gnuplot") os.system("open %s" % files)
mit
tinkerthaler/odoo
addons/membership/__init__.py
441
1101
# -*- 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 membership import wizard import report # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
polyanskiy/refractiveindex.info-scripts
scripts/Rakic 1998 - Cr (BB model).py
1
2587
# -*- coding: utf-8 -*- # Author: Mikhail Polyanskiy # Last modified: 2017-04-02 # Original data: Rakić et al. 1998, https://doi.org/10.1364/AO.37.005271 import numpy as np import matplotlib.pyplot as plt from scipy.special import wofz as w π = np.pi # Brendel-Bormann (BB) model parameters ωp = 10.75 #eV f0 = 0.154 Γ0 = 0.048 #eV f1 = 0.338 Γ1 = 4.256 #eV ω1 = 0.281 #eV σ1 = 0.115 #eV f2 = 0.261 Γ2 = 3.957 #eV ω2 = 0.584 #eV σ2 = 0.252 #eV f3 = 0.817 Γ3 = 2.218 #eV ω3 = 1.919 #eV σ3 = 0.225 #eV f4 = 0.105 Γ4 = 6.983 #eV ω4 = 6.997 #eV σ4 = 4.903 #eV Ωp = f0**.5 * ωp #eV def BB(ω): #ω: eV ε = 1-Ωp**2/(ω*(ω+1j*Γ0)) α = (ω**2+1j*ω*Γ1)**.5 za = (α-ω1)/(2**.5*σ1) zb = (α+ω1)/(2**.5*σ1) ε += 1j*π**.5*f1*ωp**2 / (2**1.5*α*σ1) * (w(za)+w(zb)) #χ1 α = (ω**2+1j*ω*Γ2)**.5 za = (α-ω2)/(2**.5*σ2) zb = (α+ω2)/(2**.5*σ2) ε += 1j*π**.5*f2*ωp**2 / (2**1.5*α*σ2) * (w(za)+w(zb)) #χ2 α = (ω**2+1j*ω*Γ3)**.5 za = (α-ω3)/(2**.5*σ3) zb = (α+ω3)/(2**.5*σ3) ε += 1j*π**.5*f3*ωp**2 / (2**1.5*α*σ3) * (w(za)+w(zb)) #χ3 α = (ω**2+1j*ω*Γ4)**.5 za = (α-ω4)/(2**.5*σ4) zb = (α+ω4)/(2**.5*σ4) ε += 1j*π**.5*f4*ωp**2 / (2**1.5*α*σ4) * (w(za)+w(zb)) #χ4 return ε ev_min=0.02 ev_max=5 npoints=200 eV = np.logspace(np.log10(ev_min), np.log10(ev_max), npoints) μm = 4.13566733e-1*2.99792458/eV ε = BB(eV) n = (ε**.5).real k = (ε**.5).imag #============================ DATA OUTPUT ================================= file = open('out.txt', 'w') for i in range(npoints-1, -1, -1): file.write('\n {:.4e} {:.4e} {:.4e}'.format(μm[i],n[i],k[i])) file.close() #=============================== PLOT ===================================== plt.rc('font', family='Arial', size='14') plt.figure(1) plt.plot(eV, -ε.real, label="-ε1") plt.plot(eV, ε.imag, label="ε2") plt.xlabel('Photon energy (eV)') plt.ylabel('ε') plt.xscale('log') plt.yscale('log') plt.legend(bbox_to_anchor=(0,1.02,1,0),loc=3,ncol=2,borderaxespad=0) #plot n,k vs eV plt.figure(2) plt.plot(eV, n, label="n") plt.plot(eV, k, label="k") plt.xlabel('Photon energy (eV)') plt.ylabel('n, k') plt.yscale('log') plt.legend(bbox_to_anchor=(0,1.02,1,0),loc=3,ncol=2,borderaxespad=0) #plot n,k vs μm plt.figure(3) plt.plot(μm, n, label="n") plt.plot(μm, k, label="k") plt.xlabel('Wavelength (μm)') plt.ylabel('n, k') plt.xscale('log') plt.yscale('log') plt.legend(bbox_to_anchor=(0,1.02,1,0),loc=3,ncol=2,borderaxespad=0)
gpl-3.0
msarana/selenium_python
ENV/Lib/ntpath.py
50
19431
# Module 'ntpath' -- common operations on WinNT/Win95 pathnames """Common pathname manipulations, WindowsNT/95 version. Instead of importing this module directly, import os and refer to this module as os.path. """ import os import sys import stat import genericpath import warnings from genericpath import * from genericpath import _unicode __all__ = ["normcase","isabs","join","splitdrive","split","splitext", "basename","dirname","commonprefix","getsize","getmtime", "getatime","getctime", "islink","exists","lexists","isdir","isfile", "ismount","walk","expanduser","expandvars","normpath","abspath", "splitunc","curdir","pardir","sep","pathsep","defpath","altsep", "extsep","devnull","realpath","supports_unicode_filenames","relpath"] # strings representing various path-related bits and pieces curdir = '.' pardir = '..' extsep = '.' sep = '\\' pathsep = ';' altsep = '/' defpath = '.;C:\\bin' if 'ce' in sys.builtin_module_names: defpath = '\\Windows' elif 'os2' in sys.builtin_module_names: # OS/2 w/ VACPP altsep = '/' devnull = 'nul' # Normalize the case of a pathname and map slashes to backslashes. # Other normalizations (such as optimizing '../' away) are not done # (this is done by normpath). def normcase(s): """Normalize case of pathname. Makes all characters lowercase and all slashes into backslashes.""" return s.replace("/", "\\").lower() # Return whether a path is absolute. # Trivial in Posix, harder on the Mac or MS-DOS. # For DOS it is absolute if it starts with a slash or backslash (current # volume), or if a pathname after the volume letter and colon / UNC resource # starts with a slash or backslash. def isabs(s): """Test whether a path is absolute""" s = splitdrive(s)[1] return s != '' and s[:1] in '/\\' # Join two (or more) paths. def join(path, *paths): """Join two or more pathname components, inserting "\\" as needed.""" result_drive, result_path = splitdrive(path) for p in paths: p_drive, p_path = splitdrive(p) if p_path and p_path[0] in '\\/': # Second path is absolute if p_drive or not result_drive: result_drive = p_drive result_path = p_path continue elif p_drive and p_drive != result_drive: if p_drive.lower() != result_drive.lower(): # Different drives => ignore the first path entirely result_drive = p_drive result_path = p_path continue # Same drive in different case result_drive = p_drive # Second path is relative to the first if result_path and result_path[-1] not in '\\/': result_path = result_path + '\\' result_path = result_path + p_path ## add separator between UNC and non-absolute path if (result_path and result_path[0] not in '\\/' and result_drive and result_drive[-1:] != ':'): return result_drive + sep + result_path return result_drive + result_path # Split a path in a drive specification (a drive letter followed by a # colon) and the path specification. # It is always true that drivespec + pathspec == p def splitdrive(p): """Split a pathname into drive/UNC sharepoint and relative path specifiers. Returns a 2-tuple (drive_or_unc, path); either part may be empty. If you assign result = splitdrive(p) It is always true that: result[0] + result[1] == p If the path contained a drive letter, drive_or_unc will contain everything up to and including the colon. e.g. splitdrive("c:/dir") returns ("c:", "/dir") If the path contained a UNC path, the drive_or_unc will contain the host name and share up to but not including the fourth directory separator character. e.g. splitdrive("//host/computer/dir") returns ("//host/computer", "/dir") Paths cannot contain both a drive letter and a UNC path. """ if len(p) > 1: normp = p.replace(altsep, sep) if (normp[0:2] == sep*2) and (normp[2:3] != sep): # is a UNC path: # vvvvvvvvvvvvvvvvvvvv drive letter or UNC path # \\machine\mountpoint\directory\etc\... # directory ^^^^^^^^^^^^^^^ index = normp.find(sep, 2) if index == -1: return '', p index2 = normp.find(sep, index + 1) # a UNC path can't have two slashes in a row # (after the initial two) if index2 == index + 1: return '', p if index2 == -1: index2 = len(p) return p[:index2], p[index2:] if normp[1] == ':': return p[:2], p[2:] return '', p # Parse UNC paths def splitunc(p): """Split a pathname into UNC mount point and relative path specifiers. Return a 2-tuple (unc, rest); either part may be empty. If unc is not empty, it has the form '//host/mount' (or similar using backslashes). unc+rest is always the input path. Paths containing drive letters never have an UNC part. """ if p[1:2] == ':': return '', p # Drive letter present firstTwo = p[0:2] if firstTwo == '//' or firstTwo == '\\\\': # is a UNC path: # vvvvvvvvvvvvvvvvvvvv equivalent to drive letter # \\machine\mountpoint\directories... # directory ^^^^^^^^^^^^^^^ normp = p.replace('\\', '/') index = normp.find('/', 2) if index <= 2: return '', p index2 = normp.find('/', index + 1) # a UNC path can't have two slashes in a row # (after the initial two) if index2 == index + 1: return '', p if index2 == -1: index2 = len(p) return p[:index2], p[index2:] return '', p # Split a path in head (everything up to the last '/') and tail (the # rest). After the trailing '/' is stripped, the invariant # join(head, tail) == p holds. # The resulting head won't end in '/' unless it is the root. def split(p): """Split a pathname. Return tuple (head, tail) where tail is everything after the final slash. Either part may be empty.""" d, p = splitdrive(p) # set i to index beyond p's last slash i = len(p) while i and p[i-1] not in '/\\': i = i - 1 head, tail = p[:i], p[i:] # now tail has no slashes # remove trailing slashes from head, unless it's all slashes head2 = head while head2 and head2[-1] in '/\\': head2 = head2[:-1] head = head2 or head return d + head, tail # Split a path in root and extension. # The extension is everything starting at the last dot in the last # pathname component; the root is everything before that. # It is always true that root + ext == p. def splitext(p): return genericpath._splitext(p, sep, altsep, extsep) splitext.__doc__ = genericpath._splitext.__doc__ # Return the tail (basename) part of a path. def basename(p): """Returns the final component of a pathname""" return split(p)[1] # Return the head (dirname) part of a path. def dirname(p): """Returns the directory component of a pathname""" return split(p)[0] # Is a path a symbolic link? # This will always return false on systems where posix.lstat doesn't exist. def islink(path): """Test for symbolic link. On WindowsNT/95 and OS/2 always returns false """ return False # alias exists to lexists lexists = exists # Is a path a mount point? Either a root (with or without drive letter) # or an UNC path with at most a / or \ after the mount point. def ismount(path): """Test whether a path is a mount point (defined as root of drive)""" unc, rest = splitunc(path) if unc: return rest in ("", "/", "\\") p = splitdrive(path)[1] return len(p) == 1 and p[0] in '/\\' # Directory tree walk. # For each directory under top (including top itself, but excluding # '.' and '..'), func(arg, dirname, filenames) is called, where # dirname is the name of the directory and filenames is the list # of files (and subdirectories etc.) in the directory. # The func may modify the filenames list, to implement a filter, # or to impose a different order of visiting. def walk(top, func, arg): """Directory tree walk with callback function. For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), call func(arg, dirname, fnames). dirname is the name of the directory, and fnames a list of the names of the files and subdirectories in dirname (excluding '.' and '..'). func may modify the fnames list in-place (e.g. via del or slice assignment), and walk will only recurse into the subdirectories whose names remain in fnames; this can be used to implement a filter, or to impose a specific order of visiting. No semantics are defined for, or required of, arg, beyond that arg is always passed to func. It can be used, e.g., to pass a filename pattern, or a mutable object designed to accumulate statistics. Passing None for arg is common.""" warnings.warnpy3k("In 3.x, os.path.walk is removed in favor of os.walk.", stacklevel=2) try: names = os.listdir(top) except os.error: return func(arg, top, names) for name in names: name = join(top, name) if isdir(name): walk(name, func, arg) # Expand paths beginning with '~' or '~user'. # '~' means $HOME; '~user' means that user's home directory. # If the path doesn't begin with '~', or if the user or $HOME is unknown, # the path is returned unchanged (leaving error reporting to whatever # function is called with the expanded path as argument). # See also module 'glob' for expansion of *, ? and [...] in pathnames. # (A function should also be defined to do full *sh-style environment # variable expansion.) def expanduser(path): """Expand ~ and ~user constructs. If user or $HOME is unknown, do nothing.""" if path[:1] != '~': return path i, n = 1, len(path) while i < n and path[i] not in '/\\': i = i + 1 if 'HOME' in os.environ: userhome = os.environ['HOME'] elif 'USERPROFILE' in os.environ: userhome = os.environ['USERPROFILE'] elif not 'HOMEPATH' in os.environ: return path else: try: drive = os.environ['HOMEDRIVE'] except KeyError: drive = '' userhome = join(drive, os.environ['HOMEPATH']) if i != 1: #~user userhome = join(dirname(userhome), path[1:i]) return userhome + path[i:] # Expand paths containing shell variable substitutions. # The following rules apply: # - no expansion within single quotes # - '$$' is translated into '$' # - '%%' is translated into '%' if '%%' are not seen in %var1%%var2% # - ${varname} is accepted. # - $varname is accepted. # - %varname% is accepted. # - varnames can be made out of letters, digits and the characters '_-' # (though is not verified in the ${varname} and %varname% cases) # XXX With COMMAND.COM you can use any characters in a variable name, # XXX except '^|<>='. def expandvars(path): """Expand shell variables of the forms $var, ${var} and %var%. Unknown variables are left unchanged.""" if '$' not in path and '%' not in path: return path import string varchars = string.ascii_letters + string.digits + '_-' if isinstance(path, _unicode): encoding = sys.getfilesystemencoding() def getenv(var): return os.environ[var.encode(encoding)].decode(encoding) else: def getenv(var): return os.environ[var] res = '' index = 0 pathlen = len(path) while index < pathlen: c = path[index] if c == '\'': # no expansion within single quotes path = path[index + 1:] pathlen = len(path) try: index = path.index('\'') res = res + '\'' + path[:index + 1] except ValueError: res = res + c + path index = pathlen - 1 elif c == '%': # variable or '%' if path[index + 1:index + 2] == '%': res = res + c index = index + 1 else: path = path[index+1:] pathlen = len(path) try: index = path.index('%') except ValueError: res = res + '%' + path index = pathlen - 1 else: var = path[:index] try: res = res + getenv(var) except KeyError: res = res + '%' + var + '%' elif c == '$': # variable or '$$' if path[index + 1:index + 2] == '$': res = res + c index = index + 1 elif path[index + 1:index + 2] == '{': path = path[index+2:] pathlen = len(path) try: index = path.index('}') var = path[:index] try: res = res + getenv(var) except KeyError: res = res + '${' + var + '}' except ValueError: res = res + '${' + path index = pathlen - 1 else: var = '' index = index + 1 c = path[index:index + 1] while c != '' and c in varchars: var = var + c index = index + 1 c = path[index:index + 1] try: res = res + getenv(var) except KeyError: res = res + '$' + var if c != '': index = index - 1 else: res = res + c index = index + 1 return res # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A\B. # Previously, this function also truncated pathnames to 8+3 format, # but as this module is called "ntpath", that's obviously wrong! def normpath(path): """Normalize path, eliminating double slashes, etc.""" # Preserve unicode (if path is unicode) backslash, dot = (u'\\', u'.') if isinstance(path, _unicode) else ('\\', '.') if path.startswith(('\\\\.\\', '\\\\?\\')): # in the case of paths with these prefixes: # \\.\ -> device names # \\?\ -> literal paths # do not do any normalization, but return the path unchanged return path path = path.replace("/", "\\") prefix, path = splitdrive(path) # We need to be careful here. If the prefix is empty, and the path starts # with a backslash, it could either be an absolute path on the current # drive (\dir1\dir2\file) or a UNC filename (\\server\mount\dir1\file). It # is therefore imperative NOT to collapse multiple backslashes blindly in # that case. # The code below preserves multiple backslashes when there is no drive # letter. This means that the invalid filename \\\a\b is preserved # unchanged, where a\\\b is normalised to a\b. It's not clear that there # is any better behaviour for such edge cases. if prefix == '': # No drive letter - preserve initial backslashes while path[:1] == "\\": prefix = prefix + backslash path = path[1:] else: # We have a drive letter - collapse initial backslashes if path.startswith("\\"): prefix = prefix + backslash path = path.lstrip("\\") comps = path.split("\\") i = 0 while i < len(comps): if comps[i] in ('.', ''): del comps[i] elif comps[i] == '..': if i > 0 and comps[i-1] != '..': del comps[i-1:i+1] i -= 1 elif i == 0 and prefix.endswith("\\"): del comps[i] else: i += 1 else: i += 1 # If the path is now empty, substitute '.' if not prefix and not comps: comps.append(dot) return prefix + backslash.join(comps) # Return an absolute path. try: from nt import _getfullpathname except ImportError: # not running on Windows - mock up something sensible def abspath(path): """Return the absolute version of a path.""" if not isabs(path): if isinstance(path, _unicode): cwd = os.getcwdu() else: cwd = os.getcwd() path = join(cwd, path) return normpath(path) else: # use native Windows method on Windows def abspath(path): """Return the absolute version of a path.""" if path: # Empty path must return current working directory. try: path = _getfullpathname(path) except WindowsError: pass # Bad path - return unchanged. elif isinstance(path, _unicode): path = os.getcwdu() else: path = os.getcwd() return normpath(path) # realpath is a no-op on systems without islink support realpath = abspath # Win9x family and earlier have no Unicode filename support. supports_unicode_filenames = (hasattr(sys, "getwindowsversion") and sys.getwindowsversion()[3] >= 2) def _abspath_split(path): abs = abspath(normpath(path)) prefix, rest = splitunc(abs) is_unc = bool(prefix) if not is_unc: prefix, rest = splitdrive(abs) return is_unc, prefix, [x for x in rest.split(sep) if x] def relpath(path, start=curdir): """Return a relative version of a path""" if not path: raise ValueError("no path specified") start_is_unc, start_prefix, start_list = _abspath_split(start) path_is_unc, path_prefix, path_list = _abspath_split(path) if path_is_unc ^ start_is_unc: raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)" % (path, start)) if path_prefix.lower() != start_prefix.lower(): if path_is_unc: raise ValueError("path is on UNC root %s, start on UNC root %s" % (path_prefix, start_prefix)) else: raise ValueError("path is on drive %s, start on drive %s" % (path_prefix, start_prefix)) # Work out how much of the filepath is shared by start and path. i = 0 for e1, e2 in zip(start_list, path_list): if e1.lower() != e2.lower(): break i += 1 rel_list = [pardir] * (len(start_list)-i) + path_list[i:] if not rel_list: return curdir return join(*rel_list) try: # The genericpath.isdir implementation uses os.stat and checks the mode # attribute to tell whether or not the path is a directory. # This is overkill on Windows - just pass the path to GetFileAttributes # and check the attribute from there. from nt import _isdir as isdir except ImportError: # Use genericpath.isdir as imported above. pass
apache-2.0
dims/nova
nova/tests/unit/objects/test_request_spec.py
2
21770
# Copyright 2015 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import mock from oslo_serialization import jsonutils from oslo_utils import uuidutils from nova import context from nova import exception from nova import objects from nova.objects import base from nova.objects import request_spec from nova.tests.unit import fake_flavor from nova.tests.unit import fake_instance from nova.tests.unit import fake_request_spec from nova.tests.unit.objects import test_objects class _TestRequestSpecObject(object): def test_image_meta_from_image_as_object(self): # Just isolating the test for the from_dict() method image_meta = objects.ImageMeta(name='foo') spec = objects.RequestSpec() spec._image_meta_from_image(image_meta) self.assertEqual(image_meta, spec.image) @mock.patch.object(objects.ImageMeta, 'from_dict') def test_image_meta_from_image_as_dict(self, from_dict): # Just isolating the test for the from_dict() method image_meta = objects.ImageMeta(name='foo') from_dict.return_value = image_meta spec = objects.RequestSpec() spec._image_meta_from_image({'name': 'foo'}) self.assertEqual(image_meta, spec.image) def test_image_meta_from_image_as_none(self): # just add a dumb check to have a full coverage spec = objects.RequestSpec() spec._image_meta_from_image(None) self.assertIsNone(spec.image) @mock.patch.object(base, 'obj_to_primitive') def test_to_legacy_image(self, obj_to_primitive): spec = objects.RequestSpec(image=objects.ImageMeta()) fake_dict = mock.Mock() obj_to_primitive.return_value = fake_dict self.assertEqual(fake_dict, spec._to_legacy_image()) obj_to_primitive.assert_called_once_with(spec.image) @mock.patch.object(base, 'obj_to_primitive') def test_to_legacy_image_with_none(self, obj_to_primitive): spec = objects.RequestSpec(image=None) self.assertEqual({}, spec._to_legacy_image()) self.assertFalse(obj_to_primitive.called) def test_from_instance_as_object(self): instance = objects.Instance() instance.uuid = uuidutils.generate_uuid() instance.numa_topology = None instance.pci_requests = None instance.project_id = '1' instance.availability_zone = 'nova' spec = objects.RequestSpec() spec._from_instance(instance) instance_fields = ['numa_topology', 'pci_requests', 'uuid', 'project_id', 'availability_zone'] for field in instance_fields: if field == 'uuid': self.assertEqual(getattr(instance, field), getattr(spec, 'instance_uuid')) else: self.assertEqual(getattr(instance, field), getattr(spec, field)) def test_from_instance_as_dict(self): instance = dict(uuid=uuidutils.generate_uuid(), numa_topology=None, pci_requests=None, project_id='1', availability_zone='nova') spec = objects.RequestSpec() spec._from_instance(instance) instance_fields = ['numa_topology', 'pci_requests', 'uuid', 'project_id', 'availability_zone'] for field in instance_fields: if field == 'uuid': self.assertEqual(instance.get(field), getattr(spec, 'instance_uuid')) else: self.assertEqual(instance.get(field), getattr(spec, field)) @mock.patch.object(objects.InstancePCIRequests, 'from_request_spec_instance_props') def test_from_instance_with_pci_requests(self, pci_from_spec): fake_pci_requests = objects.InstancePCIRequests() pci_from_spec.return_value = fake_pci_requests instance = dict( uuid=uuidutils.generate_uuid(), root_gb=10, ephemeral_gb=0, memory_mb=10, vcpus=1, numa_topology=None, project_id='1', availability_zone='nova', pci_requests={ 'instance_uuid': 'fakeid', 'requests': [{'count': 1, 'spec': [{'vendor_id': '8086'}]}]}) spec = objects.RequestSpec() spec._from_instance(instance) pci_from_spec.assert_called_once_with(instance['pci_requests']) self.assertEqual(fake_pci_requests, spec.pci_requests) def test_from_instance_with_numa_stuff(self): instance = dict( uuid=uuidutils.generate_uuid(), root_gb=10, ephemeral_gb=0, memory_mb=10, vcpus=1, project_id='1', availability_zone='nova', pci_requests=None, numa_topology={'cells': [{'id': 1, 'cpuset': ['1'], 'memory': 8192, 'pagesize': None, 'cpu_topology': None, 'cpu_pinning_raw': None}]}) spec = objects.RequestSpec() spec._from_instance(instance) self.assertIsInstance(spec.numa_topology, objects.InstanceNUMATopology) cells = spec.numa_topology.cells self.assertEqual(1, len(cells)) self.assertIsInstance(cells[0], objects.InstanceNUMACell) def test_from_flavor_as_object(self): flavor = objects.Flavor() spec = objects.RequestSpec() spec._from_flavor(flavor) self.assertEqual(flavor, spec.flavor) def test_from_flavor_as_dict(self): flavor_dict = dict(id=1) ctxt = context.RequestContext('fake', 'fake') spec = objects.RequestSpec(ctxt) spec._from_flavor(flavor_dict) self.assertIsInstance(spec.flavor, objects.Flavor) self.assertEqual({'id': 1}, spec.flavor.obj_get_changes()) def test_to_legacy_instance(self): spec = objects.RequestSpec() spec.flavor = objects.Flavor(root_gb=10, ephemeral_gb=0, memory_mb=10, vcpus=1) spec.numa_topology = None spec.pci_requests = None spec.project_id = '1' spec.availability_zone = 'nova' instance = spec._to_legacy_instance() self.assertEqual({'root_gb': 10, 'ephemeral_gb': 0, 'memory_mb': 10, 'vcpus': 1, 'numa_topology': None, 'pci_requests': None, 'project_id': '1', 'availability_zone': 'nova'}, instance) def test_to_legacy_instance_with_unset_values(self): spec = objects.RequestSpec() self.assertEqual({}, spec._to_legacy_instance()) def test_from_retry(self): retry_dict = {'num_attempts': 1, 'hosts': [['fake1', 'node1']]} ctxt = context.RequestContext('fake', 'fake') spec = objects.RequestSpec(ctxt) spec._from_retry(retry_dict) self.assertIsInstance(spec.retry, objects.SchedulerRetries) self.assertEqual(1, spec.retry.num_attempts) self.assertIsInstance(spec.retry.hosts, objects.ComputeNodeList) self.assertEqual(1, len(spec.retry.hosts)) self.assertEqual('fake1', spec.retry.hosts[0].host) self.assertEqual('node1', spec.retry.hosts[0].hypervisor_hostname) def test_from_retry_missing_values(self): retry_dict = {} ctxt = context.RequestContext('fake', 'fake') spec = objects.RequestSpec(ctxt) spec._from_retry(retry_dict) self.assertIsNone(spec.retry) def test_populate_group_info(self): filt_props = {} filt_props['group_updated'] = True filt_props['group_policies'] = set(['affinity']) filt_props['group_hosts'] = set(['fake1']) filt_props['group_members'] = set(['fake-instance1']) spec = objects.RequestSpec() spec._populate_group_info(filt_props) self.assertIsInstance(spec.instance_group, objects.InstanceGroup) self.assertEqual(['affinity'], spec.instance_group.policies) self.assertEqual(['fake1'], spec.instance_group.hosts) self.assertEqual(['fake-instance1'], spec.instance_group.members) def test_populate_group_info_missing_values(self): filt_props = {} spec = objects.RequestSpec() spec._populate_group_info(filt_props) self.assertIsNone(spec.instance_group) def test_from_limits(self): limits_dict = {'numa_topology': None, 'vcpu': 1.0, 'disk_gb': 1.0, 'memory_mb': 1.0} spec = objects.RequestSpec() spec._from_limits(limits_dict) self.assertIsInstance(spec.limits, objects.SchedulerLimits) self.assertIsNone(spec.limits.numa_topology) self.assertEqual(1, spec.limits.vcpu) self.assertEqual(1, spec.limits.disk_gb) self.assertEqual(1, spec.limits.memory_mb) def test_from_limits_missing_values(self): limits_dict = {} spec = objects.RequestSpec() spec._from_limits(limits_dict) self.assertIsInstance(spec.limits, objects.SchedulerLimits) self.assertIsNone(spec.limits.numa_topology) self.assertIsNone(spec.limits.vcpu) self.assertIsNone(spec.limits.disk_gb) self.assertIsNone(spec.limits.memory_mb) def test_from_hints(self): hints_dict = {'foo_str': '1', 'bar_list': ['2']} spec = objects.RequestSpec() spec._from_hints(hints_dict) expected = {'foo_str': ['1'], 'bar_list': ['2']} self.assertEqual(expected, spec.scheduler_hints) def test_from_hints_with_no_hints(self): spec = objects.RequestSpec() spec._from_hints(None) self.assertIsNone(spec.scheduler_hints) @mock.patch.object(objects.SchedulerLimits, 'from_dict') def test_from_primitives(self, mock_limits): spec_dict = {'instance_type': objects.Flavor(), 'instance_properties': objects.Instance( uuid=uuidutils.generate_uuid(), numa_topology=None, pci_requests=None, project_id=1, availability_zone='nova')} filt_props = {} # We seriously don't care about the return values, we just want to make # sure that all the fields are set mock_limits.return_value = None ctxt = context.RequestContext('fake', 'fake') spec = objects.RequestSpec.from_primitives(ctxt, spec_dict, filt_props) mock_limits.assert_called_once_with({}) # Make sure that all fields are set using that helper method for field in [f for f in spec.obj_fields if f != 'id']: self.assertTrue(spec.obj_attr_is_set(field), 'Field: %s is not set' % field) # just making sure that the context is set by the method self.assertEqual(ctxt, spec._context) def test_from_components(self): ctxt = context.RequestContext('fake-user', 'fake-project') instance = fake_instance.fake_instance_obj(ctxt) image = {'id': 'fake-image-id', 'properties': {'mappings': []}, 'status': 'fake-status', 'location': 'far-away'} flavor = fake_flavor.fake_flavor_obj(ctxt) filter_properties = {} instance_group = None spec = objects.RequestSpec.from_components(ctxt, instance, image, flavor, instance.numa_topology, instance.pci_requests, filter_properties, instance_group, instance.availability_zone) # Make sure that all fields are set using that helper method for field in [f for f in spec.obj_fields if f != 'id']: self.assertEqual(True, spec.obj_attr_is_set(field), 'Field: %s is not set' % field) # just making sure that the context is set by the method self.assertEqual(ctxt, spec._context) def test_get_scheduler_hint(self): spec_obj = objects.RequestSpec(scheduler_hints={'foo_single': ['1'], 'foo_mul': ['1', '2']}) self.assertEqual('1', spec_obj.get_scheduler_hint('foo_single')) self.assertEqual(['1', '2'], spec_obj.get_scheduler_hint('foo_mul')) self.assertIsNone(spec_obj.get_scheduler_hint('oops')) self.assertEqual('bar', spec_obj.get_scheduler_hint('oops', default='bar')) def test_get_scheduler_hint_with_no_hints(self): spec_obj = objects.RequestSpec() self.assertEqual('bar', spec_obj.get_scheduler_hint('oops', default='bar')) @mock.patch.object(objects.RequestSpec, '_to_legacy_instance') @mock.patch.object(base, 'obj_to_primitive') def test_to_legacy_request_spec_dict(self, image_to_primitive, spec_to_legacy_instance): fake_image_dict = mock.Mock() image_to_primitive.return_value = fake_image_dict fake_instance = {'root_gb': 1.0, 'ephemeral_gb': 1.0, 'memory_mb': 1.0, 'vcpus': 1, 'numa_topology': None, 'pci_requests': None, 'project_id': '1', 'availability_zone': 'nova', 'uuid': '1'} spec_to_legacy_instance.return_value = fake_instance fake_flavor = objects.Flavor(root_gb=10, ephemeral_gb=0, memory_mb=512, vcpus=1) spec = objects.RequestSpec(num_instances=1, image=objects.ImageMeta(), # instance properties numa_topology=None, pci_requests=None, project_id=1, availability_zone='nova', instance_uuid='1', flavor=fake_flavor) spec_dict = spec.to_legacy_request_spec_dict() expected = {'num_instances': 1, 'image': fake_image_dict, 'instance_properties': fake_instance, 'instance_type': fake_flavor} self.assertEqual(expected, spec_dict) def test_to_legacy_request_spec_dict_with_unset_values(self): spec = objects.RequestSpec() self.assertEqual({'num_instances': 1, 'image': {}, 'instance_properties': {}, 'instance_type': {}}, spec.to_legacy_request_spec_dict()) def test_to_legacy_filter_properties_dict(self): fake_numa_limits = objects.NUMATopologyLimits() fake_computes_obj = objects.ComputeNodeList( objects=[objects.ComputeNode(host='fake1', hypervisor_hostname='node1')]) spec = objects.RequestSpec( ignore_hosts=['ignoredhost'], force_hosts=['fakehost'], force_nodes=['fakenode'], retry=objects.SchedulerRetries(num_attempts=1, hosts=fake_computes_obj), limits=objects.SchedulerLimits(numa_topology=fake_numa_limits, vcpu=1.0, disk_gb=10.0, memory_mb=8192.0), instance_group=objects.InstanceGroup(hosts=['fake1'], policies=['affinity']), scheduler_hints={'foo': ['bar']}) expected = {'ignore_hosts': ['ignoredhost'], 'force_hosts': ['fakehost'], 'force_nodes': ['fakenode'], 'retry': {'num_attempts': 1, 'hosts': [['fake1', 'node1']]}, 'limits': {'numa_topology': fake_numa_limits, 'vcpu': 1.0, 'disk_gb': 10.0, 'memory_mb': 8192.0}, 'group_updated': True, 'group_hosts': set(['fake1']), 'group_policies': set(['affinity']), 'scheduler_hints': {'foo': 'bar'}} self.assertEqual(expected, spec.to_legacy_filter_properties_dict()) def test_to_legacy_filter_properties_dict_with_nullable_values(self): spec = objects.RequestSpec(force_hosts=None, force_nodes=None, retry=None, limits=None, instance_group=None, scheduler_hints=None) self.assertEqual({}, spec.to_legacy_filter_properties_dict()) def test_to_legacy_filter_properties_dict_with_unset_values(self): spec = objects.RequestSpec() self.assertEqual({}, spec.to_legacy_filter_properties_dict()) @mock.patch.object(request_spec.RequestSpec, '_get_by_instance_uuid_from_db') def test_get_by_instance_uuid(self, get_by_uuid): fake_spec = fake_request_spec.fake_db_spec() get_by_uuid.return_value = fake_spec req_obj = request_spec.RequestSpec.get_by_instance_uuid(self.context, fake_spec['instance_uuid']) self.assertEqual(1, req_obj.num_instances) self.assertEqual(['host2', 'host4'], req_obj.ignore_hosts) self.assertEqual('fake', req_obj.project_id) self.assertEqual({'hint': ['over-there']}, req_obj.scheduler_hints) self.assertEqual(['host1', 'host3'], req_obj.force_hosts) self.assertIsNone(req_obj.availability_zone) self.assertEqual(['node1', 'node2'], req_obj.force_nodes) self.assertIsInstance(req_obj.image, objects.ImageMeta) self.assertIsInstance(req_obj.numa_topology, objects.InstanceNUMATopology) self.assertIsInstance(req_obj.pci_requests, objects.InstancePCIRequests) self.assertIsInstance(req_obj.flavor, objects.Flavor) self.assertIsInstance(req_obj.retry, objects.SchedulerRetries) self.assertIsInstance(req_obj.limits, objects.SchedulerLimits) self.assertIsInstance(req_obj.instance_group, objects.InstanceGroup) def _check_update_primitive(self, req_obj, changes): self.assertEqual(req_obj.instance_uuid, changes['instance_uuid']) serialized_obj = objects.RequestSpec.obj_from_primitive( jsonutils.loads(changes['spec'])) # primitive fields for field in ['instance_uuid', 'num_instances', 'ignore_hosts', 'project_id', 'scheduler_hints', 'force_hosts', 'availability_zone', 'force_nodes']: self.assertEqual(getattr(req_obj, field), getattr(serialized_obj, field)) # object fields for field in ['image', 'numa_topology', 'pci_requests', 'flavor', 'retry', 'limits', 'instance_group']: self.assertDictEqual( getattr(req_obj, field).obj_to_primitive(), getattr(serialized_obj, field).obj_to_primitive()) def test_create(self): req_obj = fake_request_spec.fake_spec_obj(remove_id=True) def _test_create_args(self2, context, changes): self._check_update_primitive(req_obj, changes) # DB creation would have set an id changes['id'] = 42 return changes with mock.patch.object(request_spec.RequestSpec, '_create_in_db', _test_create_args): req_obj.create() def test_create_id_set(self): req_obj = request_spec.RequestSpec(self.context) req_obj.id = 3 self.assertRaises(exception.ObjectActionError, req_obj.create) def test_save(self): req_obj = fake_request_spec.fake_spec_obj() def _test_save_args(self2, context, instance_uuid, changes): self._check_update_primitive(req_obj, changes) # DB creation would have set an id changes['id'] = 42 return changes with mock.patch.object(request_spec.RequestSpec, '_save_in_db', _test_save_args): req_obj.save() class TestRequestSpecObject(test_objects._LocalTest, _TestRequestSpecObject): pass class TestRemoteRequestSpecObject(test_objects._RemoteTest, _TestRequestSpecObject): pass
apache-2.0
zappala/bene
src/buffer.py
2
5376
class SendBuffer(object): """ Send buffer for transport protocols """ def __init__(self): """ The buffer holds a series of characters to send. The base is the starting sequence number of the buffer. The next value is the sequence number for the next data that has not yet been sent. The last value is the sequence number for the last data in the buffer.""" self.buffer = b'' self.base_seq = 0 self.next_seq = 0 self.last_seq = 0 def available(self): """ Return number of bytes available to send. This is data that could be sent but hasn't.""" return self.last_seq - self.next_seq def outstanding(self): """ Return number of outstanding bytes. This is data that has been sent but not yet acked.""" return self.next_seq - self.base_seq def put(self, data): """ Put some data into the buffer """ self.buffer += data self.last_seq += len(data) def get(self, size): """ Get the next data that has not been sent yet. Return the data and the starting sequence number of this data. The total amount of data returned is at most size bytes but may be less.""" if self.next_seq + size > self.last_seq: size = self.last_seq - self.next_seq start = self.next_seq - self.base_seq data = self.buffer[start:start + size] sequence = self.next_seq self.next_seq = self.next_seq + size return data, sequence def resend(self, size, reset=True): """ Get oldest data that is outstanding, so it can be resent. Return the data and the starting sequence number of this data. The total amount of data returned is at most size bytes but may be less. If reset is true, then all other data that was outstanding is now treated as if it was never sent. This is standard practice for TCP when retransmitting.""" if self.base_seq + size > self.last_seq: size = self.last_seq - self.base_seq data = self.buffer[:size] sequence = self.base_seq if reset: self.next_seq = sequence + size return data, sequence def slide(self, sequence): """ Slide the receive window to the acked sequence number. This sequence number represents the lowest sequence number that is not yet acked. In other words, the ACK is for all data less than but not equal to this sequence number.""" acked = sequence - self.base_seq self.buffer = self.buffer[acked:] self.base_seq = sequence # adjust next in case we slide past it if self.next_seq < self.base_seq: self.next_seq = self.base_seq class Chunk(object): """ Chunk of data stored in receive buffer. """ def __init__(self, data, sequence): self.data = data self.length = len(data) self.sequence = sequence def trim(self, sequence, length): """ Check for overlap with a previous chunk and trim this chunk if needed.""" # check for overlap if self.sequence < sequence + length: self.data = self.data[sequence + length:] self.length = len(self.data) self.sequence = sequence + length class ReceiveBuffer(object): """ Receive buffer for transport protocols """ def __init__(self): """ The buffer holds all the data that has been received, indexed by starting sequence number. Data may come in out of order, so this buffer will order them. Data may also be duplicated, so this buffer will remove any duplicate bytes.""" self.buffer = {} # starting sequence number self.base_seq = 0 def put(self, data, sequence): """ Add data to the receive buffer. Put it in order of sequence number and remove any duplicate data.""" # ignore old chunk if sequence < self.base_seq: return # ignore duplicate chunk if sequence in self.buffer: if self.buffer[sequence].length >= len(data): return self.buffer[sequence] = Chunk(data, sequence) # remove overlapping data next_data = -1 length = 0 for sequence in sorted(self.buffer.keys()): chunk = self.buffer[sequence] # trim chunk if there is duplicate data from the previous chunk chunk.trim(next_data, length) if chunk.length == 0: # remove chunk del self.buffer[sequence] next_data = chunk.sequence length = len(chunk.data) def get(self): """ Get and remove all data that is in order. Return the data and its starting sequence number. """ data = b'' start = self.base_seq for sequence in sorted(self.buffer.keys()): chunk = self.buffer[sequence] if chunk.sequence == self.base_seq: # append the data, adjust the base, delete the chunk data += chunk.data self.base_seq += chunk.length del self.buffer[chunk.sequence] return data, start
gpl-2.0
jhawkesworth/ansible
lib/ansible/modules/storage/netapp/_na_cdot_volume.py
59
15187
#!/usr/bin/python # (c) 2017, NetApp, Inc # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['deprecated'], 'supported_by': 'community'} DOCUMENTATION = ''' module: na_cdot_volume short_description: Manage NetApp cDOT volumes extends_documentation_fragment: - netapp.ontap version_added: '2.3' author: Sumit Kumar (@timuster) <sumit4@netapp.com> deprecated: removed_in: '2.11' why: Updated modules released with increased functionality alternative: Use M(na_ontap_volume) instead. description: - Create or destroy volumes on NetApp cDOT options: state: description: - Whether the specified volume should exist or not. required: true choices: ['present', 'absent'] name: description: - The name of the volume to manage. required: true infinite: description: - Set True if the volume is an Infinite Volume. type: bool default: 'no' online: description: - Whether the specified volume is online, or not. type: bool default: 'yes' aggregate_name: description: - The name of the aggregate the flexvol should exist on. Required when C(state=present). size: description: - The size of the volume in (size_unit). Required when C(state=present). size_unit: description: - The unit used to interpret the size parameter. choices: ['bytes', 'b', 'kb', 'mb', 'gb', 'tb', 'pb', 'eb', 'zb', 'yb'] default: 'gb' vserver: description: - Name of the vserver to use. required: true junction_path: description: - Junction path where to mount the volume required: false version_added: '2.6' export_policy: description: - Export policy to set for the specified junction path. required: false default: default version_added: '2.6' snapshot_policy: description: - Snapshot policy to set for the specified volume. required: false default: default version_added: '2.6' ''' EXAMPLES = """ - name: Create FlexVol na_cdot_volume: state: present name: ansibleVolume infinite: False aggregate_name: aggr1 size: 20 size_unit: mb vserver: ansibleVServer hostname: "{{ netapp_hostname }}" username: "{{ netapp_username }}" password: "{{ netapp_password }}" junction_path: /ansibleVolume export_policy: all_nfs_networks snapshot_policy: daily - name: Make FlexVol offline na_cdot_volume: state: present name: ansibleVolume infinite: False online: False vserver: ansibleVServer hostname: "{{ netapp_hostname }}" username: "{{ netapp_username }}" password: "{{ netapp_password }}" """ RETURN = """ """ import traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_native import ansible.module_utils.netapp as netapp_utils HAS_NETAPP_LIB = netapp_utils.has_netapp_lib() class NetAppCDOTVolume(object): def __init__(self): self._size_unit_map = dict( bytes=1, b=1, kb=1024, mb=1024 ** 2, gb=1024 ** 3, tb=1024 ** 4, pb=1024 ** 5, eb=1024 ** 6, zb=1024 ** 7, yb=1024 ** 8 ) self.argument_spec = netapp_utils.ontap_sf_host_argument_spec() self.argument_spec.update(dict( state=dict(required=True, choices=['present', 'absent']), name=dict(required=True, type='str'), is_infinite=dict(required=False, type='bool', default=False, aliases=['infinite']), is_online=dict(required=False, type='bool', default=True, aliases=['online']), size=dict(type='int'), size_unit=dict(default='gb', choices=['bytes', 'b', 'kb', 'mb', 'gb', 'tb', 'pb', 'eb', 'zb', 'yb'], type='str'), aggregate_name=dict(type='str'), vserver=dict(required=True, type='str', default=None), junction_path=dict(required=False, type='str', default=None), export_policy=dict(required=False, type='str', default='default'), snapshot_policy=dict(required=False, type='str', default='default'), )) self.module = AnsibleModule( argument_spec=self.argument_spec, required_if=[ ('state', 'present', ['aggregate_name', 'size']) ], supports_check_mode=True ) p = self.module.params # set up state variables self.state = p['state'] self.name = p['name'] self.is_infinite = p['is_infinite'] self.is_online = p['is_online'] self.size_unit = p['size_unit'] self.vserver = p['vserver'] self.junction_path = p['junction_path'] self.export_policy = p['export_policy'] self.snapshot_policy = p['snapshot_policy'] if p['size'] is not None: self.size = p['size'] * self._size_unit_map[self.size_unit] else: self.size = None self.aggregate_name = p['aggregate_name'] if HAS_NETAPP_LIB is False: self.module.fail_json(msg="the python NetApp-Lib module is required") else: self.server = netapp_utils.setup_ontap_zapi(module=self.module, vserver=self.vserver) def get_volume(self): """ Return details about the volume :param: name : Name of the volume :return: Details about the volume. None if not found. :rtype: dict """ volume_info = netapp_utils.zapi.NaElement('volume-get-iter') volume_attributes = netapp_utils.zapi.NaElement('volume-attributes') volume_id_attributes = netapp_utils.zapi.NaElement('volume-id-attributes') volume_id_attributes.add_new_child('name', self.name) volume_attributes.add_child_elem(volume_id_attributes) query = netapp_utils.zapi.NaElement('query') query.add_child_elem(volume_attributes) volume_info.add_child_elem(query) result = self.server.invoke_successfully(volume_info, True) return_value = None if result.get_child_by_name('num-records') and \ int(result.get_child_content('num-records')) >= 1: volume_attributes = result.get_child_by_name( 'attributes-list').get_child_by_name( 'volume-attributes') # Get volume's current size volume_space_attributes = volume_attributes.get_child_by_name( 'volume-space-attributes') current_size = volume_space_attributes.get_child_content('size') # Get volume's state (online/offline) volume_state_attributes = volume_attributes.get_child_by_name( 'volume-state-attributes') current_state = volume_state_attributes.get_child_content('state') is_online = None if current_state == "online": is_online = True elif current_state == "offline": is_online = False return_value = { 'name': self.name, 'size': current_size, 'is_online': is_online, } return return_value def create_volume(self): create_parameters = {'volume': self.name, 'containing-aggr-name': self.aggregate_name, 'size': str(self.size), } if self.junction_path: create_parameters['junction-path'] = str(self.junction_path) if self.export_policy != 'default': create_parameters['export-policy'] = str(self.export_policy) if self.snapshot_policy != 'default': create_parameters['snapshot-policy'] = str(self.snapshot_policy) volume_create = netapp_utils.zapi.NaElement.create_node_with_children( 'volume-create', **create_parameters) try: self.server.invoke_successfully(volume_create, enable_tunneling=True) except netapp_utils.zapi.NaApiError as e: self.module.fail_json(msg='Error provisioning volume %s of size %s: %s' % (self.name, self.size, to_native(e)), exception=traceback.format_exc()) def delete_volume(self): if self.is_infinite: volume_delete = netapp_utils.zapi.NaElement.create_node_with_children( 'volume-destroy-async', **{'volume-name': self.name}) else: volume_delete = netapp_utils.zapi.NaElement.create_node_with_children( 'volume-destroy', **{'name': self.name, 'unmount-and-offline': 'true'}) try: self.server.invoke_successfully(volume_delete, enable_tunneling=True) except netapp_utils.zapi.NaApiError as e: self.module.fail_json(msg='Error deleting volume %s: %s' % (self.name, to_native(e)), exception=traceback.format_exc()) def rename_volume(self): """ Rename the volume. Note: 'is_infinite' needs to be set to True in order to rename an Infinite Volume. """ if self.is_infinite: volume_rename = netapp_utils.zapi.NaElement.create_node_with_children( 'volume-rename-async', **{'volume-name': self.name, 'new-volume-name': str( self.name)}) else: volume_rename = netapp_utils.zapi.NaElement.create_node_with_children( 'volume-rename', **{'volume': self.name, 'new-volume-name': str( self.name)}) try: self.server.invoke_successfully(volume_rename, enable_tunneling=True) except netapp_utils.zapi.NaApiError as e: self.module.fail_json(msg='Error renaming volume %s: %s' % (self.name, to_native(e)), exception=traceback.format_exc()) def resize_volume(self): """ Re-size the volume. Note: 'is_infinite' needs to be set to True in order to rename an Infinite Volume. """ if self.is_infinite: volume_resize = netapp_utils.zapi.NaElement.create_node_with_children( 'volume-size-async', **{'volume-name': self.name, 'new-size': str( self.size)}) else: volume_resize = netapp_utils.zapi.NaElement.create_node_with_children( 'volume-size', **{'volume': self.name, 'new-size': str( self.size)}) try: self.server.invoke_successfully(volume_resize, enable_tunneling=True) except netapp_utils.zapi.NaApiError as e: self.module.fail_json(msg='Error re-sizing volume %s: %s' % (self.name, to_native(e)), exception=traceback.format_exc()) def change_volume_state(self): """ Change volume's state (offline/online). Note: 'is_infinite' needs to be set to True in order to change the state of an Infinite Volume. """ state_requested = None if self.is_online: # Requested state is 'online'. state_requested = "online" if self.is_infinite: volume_change_state = netapp_utils.zapi.NaElement.create_node_with_children( 'volume-online-async', **{'volume-name': self.name}) else: volume_change_state = netapp_utils.zapi.NaElement.create_node_with_children( 'volume-online', **{'name': self.name}) else: # Requested state is 'offline'. state_requested = "offline" if self.is_infinite: volume_change_state = netapp_utils.zapi.NaElement.create_node_with_children( 'volume-offline-async', **{'volume-name': self.name}) else: volume_change_state = netapp_utils.zapi.NaElement.create_node_with_children( 'volume-offline', **{'name': self.name}) try: self.server.invoke_successfully(volume_change_state, enable_tunneling=True) except netapp_utils.zapi.NaApiError as e: self.module.fail_json(msg='Error changing the state of volume %s to %s: %s' % (self.name, state_requested, to_native(e)), exception=traceback.format_exc()) def apply(self): changed = False volume_exists = False rename_volume = False resize_volume = False volume_detail = self.get_volume() if volume_detail: volume_exists = True if self.state == 'absent': changed = True elif self.state == 'present': if str(volume_detail['size']) != str(self.size): resize_volume = True changed = True if (volume_detail['is_online'] is not None) and (volume_detail['is_online'] != self.is_online): changed = True if self.is_online is False: # Volume is online, but requested state is offline pass else: # Volume is offline but requested state is online pass else: if self.state == 'present': changed = True if changed: if self.module.check_mode: pass else: if self.state == 'present': if not volume_exists: self.create_volume() else: if resize_volume: self.resize_volume() if volume_detail['is_online'] is not \ None and volume_detail['is_online'] != \ self.is_online: self.change_volume_state() # Ensure re-naming is the last change made. if rename_volume: self.rename_volume() elif self.state == 'absent': self.delete_volume() self.module.exit_json(changed=changed) def main(): v = NetAppCDOTVolume() v.apply() if __name__ == '__main__': main()
gpl-3.0