repo_name
stringlengths
5
100
path
stringlengths
4
375
copies
stringclasses
991 values
size
stringlengths
4
7
content
stringlengths
666
1M
license
stringclasses
15 values
fumitoh/modelx
modelx/qtgui/modeltree.py
1
13640
# Copyright (c) 2017-2021 Fumito Hamamura <fumito.ham@gmail.com> # This library is free software: you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation version 3. # # 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, see <http://www.gnu.org/licenses/>. # The source code in this file is modified from: # https://github.com/baoboa/pyqt5/blob/master/examples/itemviews/simpletreemodel/simpletreemodel.py # See below for the original copyright notice. ############################################################################# ## ## Copyright (C) 2013 Riverbank Computing Limited. ## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ## All rights reserved. ## ## This file is part of the examples of PyQt. ## ## $QT_BEGIN_LICENSE:BSD$ ## You may use this file under the terms of the BSD license as follows: ## ## "Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in ## the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor ## the names of its contributors may be used to endorse or promote ## products derived from this software without specific prior written ## permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ## $QT_END_LICENSE$ ## ############################################################################# import itertools from qtpy.QtCore import QAbstractItemModel, QModelIndex, Qt class BaseItem(object): """Base Item class for all tree item classes.""" def __init__(self, data, parent=None): self.colType = 1 self.colParam = 2 self.parentItem = parent self.itemData = None self.childItems = [] self.updateData(data) def updateData(self, data): if self.itemData != data: self.itemData = data self.updateChild() else: self.itemData = data def updateChild(self): raise NotImplementedError def changeParent(self, parent): self.parentItem = parent def appendChild(self, item): item.changeParent(self) self.childItems.append(item) def insertChild(self, index, item): item.changeParent(self) self.childItems.insert(index, item) def child(self, row): return self.childItems[row] def childCount(self): return len(self.childItems) def columnCount(self): return 3 def data(self, column): if column == 0: return self.itemData["name"] elif column == self.colType: return self.getType() elif column == self.colParam: return self.getParams() else: raise IndexError def parent(self): return self.parentItem def row(self): if self.parentItem: return self.parentItem.childItems.index(self) return 0 def getType(self): raise NotImplementedError def getParams(self): raise NotImplementedError class InterfaceItem(BaseItem): """Object item, such as Model, Space, Cells""" @property def objid(self): return self.itemData["id"] def __eq__(self, other): if isinstance(other, InterfaceItem): return self.objid == other.objid else: return False def __hash__(self): return hash(self.objid) class ViewItem(BaseItem): @property def attrid(self): return self.getType() def __eq__(self, other): if isinstance(other, ViewItem): return ( self.parent() == other.parent() and self.attrid == other.attrid ) def __hash__(self): return hash((self.parent().objid, self.attrid)) class SpaceContainerItem(InterfaceItem): """Base Item class for Models and Spaces which inherit SpaceContainer.""" def updateChild(self): self.childItems = self.newChildItems(self.itemData) def newChildItems(self, data): return [ SpaceItem(space, self) for space in data["spaces"]["items"].values() ] class ModelItem(SpaceContainerItem): """Item class for a Model (root item)""" def __init__(self, data): super(ModelItem, self).__init__(data, parent=None) def getType(self): return "Model" def getParams(self): return "" class SpaceItem(SpaceContainerItem): """Item class for Space objects.""" def updateChild(self): self.childItems.clear() for space in self.itemData["named_spaces"]["items"].values(): self.childItems.append(SpaceItem(space, self)) dynspaces = self.itemData["named_itemspaces"]["items"] if len(dynspaces) > 0: self.childItems.append(DynamicSpaceMapItem(dynspaces, self)) cellsmap = self.itemData["cells"]["items"] for cells in cellsmap.values(): self.childItems.append(CellsItem(cells, self)) def getType(self): return "Space" def getParams(self): if "argvalues" in self.itemData: args = self.itemData["argvalues"] if args is not None: return args else: return "" else: return "" class DynamicSpaceMapItem(ViewItem): """Item class for parent nodes of dynamic spaces of a space.""" def updateChild(self): self.childItems.clear() for space in self.itemData.values(): self.childItems.append(SpaceItem(space, self)) def data(self, column): if column == 0: return "Dynamic Spaces" else: return BaseItem.data(self, column) def getType(self): return "" def getParams(self): return self.parent().itemData["params"] class CellsItem(InterfaceItem): """Item class for cells objects.""" def updateChild(self): pass def getType(self): return "Cells" def getParams(self): return self.itemData["params"] class ModelTreeModel(QAbstractItemModel): def __init__(self, data, parent=None): super(ModelTreeModel, self).__init__(parent) self.rootItem = ModelItem(data) def updateRoot(self, data): newmodel = ModelItem(data) self.updateItem(QModelIndex(), newmodel) def getItem(self, index): if not index.isValid(): return self.rootItem else: return index.internalPointer() def updateItem(self, index, newitem, recursive=True): if not index.isValid(): item = self.rootItem else: item = index.internalPointer() if item.itemData != newitem.itemData: item.itemData = newitem.itemData # self.dataChanged.emit(index, index) delItems = set(item.childItems) - set(newitem.childItems) if delItems: delRows = sorted([item.row() for item in delItems]) delRows = [ list(g) for _, g in itertools.groupby( delRows, key=lambda n, c=itertools.count(): n - next(c) ) ] for rows in delRows: self.removeRows(rows[0], len(rows), index) addItems = set(newitem.childItems) - set(item.childItems) if addItems: addRows = sorted([item.row() for item in addItems]) addRows = [ list(g) for _, g in itertools.groupby( addRows, key=lambda n, c=itertools.count(): n - next(c) ) ] for rows in addRows: self.insertRows(rows, newitem, index) self.reorderChild(index, newitem) if recursive: for row, child in enumerate(item.childItems): child_index = self.index(row, 0, index) self.updateItem(child_index, newitem.childItems[row]) def insertRows(self, rows, newitem, parent): # Signature is different from the base method. item = self.getItem(parent) self.beginInsertRows(parent, rows[0], rows[-1]) for row in rows: item.insertChild(row, newitem.childItems[row]) self.endInsertRows() def removeRows(self, position, rows, parent=QModelIndex()): item = self.getItem(parent) self.beginRemoveRows(parent, position, position + rows - 1) for row in range(position, position + rows): item.childItems.pop(row) self.endRemoveRows() def reorderChild(self, parent, newitem): """Reorder a list to match target by moving a sequence at a time. Written for QtAbstractItemModel.moveRows. """ source = self.getItem(parent).childItems target = newitem.childItems i = 0 while i < len(source): if source[i] == target[i]: i += 1 continue else: i0 = i j0 = source.index(target[i0]) j = j0 + 1 while j < len(source): if source[j] == target[j - j0 + i0]: j += 1 continue else: break self.moveRows(parent, i0, j0, j - j0) i += j - j0 def moveRows(self, parent, index_to, index_from, length): """Move a sub sequence in a list index_to must be smaller than index_from """ source = self.getItem(parent).childItems self.beginMoveRows( parent, index_from, index_from + length - 1, parent, index_to ) sublist = [source.pop(index_from) for _ in range(length)] for _ in range(length): source.insert(index_to, sublist.pop()) self.endMoveRows() @property def modelid(self): if self.rootItem: return self.rootItem.objid else: return None def columnCount(self, parent): if parent.isValid(): return parent.internalPointer().columnCount() else: return self.rootItem.columnCount() def data(self, index, role): if not index.isValid(): return None if role != Qt.DisplayRole: return None item = index.internalPointer() return item.data(index.column()) def flags(self, index): if not index.isValid(): return Qt.NoItemFlags return Qt.ItemIsEnabled | Qt.ItemIsSelectable def headerData(self, section, orientation, role): if orientation == Qt.Horizontal and role == Qt.DisplayRole: # TODO: Refactor hard-coding column indexes if section == 0: return "Objects" elif section == 1: return "Type" elif section == 2: return "Parameters" return None def index(self, row, column, parent): if not self.hasIndex(row, column, parent): return QModelIndex() if not parent.isValid(): parentItem = self.rootItem else: parentItem = parent.internalPointer() childItem = parentItem.child(row) if childItem: return self.createIndex(row, column, childItem) else: return QModelIndex() def parent(self, index): if not index.isValid(): return QModelIndex() childItem = index.internalPointer() parentItem = childItem.parent() if parentItem is None or parentItem == self.rootItem: return QModelIndex() return self.createIndex(parentItem.row(), 0, parentItem) def rowCount(self, parent): if parent.column() > 0: return 0 if not parent.isValid(): parentItem = self.rootItem else: parentItem = parent.internalPointer() return parentItem.childCount()
gpl-3.0
Berserker66/FactorioManager
FactorioManager/paths.py
1
1357
__author__ = 'Fabian' import sys import appdirs import os import shutil join = os.path.join directories = appdirs.AppDirs("FactorioManager", "", roaming=True) configpath = join(directories.user_config_dir, "config.cfg") tempfolder = appdirs.user_cache_dir("FactorioManager", "", opinion=False) log = join(tempfolder, "log.txt") errorlog = join(tempfolder, "errorlog.txt") assert(tempfolder != directories.user_config_dir) if not os.path.exists(directories.user_config_dir): os.makedirs(directories.user_config_dir) def get_instances(): paths = set() if sys.platform.startswith("win"):#check for installed factorio factorioappdata = join(appdirs.user_config_dir("Factorio", "", roaming=True), "mods") if os.path.exists(factorioappdata): paths.add(factorioappdata) #TODO add configured paths return paths mods_folders = get_instances() def clean(): if os.path.exists(tempfolder): for file_object in os.listdir(tempfolder): file_object_path = os.path.join(tempfolder, file_object) try: if os.path.isfile(file_object_path): os.unlink(file_object_path) else: shutil.rmtree(file_object_path) except PermissionError: pass else: os.makedirs(tempfolder) clean()
mit
villip/moon-safari
node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py
1366
120842
# 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. """Xcode project file generator. This module is both an Xcode project file generator and a documentation of the Xcode project file format. Knowledge of the project file format was gained based on extensive experience with Xcode, and by making changes to projects in Xcode.app and observing the resultant changes in the associated project files. XCODE PROJECT FILES The generator targets the file format as written by Xcode 3.2 (specifically, 3.2.6), but past experience has taught that the format has not changed significantly in the past several years, and future versions of Xcode are able to read older project files. Xcode project files are "bundled": the project "file" from an end-user's perspective is actually a directory with an ".xcodeproj" extension. The project file from this module's perspective is actually a file inside this directory, always named "project.pbxproj". This file contains a complete description of the project and is all that is needed to use the xcodeproj. Other files contained in the xcodeproj directory are simply used to store per-user settings, such as the state of various UI elements in the Xcode application. The project.pbxproj file is a property list, stored in a format almost identical to the NeXTstep property list format. The file is able to carry Unicode data, and is encoded in UTF-8. The root element in the property list is a dictionary that contains several properties of minimal interest, and two properties of immense interest. The most important property is a dictionary named "objects". The entire structure of the project is represented by the children of this property. The objects dictionary is keyed by unique 96-bit values represented by 24 uppercase hexadecimal characters. Each value in the objects dictionary is itself a dictionary, describing an individual object. Each object in the dictionary is a member of a class, which is identified by the "isa" property of each object. A variety of classes are represented in a project file. Objects can refer to other objects by ID, using the 24-character hexadecimal object key. A project's objects form a tree, with a root object of class PBXProject at the root. As an example, the PBXProject object serves as parent to an XCConfigurationList object defining the build configurations used in the project, a PBXGroup object serving as a container for all files referenced in the project, and a list of target objects, each of which defines a target in the project. There are several different types of target object, such as PBXNativeTarget and PBXAggregateTarget. In this module, this relationship is expressed by having each target type derive from an abstract base named XCTarget. The project.pbxproj file's root dictionary also contains a property, sibling to the "objects" dictionary, named "rootObject". The value of rootObject is a 24-character object key referring to the root PBXProject object in the objects dictionary. In Xcode, every file used as input to a target or produced as a final product of a target must appear somewhere in the hierarchy rooted at the PBXGroup object referenced by the PBXProject's mainGroup property. A PBXGroup is generally represented as a folder in the Xcode application. PBXGroups can contain other PBXGroups as well as PBXFileReferences, which are pointers to actual files. Each XCTarget contains a list of build phases, represented in this module by the abstract base XCBuildPhase. Examples of concrete XCBuildPhase derivations are PBXSourcesBuildPhase and PBXFrameworksBuildPhase, which correspond to the "Compile Sources" and "Link Binary With Libraries" phases displayed in the Xcode application. Files used as input to these phases (for example, source files in the former case and libraries and frameworks in the latter) are represented by PBXBuildFile objects, referenced by elements of "files" lists in XCTarget objects. Each PBXBuildFile object refers to a PBXBuildFile object as a "weak" reference: it does not "own" the PBXBuildFile, which is owned by the root object's mainGroup or a descendant group. In most cases, the layer of indirection between an XCBuildPhase and a PBXFileReference via a PBXBuildFile appears extraneous, but there's actually one reason for this: file-specific compiler flags are added to the PBXBuildFile object so as to allow a single file to be a member of multiple targets while having distinct compiler flags for each. These flags can be modified in the Xcode applciation in the "Build" tab of a File Info window. When a project is open in the Xcode application, Xcode will rewrite it. As such, this module is careful to adhere to the formatting used by Xcode, to avoid insignificant changes appearing in the file when it is used in the Xcode application. This will keep version control repositories happy, and makes it possible to compare a project file used in Xcode to one generated by this module to determine if any significant changes were made in the application. Xcode has its own way of assigning 24-character identifiers to each object, which is not duplicated here. Because the identifier only is only generated once, when an object is created, and is then left unchanged, there is no need to attempt to duplicate Xcode's behavior in this area. The generator is free to select any identifier, even at random, to refer to the objects it creates, and Xcode will retain those identifiers and use them when subsequently rewriting the project file. However, the generator would choose new random identifiers each time the project files are generated, leading to difficulties comparing "used" project files to "pristine" ones produced by this module, and causing the appearance of changes as every object identifier is changed when updated projects are checked in to a version control repository. To mitigate this problem, this module chooses identifiers in a more deterministic way, by hashing a description of each object as well as its parent and ancestor objects. This strategy should result in minimal "shift" in IDs as successive generations of project files are produced. THIS MODULE This module introduces several classes, all derived from the XCObject class. Nearly all of the "brains" are built into the XCObject class, which understands how to create and modify objects, maintain the proper tree structure, compute identifiers, and print objects. For the most part, classes derived from XCObject need only provide a _schema class object, a dictionary that expresses what properties objects of the class may contain. Given this structure, it's possible to build a minimal project file by creating objects of the appropriate types and making the proper connections: config_list = XCConfigurationList() group = PBXGroup() project = PBXProject({'buildConfigurationList': config_list, 'mainGroup': group}) With the project object set up, it can be added to an XCProjectFile object. XCProjectFile is a pseudo-class in the sense that it is a concrete XCObject subclass that does not actually correspond to a class type found in a project file. Rather, it is used to represent the project file's root dictionary. Printing an XCProjectFile will print the entire project file, including the full "objects" dictionary. project_file = XCProjectFile({'rootObject': project}) project_file.ComputeIDs() project_file.Print() Xcode project files are always encoded in UTF-8. This module will accept strings of either the str class or the unicode class. Strings of class str are assumed to already be encoded in UTF-8. Obviously, if you're just using ASCII, you won't encounter difficulties because ASCII is a UTF-8 subset. Strings of class unicode are handled properly and encoded in UTF-8 when a project file is output. """ import gyp.common import posixpath import re import struct import sys # hashlib is supplied as of Python 2.5 as the replacement interface for sha # and other secure hashes. In 2.6, sha is deprecated. Import hashlib if # available, avoiding a deprecation warning under 2.6. Import sha otherwise, # preserving 2.4 compatibility. try: import hashlib _new_sha1 = hashlib.sha1 except ImportError: import sha _new_sha1 = sha.new # See XCObject._EncodeString. This pattern is used to determine when a string # can be printed unquoted. Strings that match this pattern may be printed # unquoted. Strings that do not match must be quoted and may be further # transformed to be properly encoded. Note that this expression matches the # characters listed with "+", for 1 or more occurrences: if a string is empty, # it must not match this pattern, because it needs to be encoded as "". _unquoted = re.compile('^[A-Za-z0-9$./_]+$') # Strings that match this pattern are quoted regardless of what _unquoted says. # Oddly, Xcode will quote any string with a run of three or more underscores. _quoted = re.compile('___') # This pattern should match any character that needs to be escaped by # XCObject._EncodeString. See that function. _escaped = re.compile('[\\\\"]|[\x00-\x1f]') # Used by SourceTreeAndPathFromPath _path_leading_variable = re.compile(r'^\$\((.*?)\)(/(.*))?$') def SourceTreeAndPathFromPath(input_path): """Given input_path, returns a tuple with sourceTree and path values. Examples: input_path (source_tree, output_path) '$(VAR)/path' ('VAR', 'path') '$(VAR)' ('VAR', None) 'path' (None, 'path') """ source_group_match = _path_leading_variable.match(input_path) if source_group_match: source_tree = source_group_match.group(1) output_path = source_group_match.group(3) # This may be None. else: source_tree = None output_path = input_path return (source_tree, output_path) def ConvertVariablesToShellSyntax(input_string): return re.sub(r'\$\((.*?)\)', '${\\1}', input_string) class XCObject(object): """The abstract base of all class types used in Xcode project files. Class variables: _schema: A dictionary defining the properties of this class. The keys to _schema are string property keys as used in project files. Values are a list of four or five elements: [ is_list, property_type, is_strong, is_required, default ] is_list: True if the property described is a list, as opposed to a single element. property_type: The type to use as the value of the property, or if is_list is True, the type to use for each element of the value's list. property_type must be an XCObject subclass, or one of the built-in types str, int, or dict. is_strong: If property_type is an XCObject subclass, is_strong is True to assert that this class "owns," or serves as parent, to the property value (or, if is_list is True, values). is_strong must be False if property_type is not an XCObject subclass. is_required: True if the property is required for the class. Note that is_required being True does not preclude an empty string ("", in the case of property_type str) or list ([], in the case of is_list True) from being set for the property. default: Optional. If is_requried is True, default may be set to provide a default value for objects that do not supply their own value. If is_required is True and default is not provided, users of the class must supply their own value for the property. Note that although the values of the array are expressed in boolean terms, subclasses provide values as integers to conserve horizontal space. _should_print_single_line: False in XCObject. Subclasses whose objects should be written to the project file in the alternate single-line format, such as PBXFileReference and PBXBuildFile, should set this to True. _encode_transforms: Used by _EncodeString to encode unprintable characters. The index into this list is the ordinal of the character to transform; each value is a string used to represent the character in the output. XCObject provides an _encode_transforms list suitable for most XCObject subclasses. _alternate_encode_transforms: Provided for subclasses that wish to use the alternate encoding rules. Xcode seems to use these rules when printing objects in single-line format. Subclasses that desire this behavior should set _encode_transforms to _alternate_encode_transforms. _hashables: A list of XCObject subclasses that can be hashed by ComputeIDs to construct this object's ID. Most classes that need custom hashing behavior should do it by overriding Hashables, but in some cases an object's parent may wish to push a hashable value into its child, and it can do so by appending to _hashables. Attributes: id: The object's identifier, a 24-character uppercase hexadecimal string. Usually, objects being created should not set id until the entire project file structure is built. At that point, UpdateIDs() should be called on the root object to assign deterministic values for id to each object in the tree. parent: The object's parent. This is set by a parent XCObject when a child object is added to it. _properties: The object's property dictionary. An object's properties are described by its class' _schema variable. """ _schema = {} _should_print_single_line = False # See _EncodeString. _encode_transforms = [] i = 0 while i < ord(' '): _encode_transforms.append('\\U%04x' % i) i = i + 1 _encode_transforms[7] = '\\a' _encode_transforms[8] = '\\b' _encode_transforms[9] = '\\t' _encode_transforms[10] = '\\n' _encode_transforms[11] = '\\v' _encode_transforms[12] = '\\f' _encode_transforms[13] = '\\n' _alternate_encode_transforms = list(_encode_transforms) _alternate_encode_transforms[9] = chr(9) _alternate_encode_transforms[10] = chr(10) _alternate_encode_transforms[11] = chr(11) def __init__(self, properties=None, id=None, parent=None): self.id = id self.parent = parent self._properties = {} self._hashables = [] self._SetDefaultsFromSchema() self.UpdateProperties(properties) def __repr__(self): try: name = self.Name() except NotImplementedError: return '<%s at 0x%x>' % (self.__class__.__name__, id(self)) return '<%s %r at 0x%x>' % (self.__class__.__name__, name, id(self)) def Copy(self): """Make a copy of this object. The new object will have its own copy of lists and dicts. Any XCObject objects owned by this object (marked "strong") will be copied in the new object, even those found in lists. If this object has any weak references to other XCObjects, the same references are added to the new object without making a copy. """ that = self.__class__(id=self.id, parent=self.parent) for key, value in self._properties.iteritems(): is_strong = self._schema[key][2] if isinstance(value, XCObject): if is_strong: new_value = value.Copy() new_value.parent = that that._properties[key] = new_value else: that._properties[key] = value elif isinstance(value, str) or isinstance(value, unicode) or \ isinstance(value, int): that._properties[key] = value elif isinstance(value, list): if is_strong: # If is_strong is True, each element is an XCObject, so it's safe to # call Copy. that._properties[key] = [] for item in value: new_item = item.Copy() new_item.parent = that that._properties[key].append(new_item) else: that._properties[key] = value[:] elif isinstance(value, dict): # dicts are never strong. if is_strong: raise TypeError('Strong dict for key ' + key + ' in ' + \ self.__class__.__name__) else: that._properties[key] = value.copy() else: raise TypeError('Unexpected type ' + value.__class__.__name__ + \ ' for key ' + key + ' in ' + self.__class__.__name__) return that def Name(self): """Return the name corresponding to an object. Not all objects necessarily need to be nameable, and not all that do have a "name" property. Override as needed. """ # If the schema indicates that "name" is required, try to access the # property even if it doesn't exist. This will result in a KeyError # being raised for the property that should be present, which seems more # appropriate than NotImplementedError in this case. if 'name' in self._properties or \ ('name' in self._schema and self._schema['name'][3]): return self._properties['name'] raise NotImplementedError(self.__class__.__name__ + ' must implement Name') def Comment(self): """Return a comment string for the object. Most objects just use their name as the comment, but PBXProject uses different values. The returned comment is not escaped and does not have any comment marker strings applied to it. """ return self.Name() def Hashables(self): hashables = [self.__class__.__name__] name = self.Name() if name != None: hashables.append(name) hashables.extend(self._hashables) return hashables def HashablesForChild(self): return None def ComputeIDs(self, recursive=True, overwrite=True, seed_hash=None): """Set "id" properties deterministically. An object's "id" property is set based on a hash of its class type and name, as well as the class type and name of all ancestor objects. As such, it is only advisable to call ComputeIDs once an entire project file tree is built. If recursive is True, recurse into all descendant objects and update their hashes. If overwrite is True, any existing value set in the "id" property will be replaced. """ def _HashUpdate(hash, data): """Update hash with data's length and contents. If the hash were updated only with the value of data, it would be possible for clowns to induce collisions by manipulating the names of their objects. By adding the length, it's exceedingly less likely that ID collisions will be encountered, intentionally or not. """ hash.update(struct.pack('>i', len(data))) hash.update(data) if seed_hash is None: seed_hash = _new_sha1() hash = seed_hash.copy() hashables = self.Hashables() assert len(hashables) > 0 for hashable in hashables: _HashUpdate(hash, hashable) if recursive: hashables_for_child = self.HashablesForChild() if hashables_for_child is None: child_hash = hash else: assert len(hashables_for_child) > 0 child_hash = seed_hash.copy() for hashable in hashables_for_child: _HashUpdate(child_hash, hashable) for child in self.Children(): child.ComputeIDs(recursive, overwrite, child_hash) if overwrite or self.id is None: # Xcode IDs are only 96 bits (24 hex characters), but a SHA-1 digest is # is 160 bits. Instead of throwing out 64 bits of the digest, xor them # into the portion that gets used. assert hash.digest_size % 4 == 0 digest_int_count = hash.digest_size / 4 digest_ints = struct.unpack('>' + 'I' * digest_int_count, hash.digest()) id_ints = [0, 0, 0] for index in xrange(0, digest_int_count): id_ints[index % 3] ^= digest_ints[index] self.id = '%08X%08X%08X' % tuple(id_ints) def EnsureNoIDCollisions(self): """Verifies that no two objects have the same ID. Checks all descendants. """ ids = {} descendants = self.Descendants() for descendant in descendants: if descendant.id in ids: other = ids[descendant.id] raise KeyError( 'Duplicate ID %s, objects "%s" and "%s" in "%s"' % \ (descendant.id, str(descendant._properties), str(other._properties), self._properties['rootObject'].Name())) ids[descendant.id] = descendant def Children(self): """Returns a list of all of this object's owned (strong) children.""" children = [] for property, attributes in self._schema.iteritems(): (is_list, property_type, is_strong) = attributes[0:3] if is_strong and property in self._properties: if not is_list: children.append(self._properties[property]) else: children.extend(self._properties[property]) return children def Descendants(self): """Returns a list of all of this object's descendants, including this object. """ children = self.Children() descendants = [self] for child in children: descendants.extend(child.Descendants()) return descendants def PBXProjectAncestor(self): # The base case for recursion is defined at PBXProject.PBXProjectAncestor. if self.parent: return self.parent.PBXProjectAncestor() return None def _EncodeComment(self, comment): """Encodes a comment to be placed in the project file output, mimicing Xcode behavior. """ # This mimics Xcode behavior by wrapping the comment in "/*" and "*/". If # the string already contains a "*/", it is turned into "(*)/". This keeps # the file writer from outputting something that would be treated as the # end of a comment in the middle of something intended to be entirely a # comment. return '/* ' + comment.replace('*/', '(*)/') + ' */' def _EncodeTransform(self, match): # This function works closely with _EncodeString. It will only be called # by re.sub with match.group(0) containing a character matched by the # the _escaped expression. char = match.group(0) # Backslashes (\) and quotation marks (") are always replaced with a # backslash-escaped version of the same. Everything else gets its # replacement from the class' _encode_transforms array. if char == '\\': return '\\\\' if char == '"': return '\\"' return self._encode_transforms[ord(char)] def _EncodeString(self, value): """Encodes a string to be placed in the project file output, mimicing Xcode behavior. """ # Use quotation marks when any character outside of the range A-Z, a-z, 0-9, # $ (dollar sign), . (period), and _ (underscore) is present. Also use # quotation marks to represent empty strings. # # Escape " (double-quote) and \ (backslash) by preceding them with a # backslash. # # Some characters below the printable ASCII range are encoded specially: # 7 ^G BEL is encoded as "\a" # 8 ^H BS is encoded as "\b" # 11 ^K VT is encoded as "\v" # 12 ^L NP is encoded as "\f" # 127 ^? DEL is passed through as-is without escaping # - In PBXFileReference and PBXBuildFile objects: # 9 ^I HT is passed through as-is without escaping # 10 ^J NL is passed through as-is without escaping # 13 ^M CR is passed through as-is without escaping # - In other objects: # 9 ^I HT is encoded as "\t" # 10 ^J NL is encoded as "\n" # 13 ^M CR is encoded as "\n" rendering it indistinguishable from # 10 ^J NL # All other characters within the ASCII control character range (0 through # 31 inclusive) are encoded as "\U001f" referring to the Unicode code point # in hexadecimal. For example, character 14 (^N SO) is encoded as "\U000e". # Characters above the ASCII range are passed through to the output encoded # as UTF-8 without any escaping. These mappings are contained in the # class' _encode_transforms list. if _unquoted.search(value) and not _quoted.search(value): return value return '"' + _escaped.sub(self._EncodeTransform, value) + '"' def _XCPrint(self, file, tabs, line): file.write('\t' * tabs + line) def _XCPrintableValue(self, tabs, value, flatten_list=False): """Returns a representation of value that may be printed in a project file, mimicing Xcode's behavior. _XCPrintableValue can handle str and int values, XCObjects (which are made printable by returning their id property), and list and dict objects composed of any of the above types. When printing a list or dict, and _should_print_single_line is False, the tabs parameter is used to determine how much to indent the lines corresponding to the items in the list or dict. If flatten_list is True, single-element lists will be transformed into strings. """ printable = '' comment = None if self._should_print_single_line: sep = ' ' element_tabs = '' end_tabs = '' else: sep = '\n' element_tabs = '\t' * (tabs + 1) end_tabs = '\t' * tabs if isinstance(value, XCObject): printable += value.id comment = value.Comment() elif isinstance(value, str): printable += self._EncodeString(value) elif isinstance(value, unicode): printable += self._EncodeString(value.encode('utf-8')) elif isinstance(value, int): printable += str(value) elif isinstance(value, list): if flatten_list and len(value) <= 1: if len(value) == 0: printable += self._EncodeString('') else: printable += self._EncodeString(value[0]) else: printable = '(' + sep for item in value: printable += element_tabs + \ self._XCPrintableValue(tabs + 1, item, flatten_list) + \ ',' + sep printable += end_tabs + ')' elif isinstance(value, dict): printable = '{' + sep for item_key, item_value in sorted(value.iteritems()): printable += element_tabs + \ self._XCPrintableValue(tabs + 1, item_key, flatten_list) + ' = ' + \ self._XCPrintableValue(tabs + 1, item_value, flatten_list) + ';' + \ sep printable += end_tabs + '}' else: raise TypeError("Can't make " + value.__class__.__name__ + ' printable') if comment != None: printable += ' ' + self._EncodeComment(comment) return printable def _XCKVPrint(self, file, tabs, key, value): """Prints a key and value, members of an XCObject's _properties dictionary, to file. tabs is an int identifying the indentation level. If the class' _should_print_single_line variable is True, tabs is ignored and the key-value pair will be followed by a space insead of a newline. """ if self._should_print_single_line: printable = '' after_kv = ' ' else: printable = '\t' * tabs after_kv = '\n' # Xcode usually prints remoteGlobalIDString values in PBXContainerItemProxy # objects without comments. Sometimes it prints them with comments, but # the majority of the time, it doesn't. To avoid unnecessary changes to # the project file after Xcode opens it, don't write comments for # remoteGlobalIDString. This is a sucky hack and it would certainly be # cleaner to extend the schema to indicate whether or not a comment should # be printed, but since this is the only case where the problem occurs and # Xcode itself can't seem to make up its mind, the hack will suffice. # # Also see PBXContainerItemProxy._schema['remoteGlobalIDString']. if key == 'remoteGlobalIDString' and isinstance(self, PBXContainerItemProxy): value_to_print = value.id else: value_to_print = value # PBXBuildFile's settings property is represented in the output as a dict, # but a hack here has it represented as a string. Arrange to strip off the # quotes so that it shows up in the output as expected. if key == 'settings' and isinstance(self, PBXBuildFile): strip_value_quotes = True else: strip_value_quotes = False # In another one-off, let's set flatten_list on buildSettings properties # of XCBuildConfiguration objects, because that's how Xcode treats them. if key == 'buildSettings' and isinstance(self, XCBuildConfiguration): flatten_list = True else: flatten_list = False try: printable_key = self._XCPrintableValue(tabs, key, flatten_list) printable_value = self._XCPrintableValue(tabs, value_to_print, flatten_list) if strip_value_quotes and len(printable_value) > 1 and \ printable_value[0] == '"' and printable_value[-1] == '"': printable_value = printable_value[1:-1] printable += printable_key + ' = ' + printable_value + ';' + after_kv except TypeError, e: gyp.common.ExceptionAppend(e, 'while printing key "%s"' % key) raise self._XCPrint(file, 0, printable) def Print(self, file=sys.stdout): """Prints a reprentation of this object to file, adhering to Xcode output formatting. """ self.VerifyHasRequiredProperties() if self._should_print_single_line: # When printing an object in a single line, Xcode doesn't put any space # between the beginning of a dictionary (or presumably a list) and the # first contained item, so you wind up with snippets like # ...CDEF = {isa = PBXFileReference; fileRef = 0123... # If it were me, I would have put a space in there after the opening # curly, but I guess this is just another one of those inconsistencies # between how Xcode prints PBXFileReference and PBXBuildFile objects as # compared to other objects. Mimic Xcode's behavior here by using an # empty string for sep. sep = '' end_tabs = 0 else: sep = '\n' end_tabs = 2 # Start the object. For example, '\t\tPBXProject = {\n'. self._XCPrint(file, 2, self._XCPrintableValue(2, self) + ' = {' + sep) # "isa" isn't in the _properties dictionary, it's an intrinsic property # of the class which the object belongs to. Xcode always outputs "isa" # as the first element of an object dictionary. self._XCKVPrint(file, 3, 'isa', self.__class__.__name__) # The remaining elements of an object dictionary are sorted alphabetically. for property, value in sorted(self._properties.iteritems()): self._XCKVPrint(file, 3, property, value) # End the object. self._XCPrint(file, end_tabs, '};\n') def UpdateProperties(self, properties, do_copy=False): """Merge the supplied properties into the _properties dictionary. The input properties must adhere to the class schema or a KeyError or TypeError exception will be raised. If adding an object of an XCObject subclass and the schema indicates a strong relationship, the object's parent will be set to this object. If do_copy is True, then lists, dicts, strong-owned XCObjects, and strong-owned XCObjects in lists will be copied instead of having their references added. """ if properties is None: return for property, value in properties.iteritems(): # Make sure the property is in the schema. if not property in self._schema: raise KeyError(property + ' not in ' + self.__class__.__name__) # Make sure the property conforms to the schema. (is_list, property_type, is_strong) = self._schema[property][0:3] if is_list: if value.__class__ != list: raise TypeError( property + ' of ' + self.__class__.__name__ + \ ' must be list, not ' + value.__class__.__name__) for item in value: if not isinstance(item, property_type) and \ not (item.__class__ == unicode and property_type == str): # Accept unicode where str is specified. str is treated as # UTF-8-encoded. raise TypeError( 'item of ' + property + ' of ' + self.__class__.__name__ + \ ' must be ' + property_type.__name__ + ', not ' + \ item.__class__.__name__) elif not isinstance(value, property_type) and \ not (value.__class__ == unicode and property_type == str): # Accept unicode where str is specified. str is treated as # UTF-8-encoded. raise TypeError( property + ' of ' + self.__class__.__name__ + ' must be ' + \ property_type.__name__ + ', not ' + value.__class__.__name__) # Checks passed, perform the assignment. if do_copy: if isinstance(value, XCObject): if is_strong: self._properties[property] = value.Copy() else: self._properties[property] = value elif isinstance(value, str) or isinstance(value, unicode) or \ isinstance(value, int): self._properties[property] = value elif isinstance(value, list): if is_strong: # If is_strong is True, each element is an XCObject, so it's safe # to call Copy. self._properties[property] = [] for item in value: self._properties[property].append(item.Copy()) else: self._properties[property] = value[:] elif isinstance(value, dict): self._properties[property] = value.copy() else: raise TypeError("Don't know how to copy a " + \ value.__class__.__name__ + ' object for ' + \ property + ' in ' + self.__class__.__name__) else: self._properties[property] = value # Set up the child's back-reference to this object. Don't use |value| # any more because it may not be right if do_copy is true. if is_strong: if not is_list: self._properties[property].parent = self else: for item in self._properties[property]: item.parent = self def HasProperty(self, key): return key in self._properties def GetProperty(self, key): return self._properties[key] def SetProperty(self, key, value): self.UpdateProperties({key: value}) def DelProperty(self, key): if key in self._properties: del self._properties[key] def AppendProperty(self, key, value): # TODO(mark): Support ExtendProperty too (and make this call that)? # Schema validation. if not key in self._schema: raise KeyError(key + ' not in ' + self.__class__.__name__) (is_list, property_type, is_strong) = self._schema[key][0:3] if not is_list: raise TypeError(key + ' of ' + self.__class__.__name__ + ' must be list') if not isinstance(value, property_type): raise TypeError('item of ' + key + ' of ' + self.__class__.__name__ + \ ' must be ' + property_type.__name__ + ', not ' + \ value.__class__.__name__) # If the property doesn't exist yet, create a new empty list to receive the # item. if not key in self._properties: self._properties[key] = [] # Set up the ownership link. if is_strong: value.parent = self # Store the item. self._properties[key].append(value) def VerifyHasRequiredProperties(self): """Ensure that all properties identified as required by the schema are set. """ # TODO(mark): A stronger verification mechanism is needed. Some # subclasses need to perform validation beyond what the schema can enforce. for property, attributes in self._schema.iteritems(): (is_list, property_type, is_strong, is_required) = attributes[0:4] if is_required and not property in self._properties: raise KeyError(self.__class__.__name__ + ' requires ' + property) def _SetDefaultsFromSchema(self): """Assign object default values according to the schema. This will not overwrite properties that have already been set.""" defaults = {} for property, attributes in self._schema.iteritems(): (is_list, property_type, is_strong, is_required) = attributes[0:4] if is_required and len(attributes) >= 5 and \ not property in self._properties: default = attributes[4] defaults[property] = default if len(defaults) > 0: # Use do_copy=True so that each new object gets its own copy of strong # objects, lists, and dicts. self.UpdateProperties(defaults, do_copy=True) class XCHierarchicalElement(XCObject): """Abstract base for PBXGroup and PBXFileReference. Not represented in a project file.""" # TODO(mark): Do name and path belong here? Probably so. # If path is set and name is not, name may have a default value. Name will # be set to the basename of path, if the basename of path is different from # the full value of path. If path is already just a leaf name, name will # not be set. _schema = XCObject._schema.copy() _schema.update({ 'comments': [0, str, 0, 0], 'fileEncoding': [0, str, 0, 0], 'includeInIndex': [0, int, 0, 0], 'indentWidth': [0, int, 0, 0], 'lineEnding': [0, int, 0, 0], 'sourceTree': [0, str, 0, 1, '<group>'], 'tabWidth': [0, int, 0, 0], 'usesTabs': [0, int, 0, 0], 'wrapsLines': [0, int, 0, 0], }) def __init__(self, properties=None, id=None, parent=None): # super XCObject.__init__(self, properties, id, parent) if 'path' in self._properties and not 'name' in self._properties: path = self._properties['path'] name = posixpath.basename(path) if name != '' and path != name: self.SetProperty('name', name) if 'path' in self._properties and \ (not 'sourceTree' in self._properties or \ self._properties['sourceTree'] == '<group>'): # If the pathname begins with an Xcode variable like "$(SDKROOT)/", take # the variable out and make the path be relative to that variable by # assigning the variable name as the sourceTree. (source_tree, path) = SourceTreeAndPathFromPath(self._properties['path']) if source_tree != None: self._properties['sourceTree'] = source_tree if path != None: self._properties['path'] = path if source_tree != None and path is None and \ not 'name' in self._properties: # The path was of the form "$(SDKROOT)" with no path following it. # This object is now relative to that variable, so it has no path # attribute of its own. It does, however, keep a name. del self._properties['path'] self._properties['name'] = source_tree def Name(self): if 'name' in self._properties: return self._properties['name'] elif 'path' in self._properties: return self._properties['path'] else: # This happens in the case of the root PBXGroup. return None def Hashables(self): """Custom hashables for XCHierarchicalElements. XCHierarchicalElements are special. Generally, their hashes shouldn't change if the paths don't change. The normal XCObject implementation of Hashables adds a hashable for each object, which means that if the hierarchical structure changes (possibly due to changes caused when TakeOverOnlyChild runs and encounters slight changes in the hierarchy), the hashes will change. For example, if a project file initially contains a/b/f1 and a/b becomes collapsed into a/b, f1 will have a single parent a/b. If someone later adds a/f2 to the project file, a/b can no longer be collapsed, and f1 winds up with parent b and grandparent a. That would be sufficient to change f1's hash. To counteract this problem, hashables for all XCHierarchicalElements except for the main group (which has neither a name nor a path) are taken to be just the set of path components. Because hashables are inherited from parents, this provides assurance that a/b/f1 has the same set of hashables whether its parent is b or a/b. The main group is a special case. As it is permitted to have no name or path, it is permitted to use the standard XCObject hash mechanism. This is not considered a problem because there can be only one main group. """ if self == self.PBXProjectAncestor()._properties['mainGroup']: # super return XCObject.Hashables(self) hashables = [] # Put the name in first, ensuring that if TakeOverOnlyChild collapses # children into a top-level group like "Source", the name always goes # into the list of hashables without interfering with path components. if 'name' in self._properties: # Make it less likely for people to manipulate hashes by following the # pattern of always pushing an object type value onto the list first. hashables.append(self.__class__.__name__ + '.name') hashables.append(self._properties['name']) # NOTE: This still has the problem that if an absolute path is encountered, # including paths with a sourceTree, they'll still inherit their parents' # hashables, even though the paths aren't relative to their parents. This # is not expected to be much of a problem in practice. path = self.PathFromSourceTreeAndPath() if path != None: components = path.split(posixpath.sep) for component in components: hashables.append(self.__class__.__name__ + '.path') hashables.append(component) hashables.extend(self._hashables) return hashables def Compare(self, other): # Allow comparison of these types. PBXGroup has the highest sort rank; # PBXVariantGroup is treated as equal to PBXFileReference. valid_class_types = { PBXFileReference: 'file', PBXGroup: 'group', PBXVariantGroup: 'file', } self_type = valid_class_types[self.__class__] other_type = valid_class_types[other.__class__] if self_type == other_type: # If the two objects are of the same sort rank, compare their names. return cmp(self.Name(), other.Name()) # Otherwise, sort groups before everything else. if self_type == 'group': return -1 return 1 def CompareRootGroup(self, other): # This function should be used only to compare direct children of the # containing PBXProject's mainGroup. These groups should appear in the # listed order. # TODO(mark): "Build" is used by gyp.generator.xcode, perhaps the # generator should have a way of influencing this list rather than having # to hardcode for the generator here. order = ['Source', 'Intermediates', 'Projects', 'Frameworks', 'Products', 'Build'] # If the groups aren't in the listed order, do a name comparison. # Otherwise, groups in the listed order should come before those that # aren't. self_name = self.Name() other_name = other.Name() self_in = isinstance(self, PBXGroup) and self_name in order other_in = isinstance(self, PBXGroup) and other_name in order if not self_in and not other_in: return self.Compare(other) if self_name in order and not other_name in order: return -1 if other_name in order and not self_name in order: return 1 # If both groups are in the listed order, go by the defined order. self_index = order.index(self_name) other_index = order.index(other_name) if self_index < other_index: return -1 if self_index > other_index: return 1 return 0 def PathFromSourceTreeAndPath(self): # Turn the object's sourceTree and path properties into a single flat # string of a form comparable to the path parameter. If there's a # sourceTree property other than "<group>", wrap it in $(...) for the # comparison. components = [] if self._properties['sourceTree'] != '<group>': components.append('$(' + self._properties['sourceTree'] + ')') if 'path' in self._properties: components.append(self._properties['path']) if len(components) > 0: return posixpath.join(*components) return None def FullPath(self): # Returns a full path to self relative to the project file, or relative # to some other source tree. Start with self, and walk up the chain of # parents prepending their paths, if any, until no more parents are # available (project-relative path) or until a path relative to some # source tree is found. xche = self path = None while isinstance(xche, XCHierarchicalElement) and \ (path is None or \ (not path.startswith('/') and not path.startswith('$'))): this_path = xche.PathFromSourceTreeAndPath() if this_path != None and path != None: path = posixpath.join(this_path, path) elif this_path != None: path = this_path xche = xche.parent return path class PBXGroup(XCHierarchicalElement): """ Attributes: _children_by_path: Maps pathnames of children of this PBXGroup to the actual child XCHierarchicalElement objects. _variant_children_by_name_and_path: Maps (name, path) tuples of PBXVariantGroup children to the actual child PBXVariantGroup objects. """ _schema = XCHierarchicalElement._schema.copy() _schema.update({ 'children': [1, XCHierarchicalElement, 1, 1, []], 'name': [0, str, 0, 0], 'path': [0, str, 0, 0], }) def __init__(self, properties=None, id=None, parent=None): # super XCHierarchicalElement.__init__(self, properties, id, parent) self._children_by_path = {} self._variant_children_by_name_and_path = {} for child in self._properties.get('children', []): self._AddChildToDicts(child) def Hashables(self): # super hashables = XCHierarchicalElement.Hashables(self) # It is not sufficient to just rely on name and parent to build a unique # hashable : a node could have two child PBXGroup sharing a common name. # To add entropy the hashable is enhanced with the names of all its # children. for child in self._properties.get('children', []): child_name = child.Name() if child_name != None: hashables.append(child_name) return hashables def HashablesForChild(self): # To avoid a circular reference the hashables used to compute a child id do # not include the child names. return XCHierarchicalElement.Hashables(self) def _AddChildToDicts(self, child): # Sets up this PBXGroup object's dicts to reference the child properly. child_path = child.PathFromSourceTreeAndPath() if child_path: if child_path in self._children_by_path: raise ValueError('Found multiple children with path ' + child_path) self._children_by_path[child_path] = child if isinstance(child, PBXVariantGroup): child_name = child._properties.get('name', None) key = (child_name, child_path) if key in self._variant_children_by_name_and_path: raise ValueError('Found multiple PBXVariantGroup children with ' + \ 'name ' + str(child_name) + ' and path ' + \ str(child_path)) self._variant_children_by_name_and_path[key] = child def AppendChild(self, child): # Callers should use this instead of calling # AppendProperty('children', child) directly because this function # maintains the group's dicts. self.AppendProperty('children', child) self._AddChildToDicts(child) def GetChildByName(self, name): # This is not currently optimized with a dict as GetChildByPath is because # it has few callers. Most callers probably want GetChildByPath. This # function is only useful to get children that have names but no paths, # which is rare. The children of the main group ("Source", "Products", # etc.) is pretty much the only case where this likely to come up. # # TODO(mark): Maybe this should raise an error if more than one child is # present with the same name. if not 'children' in self._properties: return None for child in self._properties['children']: if child.Name() == name: return child return None def GetChildByPath(self, path): if not path: return None if path in self._children_by_path: return self._children_by_path[path] return None def GetChildByRemoteObject(self, remote_object): # This method is a little bit esoteric. Given a remote_object, which # should be a PBXFileReference in another project file, this method will # return this group's PBXReferenceProxy object serving as a local proxy # for the remote PBXFileReference. # # This function might benefit from a dict optimization as GetChildByPath # for some workloads, but profiling shows that it's not currently a # problem. if not 'children' in self._properties: return None for child in self._properties['children']: if not isinstance(child, PBXReferenceProxy): continue container_proxy = child._properties['remoteRef'] if container_proxy._properties['remoteGlobalIDString'] == remote_object: return child return None def AddOrGetFileByPath(self, path, hierarchical): """Returns an existing or new file reference corresponding to path. If hierarchical is True, this method will create or use the necessary hierarchical group structure corresponding to path. Otherwise, it will look in and create an item in the current group only. If an existing matching reference is found, it is returned, otherwise, a new one will be created, added to the correct group, and returned. If path identifies a directory by virtue of carrying a trailing slash, this method returns a PBXFileReference of "folder" type. If path identifies a variant, by virtue of it identifying a file inside a directory with an ".lproj" extension, this method returns a PBXVariantGroup containing the variant named by path, and possibly other variants. For all other paths, a "normal" PBXFileReference will be returned. """ # Adding or getting a directory? Directories end with a trailing slash. is_dir = False if path.endswith('/'): is_dir = True path = posixpath.normpath(path) if is_dir: path = path + '/' # Adding or getting a variant? Variants are files inside directories # with an ".lproj" extension. Xcode uses variants for localization. For # a variant path/to/Language.lproj/MainMenu.nib, put a variant group named # MainMenu.nib inside path/to, and give it a variant named Language. In # this example, grandparent would be set to path/to and parent_root would # be set to Language. variant_name = None parent = posixpath.dirname(path) grandparent = posixpath.dirname(parent) parent_basename = posixpath.basename(parent) (parent_root, parent_ext) = posixpath.splitext(parent_basename) if parent_ext == '.lproj': variant_name = parent_root if grandparent == '': grandparent = None # Putting a directory inside a variant group is not currently supported. assert not is_dir or variant_name is None path_split = path.split(posixpath.sep) if len(path_split) == 1 or \ ((is_dir or variant_name != None) and len(path_split) == 2) or \ not hierarchical: # The PBXFileReference or PBXVariantGroup will be added to or gotten from # this PBXGroup, no recursion necessary. if variant_name is None: # Add or get a PBXFileReference. file_ref = self.GetChildByPath(path) if file_ref != None: assert file_ref.__class__ == PBXFileReference else: file_ref = PBXFileReference({'path': path}) self.AppendChild(file_ref) else: # Add or get a PBXVariantGroup. The variant group name is the same # as the basename (MainMenu.nib in the example above). grandparent # specifies the path to the variant group itself, and path_split[-2:] # is the path of the specific variant relative to its group. variant_group_name = posixpath.basename(path) variant_group_ref = self.AddOrGetVariantGroupByNameAndPath( variant_group_name, grandparent) variant_path = posixpath.sep.join(path_split[-2:]) variant_ref = variant_group_ref.GetChildByPath(variant_path) if variant_ref != None: assert variant_ref.__class__ == PBXFileReference else: variant_ref = PBXFileReference({'name': variant_name, 'path': variant_path}) variant_group_ref.AppendChild(variant_ref) # The caller is interested in the variant group, not the specific # variant file. file_ref = variant_group_ref return file_ref else: # Hierarchical recursion. Add or get a PBXGroup corresponding to the # outermost path component, and then recurse into it, chopping off that # path component. next_dir = path_split[0] group_ref = self.GetChildByPath(next_dir) if group_ref != None: assert group_ref.__class__ == PBXGroup else: group_ref = PBXGroup({'path': next_dir}) self.AppendChild(group_ref) return group_ref.AddOrGetFileByPath(posixpath.sep.join(path_split[1:]), hierarchical) def AddOrGetVariantGroupByNameAndPath(self, name, path): """Returns an existing or new PBXVariantGroup for name and path. If a PBXVariantGroup identified by the name and path arguments is already present as a child of this object, it is returned. Otherwise, a new PBXVariantGroup with the correct properties is created, added as a child, and returned. This method will generally be called by AddOrGetFileByPath, which knows when to create a variant group based on the structure of the pathnames passed to it. """ key = (name, path) if key in self._variant_children_by_name_and_path: variant_group_ref = self._variant_children_by_name_and_path[key] assert variant_group_ref.__class__ == PBXVariantGroup return variant_group_ref variant_group_properties = {'name': name} if path != None: variant_group_properties['path'] = path variant_group_ref = PBXVariantGroup(variant_group_properties) self.AppendChild(variant_group_ref) return variant_group_ref def TakeOverOnlyChild(self, recurse=False): """If this PBXGroup has only one child and it's also a PBXGroup, take it over by making all of its children this object's children. This function will continue to take over only children when those children are groups. If there are three PBXGroups representing a, b, and c, with c inside b and b inside a, and a and b have no other children, this will result in a taking over both b and c, forming a PBXGroup for a/b/c. If recurse is True, this function will recurse into children and ask them to collapse themselves by taking over only children as well. Assuming an example hierarchy with files at a/b/c/d1, a/b/c/d2, and a/b/c/d3/e/f (d1, d2, and f are files, the rest are groups), recursion will result in a group for a/b/c containing a group for d3/e. """ # At this stage, check that child class types are PBXGroup exactly, # instead of using isinstance. The only subclass of PBXGroup, # PBXVariantGroup, should not participate in reparenting in the same way: # reparenting by merging different object types would be wrong. while len(self._properties['children']) == 1 and \ self._properties['children'][0].__class__ == PBXGroup: # Loop to take over the innermost only-child group possible. child = self._properties['children'][0] # Assume the child's properties, including its children. Save a copy # of this object's old properties, because they'll still be needed. # This object retains its existing id and parent attributes. old_properties = self._properties self._properties = child._properties self._children_by_path = child._children_by_path if not 'sourceTree' in self._properties or \ self._properties['sourceTree'] == '<group>': # The child was relative to its parent. Fix up the path. Note that # children with a sourceTree other than "<group>" are not relative to # their parents, so no path fix-up is needed in that case. if 'path' in old_properties: if 'path' in self._properties: # Both the original parent and child have paths set. self._properties['path'] = posixpath.join(old_properties['path'], self._properties['path']) else: # Only the original parent has a path, use it. self._properties['path'] = old_properties['path'] if 'sourceTree' in old_properties: # The original parent had a sourceTree set, use it. self._properties['sourceTree'] = old_properties['sourceTree'] # If the original parent had a name set, keep using it. If the original # parent didn't have a name but the child did, let the child's name # live on. If the name attribute seems unnecessary now, get rid of it. if 'name' in old_properties and old_properties['name'] != None and \ old_properties['name'] != self.Name(): self._properties['name'] = old_properties['name'] if 'name' in self._properties and 'path' in self._properties and \ self._properties['name'] == self._properties['path']: del self._properties['name'] # Notify all children of their new parent. for child in self._properties['children']: child.parent = self # If asked to recurse, recurse. if recurse: for child in self._properties['children']: if child.__class__ == PBXGroup: child.TakeOverOnlyChild(recurse) def SortGroup(self): self._properties['children'] = \ sorted(self._properties['children'], cmp=lambda x,y: x.Compare(y)) # Recurse. for child in self._properties['children']: if isinstance(child, PBXGroup): child.SortGroup() class XCFileLikeElement(XCHierarchicalElement): # Abstract base for objects that can be used as the fileRef property of # PBXBuildFile. def PathHashables(self): # A PBXBuildFile that refers to this object will call this method to # obtain additional hashables specific to this XCFileLikeElement. Don't # just use this object's hashables, they're not specific and unique enough # on their own (without access to the parent hashables.) Instead, provide # hashables that identify this object by path by getting its hashables as # well as the hashables of ancestor XCHierarchicalElement objects. hashables = [] xche = self while xche != None and isinstance(xche, XCHierarchicalElement): xche_hashables = xche.Hashables() for index in xrange(0, len(xche_hashables)): hashables.insert(index, xche_hashables[index]) xche = xche.parent return hashables class XCContainerPortal(XCObject): # Abstract base for objects that can be used as the containerPortal property # of PBXContainerItemProxy. pass class XCRemoteObject(XCObject): # Abstract base for objects that can be used as the remoteGlobalIDString # property of PBXContainerItemProxy. pass class PBXFileReference(XCFileLikeElement, XCContainerPortal, XCRemoteObject): _schema = XCFileLikeElement._schema.copy() _schema.update({ 'explicitFileType': [0, str, 0, 0], 'lastKnownFileType': [0, str, 0, 0], 'name': [0, str, 0, 0], 'path': [0, str, 0, 1], }) # Weird output rules for PBXFileReference. _should_print_single_line = True # super _encode_transforms = XCFileLikeElement._alternate_encode_transforms def __init__(self, properties=None, id=None, parent=None): # super XCFileLikeElement.__init__(self, properties, id, parent) if 'path' in self._properties and self._properties['path'].endswith('/'): self._properties['path'] = self._properties['path'][:-1] is_dir = True else: is_dir = False if 'path' in self._properties and \ not 'lastKnownFileType' in self._properties and \ not 'explicitFileType' in self._properties: # TODO(mark): This is the replacement for a replacement for a quick hack. # It is no longer incredibly sucky, but this list needs to be extended. extension_map = { 'a': 'archive.ar', 'app': 'wrapper.application', 'bdic': 'file', 'bundle': 'wrapper.cfbundle', 'c': 'sourcecode.c.c', 'cc': 'sourcecode.cpp.cpp', 'cpp': 'sourcecode.cpp.cpp', 'css': 'text.css', 'cxx': 'sourcecode.cpp.cpp', 'dart': 'sourcecode', 'dylib': 'compiled.mach-o.dylib', 'framework': 'wrapper.framework', 'gyp': 'sourcecode', 'gypi': 'sourcecode', 'h': 'sourcecode.c.h', 'hxx': 'sourcecode.cpp.h', 'icns': 'image.icns', 'java': 'sourcecode.java', 'js': 'sourcecode.javascript', 'kext': 'wrapper.kext', 'm': 'sourcecode.c.objc', 'mm': 'sourcecode.cpp.objcpp', 'nib': 'wrapper.nib', 'o': 'compiled.mach-o.objfile', 'pdf': 'image.pdf', 'pl': 'text.script.perl', 'plist': 'text.plist.xml', 'pm': 'text.script.perl', 'png': 'image.png', 'py': 'text.script.python', 'r': 'sourcecode.rez', 'rez': 'sourcecode.rez', 's': 'sourcecode.asm', 'storyboard': 'file.storyboard', 'strings': 'text.plist.strings', 'swift': 'sourcecode.swift', 'ttf': 'file', 'xcassets': 'folder.assetcatalog', 'xcconfig': 'text.xcconfig', 'xcdatamodel': 'wrapper.xcdatamodel', 'xcdatamodeld':'wrapper.xcdatamodeld', 'xib': 'file.xib', 'y': 'sourcecode.yacc', } prop_map = { 'dart': 'explicitFileType', 'gyp': 'explicitFileType', 'gypi': 'explicitFileType', } if is_dir: file_type = 'folder' prop_name = 'lastKnownFileType' else: basename = posixpath.basename(self._properties['path']) (root, ext) = posixpath.splitext(basename) # Check the map using a lowercase extension. # TODO(mark): Maybe it should try with the original case first and fall # back to lowercase, in case there are any instances where case # matters. There currently aren't. if ext != '': ext = ext[1:].lower() # TODO(mark): "text" is the default value, but "file" is appropriate # for unrecognized files not containing text. Xcode seems to choose # based on content. file_type = extension_map.get(ext, 'text') prop_name = prop_map.get(ext, 'lastKnownFileType') self._properties[prop_name] = file_type class PBXVariantGroup(PBXGroup, XCFileLikeElement): """PBXVariantGroup is used by Xcode to represent localizations.""" # No additions to the schema relative to PBXGroup. pass # PBXReferenceProxy is also an XCFileLikeElement subclass. It is defined below # because it uses PBXContainerItemProxy, defined below. class XCBuildConfiguration(XCObject): _schema = XCObject._schema.copy() _schema.update({ 'baseConfigurationReference': [0, PBXFileReference, 0, 0], 'buildSettings': [0, dict, 0, 1, {}], 'name': [0, str, 0, 1], }) def HasBuildSetting(self, key): return key in self._properties['buildSettings'] def GetBuildSetting(self, key): return self._properties['buildSettings'][key] def SetBuildSetting(self, key, value): # TODO(mark): If a list, copy? self._properties['buildSettings'][key] = value def AppendBuildSetting(self, key, value): if not key in self._properties['buildSettings']: self._properties['buildSettings'][key] = [] self._properties['buildSettings'][key].append(value) def DelBuildSetting(self, key): if key in self._properties['buildSettings']: del self._properties['buildSettings'][key] def SetBaseConfiguration(self, value): self._properties['baseConfigurationReference'] = value class XCConfigurationList(XCObject): # _configs is the default list of configurations. _configs = [ XCBuildConfiguration({'name': 'Debug'}), XCBuildConfiguration({'name': 'Release'}) ] _schema = XCObject._schema.copy() _schema.update({ 'buildConfigurations': [1, XCBuildConfiguration, 1, 1, _configs], 'defaultConfigurationIsVisible': [0, int, 0, 1, 1], 'defaultConfigurationName': [0, str, 0, 1, 'Release'], }) def Name(self): return 'Build configuration list for ' + \ self.parent.__class__.__name__ + ' "' + self.parent.Name() + '"' def ConfigurationNamed(self, name): """Convenience accessor to obtain an XCBuildConfiguration by name.""" for configuration in self._properties['buildConfigurations']: if configuration._properties['name'] == name: return configuration raise KeyError(name) def DefaultConfiguration(self): """Convenience accessor to obtain the default XCBuildConfiguration.""" return self.ConfigurationNamed(self._properties['defaultConfigurationName']) def HasBuildSetting(self, key): """Determines the state of a build setting in all XCBuildConfiguration child objects. If all child objects have key in their build settings, and the value is the same in all child objects, returns 1. If no child objects have the key in their build settings, returns 0. If some, but not all, child objects have the key in their build settings, or if any children have different values for the key, returns -1. """ has = None value = None for configuration in self._properties['buildConfigurations']: configuration_has = configuration.HasBuildSetting(key) if has is None: has = configuration_has elif has != configuration_has: return -1 if configuration_has: configuration_value = configuration.GetBuildSetting(key) if value is None: value = configuration_value elif value != configuration_value: return -1 if not has: return 0 return 1 def GetBuildSetting(self, key): """Gets the build setting for key. All child XCConfiguration objects must have the same value set for the setting, or a ValueError will be raised. """ # TODO(mark): This is wrong for build settings that are lists. The list # contents should be compared (and a list copy returned?) value = None for configuration in self._properties['buildConfigurations']: configuration_value = configuration.GetBuildSetting(key) if value is None: value = configuration_value else: if value != configuration_value: raise ValueError('Variant values for ' + key) return value def SetBuildSetting(self, key, value): """Sets the build setting for key to value in all child XCBuildConfiguration objects. """ for configuration in self._properties['buildConfigurations']: configuration.SetBuildSetting(key, value) def AppendBuildSetting(self, key, value): """Appends value to the build setting for key, which is treated as a list, in all child XCBuildConfiguration objects. """ for configuration in self._properties['buildConfigurations']: configuration.AppendBuildSetting(key, value) def DelBuildSetting(self, key): """Deletes the build setting key from all child XCBuildConfiguration objects. """ for configuration in self._properties['buildConfigurations']: configuration.DelBuildSetting(key) def SetBaseConfiguration(self, value): """Sets the build configuration in all child XCBuildConfiguration objects. """ for configuration in self._properties['buildConfigurations']: configuration.SetBaseConfiguration(value) class PBXBuildFile(XCObject): _schema = XCObject._schema.copy() _schema.update({ 'fileRef': [0, XCFileLikeElement, 0, 1], 'settings': [0, str, 0, 0], # hack, it's a dict }) # Weird output rules for PBXBuildFile. _should_print_single_line = True _encode_transforms = XCObject._alternate_encode_transforms def Name(self): # Example: "main.cc in Sources" return self._properties['fileRef'].Name() + ' in ' + self.parent.Name() def Hashables(self): # super hashables = XCObject.Hashables(self) # It is not sufficient to just rely on Name() to get the # XCFileLikeElement's name, because that is not a complete pathname. # PathHashables returns hashables unique enough that no two # PBXBuildFiles should wind up with the same set of hashables, unless # someone adds the same file multiple times to the same target. That # would be considered invalid anyway. hashables.extend(self._properties['fileRef'].PathHashables()) return hashables class XCBuildPhase(XCObject): """Abstract base for build phase classes. Not represented in a project file. Attributes: _files_by_path: A dict mapping each path of a child in the files list by path (keys) to the corresponding PBXBuildFile children (values). _files_by_xcfilelikeelement: A dict mapping each XCFileLikeElement (keys) to the corresponding PBXBuildFile children (values). """ # TODO(mark): Some build phase types, like PBXShellScriptBuildPhase, don't # actually have a "files" list. XCBuildPhase should not have "files" but # another abstract subclass of it should provide this, and concrete build # phase types that do have "files" lists should be derived from that new # abstract subclass. XCBuildPhase should only provide buildActionMask and # runOnlyForDeploymentPostprocessing, and not files or the various # file-related methods and attributes. _schema = XCObject._schema.copy() _schema.update({ 'buildActionMask': [0, int, 0, 1, 0x7fffffff], 'files': [1, PBXBuildFile, 1, 1, []], 'runOnlyForDeploymentPostprocessing': [0, int, 0, 1, 0], }) def __init__(self, properties=None, id=None, parent=None): # super XCObject.__init__(self, properties, id, parent) self._files_by_path = {} self._files_by_xcfilelikeelement = {} for pbxbuildfile in self._properties.get('files', []): self._AddBuildFileToDicts(pbxbuildfile) def FileGroup(self, path): # Subclasses must override this by returning a two-element tuple. The # first item in the tuple should be the PBXGroup to which "path" should be # added, either as a child or deeper descendant. The second item should # be a boolean indicating whether files should be added into hierarchical # groups or one single flat group. raise NotImplementedError( self.__class__.__name__ + ' must implement FileGroup') def _AddPathToDict(self, pbxbuildfile, path): """Adds path to the dict tracking paths belonging to this build phase. If the path is already a member of this build phase, raises an exception. """ if path in self._files_by_path: raise ValueError('Found multiple build files with path ' + path) self._files_by_path[path] = pbxbuildfile def _AddBuildFileToDicts(self, pbxbuildfile, path=None): """Maintains the _files_by_path and _files_by_xcfilelikeelement dicts. If path is specified, then it is the path that is being added to the phase, and pbxbuildfile must contain either a PBXFileReference directly referencing that path, or it must contain a PBXVariantGroup that itself contains a PBXFileReference referencing the path. If path is not specified, either the PBXFileReference's path or the paths of all children of the PBXVariantGroup are taken as being added to the phase. If the path is already present in the phase, raises an exception. If the PBXFileReference or PBXVariantGroup referenced by pbxbuildfile are already present in the phase, referenced by a different PBXBuildFile object, raises an exception. This does not raise an exception when a PBXFileReference or PBXVariantGroup reappear and are referenced by the same PBXBuildFile that has already introduced them, because in the case of PBXVariantGroup objects, they may correspond to multiple paths that are not all added simultaneously. When this situation occurs, the path needs to be added to _files_by_path, but nothing needs to change in _files_by_xcfilelikeelement, and the caller should have avoided adding the PBXBuildFile if it is already present in the list of children. """ xcfilelikeelement = pbxbuildfile._properties['fileRef'] paths = [] if path != None: # It's best when the caller provides the path. if isinstance(xcfilelikeelement, PBXVariantGroup): paths.append(path) else: # If the caller didn't provide a path, there can be either multiple # paths (PBXVariantGroup) or one. if isinstance(xcfilelikeelement, PBXVariantGroup): for variant in xcfilelikeelement._properties['children']: paths.append(variant.FullPath()) else: paths.append(xcfilelikeelement.FullPath()) # Add the paths first, because if something's going to raise, the # messages provided by _AddPathToDict are more useful owing to its # having access to a real pathname and not just an object's Name(). for a_path in paths: self._AddPathToDict(pbxbuildfile, a_path) # If another PBXBuildFile references this XCFileLikeElement, there's a # problem. if xcfilelikeelement in self._files_by_xcfilelikeelement and \ self._files_by_xcfilelikeelement[xcfilelikeelement] != pbxbuildfile: raise ValueError('Found multiple build files for ' + \ xcfilelikeelement.Name()) self._files_by_xcfilelikeelement[xcfilelikeelement] = pbxbuildfile def AppendBuildFile(self, pbxbuildfile, path=None): # Callers should use this instead of calling # AppendProperty('files', pbxbuildfile) directly because this function # maintains the object's dicts. Better yet, callers can just call AddFile # with a pathname and not worry about building their own PBXBuildFile # objects. self.AppendProperty('files', pbxbuildfile) self._AddBuildFileToDicts(pbxbuildfile, path) def AddFile(self, path, settings=None): (file_group, hierarchical) = self.FileGroup(path) file_ref = file_group.AddOrGetFileByPath(path, hierarchical) if file_ref in self._files_by_xcfilelikeelement and \ isinstance(file_ref, PBXVariantGroup): # There's already a PBXBuildFile in this phase corresponding to the # PBXVariantGroup. path just provides a new variant that belongs to # the group. Add the path to the dict. pbxbuildfile = self._files_by_xcfilelikeelement[file_ref] self._AddBuildFileToDicts(pbxbuildfile, path) else: # Add a new PBXBuildFile to get file_ref into the phase. if settings is None: pbxbuildfile = PBXBuildFile({'fileRef': file_ref}) else: pbxbuildfile = PBXBuildFile({'fileRef': file_ref, 'settings': settings}) self.AppendBuildFile(pbxbuildfile, path) class PBXHeadersBuildPhase(XCBuildPhase): # No additions to the schema relative to XCBuildPhase. def Name(self): return 'Headers' def FileGroup(self, path): return self.PBXProjectAncestor().RootGroupForPath(path) class PBXResourcesBuildPhase(XCBuildPhase): # No additions to the schema relative to XCBuildPhase. def Name(self): return 'Resources' def FileGroup(self, path): return self.PBXProjectAncestor().RootGroupForPath(path) class PBXSourcesBuildPhase(XCBuildPhase): # No additions to the schema relative to XCBuildPhase. def Name(self): return 'Sources' def FileGroup(self, path): return self.PBXProjectAncestor().RootGroupForPath(path) class PBXFrameworksBuildPhase(XCBuildPhase): # No additions to the schema relative to XCBuildPhase. def Name(self): return 'Frameworks' def FileGroup(self, path): (root, ext) = posixpath.splitext(path) if ext != '': ext = ext[1:].lower() if ext == 'o': # .o files are added to Xcode Frameworks phases, but conceptually aren't # frameworks, they're more like sources or intermediates. Redirect them # to show up in one of those other groups. return self.PBXProjectAncestor().RootGroupForPath(path) else: return (self.PBXProjectAncestor().FrameworksGroup(), False) class PBXShellScriptBuildPhase(XCBuildPhase): _schema = XCBuildPhase._schema.copy() _schema.update({ 'inputPaths': [1, str, 0, 1, []], 'name': [0, str, 0, 0], 'outputPaths': [1, str, 0, 1, []], 'shellPath': [0, str, 0, 1, '/bin/sh'], 'shellScript': [0, str, 0, 1], 'showEnvVarsInLog': [0, int, 0, 0], }) def Name(self): if 'name' in self._properties: return self._properties['name'] return 'ShellScript' class PBXCopyFilesBuildPhase(XCBuildPhase): _schema = XCBuildPhase._schema.copy() _schema.update({ 'dstPath': [0, str, 0, 1], 'dstSubfolderSpec': [0, int, 0, 1], 'name': [0, str, 0, 0], }) # path_tree_re matches "$(DIR)/path" or just "$(DIR)". Match group 1 is # "DIR", match group 3 is "path" or None. path_tree_re = re.compile('^\\$\\((.*)\\)(/(.*)|)$') # path_tree_to_subfolder maps names of Xcode variables to the associated # dstSubfolderSpec property value used in a PBXCopyFilesBuildPhase object. path_tree_to_subfolder = { 'BUILT_FRAMEWORKS_DIR': 10, # Frameworks Directory 'BUILT_PRODUCTS_DIR': 16, # Products Directory # Other types that can be chosen via the Xcode UI. # TODO(mark): Map Xcode variable names to these. # : 1, # Wrapper # : 6, # Executables: 6 # : 7, # Resources # : 15, # Java Resources # : 11, # Shared Frameworks # : 12, # Shared Support # : 13, # PlugIns } def Name(self): if 'name' in self._properties: return self._properties['name'] return 'CopyFiles' def FileGroup(self, path): return self.PBXProjectAncestor().RootGroupForPath(path) def SetDestination(self, path): """Set the dstSubfolderSpec and dstPath properties from path. path may be specified in the same notation used for XCHierarchicalElements, specifically, "$(DIR)/path". """ path_tree_match = self.path_tree_re.search(path) if path_tree_match: # Everything else needs to be relative to an Xcode variable. path_tree = path_tree_match.group(1) relative_path = path_tree_match.group(3) if path_tree in self.path_tree_to_subfolder: subfolder = self.path_tree_to_subfolder[path_tree] if relative_path is None: relative_path = '' else: # The path starts with an unrecognized Xcode variable # name like $(SRCROOT). Xcode will still handle this # as an "absolute path" that starts with the variable. subfolder = 0 relative_path = path elif path.startswith('/'): # Special case. Absolute paths are in dstSubfolderSpec 0. subfolder = 0 relative_path = path[1:] else: raise ValueError('Can\'t use path %s in a %s' % \ (path, self.__class__.__name__)) self._properties['dstPath'] = relative_path self._properties['dstSubfolderSpec'] = subfolder class PBXBuildRule(XCObject): _schema = XCObject._schema.copy() _schema.update({ 'compilerSpec': [0, str, 0, 1], 'filePatterns': [0, str, 0, 0], 'fileType': [0, str, 0, 1], 'isEditable': [0, int, 0, 1, 1], 'outputFiles': [1, str, 0, 1, []], 'script': [0, str, 0, 0], }) def Name(self): # Not very inspired, but it's what Xcode uses. return self.__class__.__name__ def Hashables(self): # super hashables = XCObject.Hashables(self) # Use the hashables of the weak objects that this object refers to. hashables.append(self._properties['fileType']) if 'filePatterns' in self._properties: hashables.append(self._properties['filePatterns']) return hashables class PBXContainerItemProxy(XCObject): # When referencing an item in this project file, containerPortal is the # PBXProject root object of this project file. When referencing an item in # another project file, containerPortal is a PBXFileReference identifying # the other project file. # # When serving as a proxy to an XCTarget (in this project file or another), # proxyType is 1. When serving as a proxy to a PBXFileReference (in another # project file), proxyType is 2. Type 2 is used for references to the # producs of the other project file's targets. # # Xcode is weird about remoteGlobalIDString. Usually, it's printed without # a comment, indicating that it's tracked internally simply as a string, but # sometimes it's printed with a comment (usually when the object is initially # created), indicating that it's tracked as a project file object at least # sometimes. This module always tracks it as an object, but contains a hack # to prevent it from printing the comment in the project file output. See # _XCKVPrint. _schema = XCObject._schema.copy() _schema.update({ 'containerPortal': [0, XCContainerPortal, 0, 1], 'proxyType': [0, int, 0, 1], 'remoteGlobalIDString': [0, XCRemoteObject, 0, 1], 'remoteInfo': [0, str, 0, 1], }) def __repr__(self): props = self._properties name = '%s.gyp:%s' % (props['containerPortal'].Name(), props['remoteInfo']) return '<%s %r at 0x%x>' % (self.__class__.__name__, name, id(self)) def Name(self): # Admittedly not the best name, but it's what Xcode uses. return self.__class__.__name__ def Hashables(self): # super hashables = XCObject.Hashables(self) # Use the hashables of the weak objects that this object refers to. hashables.extend(self._properties['containerPortal'].Hashables()) hashables.extend(self._properties['remoteGlobalIDString'].Hashables()) return hashables class PBXTargetDependency(XCObject): # The "target" property accepts an XCTarget object, and obviously not # NoneType. But XCTarget is defined below, so it can't be put into the # schema yet. The definition of PBXTargetDependency can't be moved below # XCTarget because XCTarget's own schema references PBXTargetDependency. # Python doesn't deal well with this circular relationship, and doesn't have # a real way to do forward declarations. To work around, the type of # the "target" property is reset below, after XCTarget is defined. # # At least one of "name" and "target" is required. _schema = XCObject._schema.copy() _schema.update({ 'name': [0, str, 0, 0], 'target': [0, None.__class__, 0, 0], 'targetProxy': [0, PBXContainerItemProxy, 1, 1], }) def __repr__(self): name = self._properties.get('name') or self._properties['target'].Name() return '<%s %r at 0x%x>' % (self.__class__.__name__, name, id(self)) def Name(self): # Admittedly not the best name, but it's what Xcode uses. return self.__class__.__name__ def Hashables(self): # super hashables = XCObject.Hashables(self) # Use the hashables of the weak objects that this object refers to. hashables.extend(self._properties['targetProxy'].Hashables()) return hashables class PBXReferenceProxy(XCFileLikeElement): _schema = XCFileLikeElement._schema.copy() _schema.update({ 'fileType': [0, str, 0, 1], 'path': [0, str, 0, 1], 'remoteRef': [0, PBXContainerItemProxy, 1, 1], }) class XCTarget(XCRemoteObject): # An XCTarget is really just an XCObject, the XCRemoteObject thing is just # to allow PBXProject to be used in the remoteGlobalIDString property of # PBXContainerItemProxy. # # Setting a "name" property at instantiation may also affect "productName", # which may in turn affect the "PRODUCT_NAME" build setting in children of # "buildConfigurationList". See __init__ below. _schema = XCRemoteObject._schema.copy() _schema.update({ 'buildConfigurationList': [0, XCConfigurationList, 1, 1, XCConfigurationList()], 'buildPhases': [1, XCBuildPhase, 1, 1, []], 'dependencies': [1, PBXTargetDependency, 1, 1, []], 'name': [0, str, 0, 1], 'productName': [0, str, 0, 1], }) def __init__(self, properties=None, id=None, parent=None, force_outdir=None, force_prefix=None, force_extension=None): # super XCRemoteObject.__init__(self, properties, id, parent) # Set up additional defaults not expressed in the schema. If a "name" # property was supplied, set "productName" if it is not present. Also set # the "PRODUCT_NAME" build setting in each configuration, but only if # the setting is not present in any build configuration. if 'name' in self._properties: if not 'productName' in self._properties: self.SetProperty('productName', self._properties['name']) if 'productName' in self._properties: if 'buildConfigurationList' in self._properties: configs = self._properties['buildConfigurationList'] if configs.HasBuildSetting('PRODUCT_NAME') == 0: configs.SetBuildSetting('PRODUCT_NAME', self._properties['productName']) def AddDependency(self, other): pbxproject = self.PBXProjectAncestor() other_pbxproject = other.PBXProjectAncestor() if pbxproject == other_pbxproject: # Add a dependency to another target in the same project file. container = PBXContainerItemProxy({'containerPortal': pbxproject, 'proxyType': 1, 'remoteGlobalIDString': other, 'remoteInfo': other.Name()}) dependency = PBXTargetDependency({'target': other, 'targetProxy': container}) self.AppendProperty('dependencies', dependency) else: # Add a dependency to a target in a different project file. other_project_ref = \ pbxproject.AddOrGetProjectReference(other_pbxproject)[1] container = PBXContainerItemProxy({ 'containerPortal': other_project_ref, 'proxyType': 1, 'remoteGlobalIDString': other, 'remoteInfo': other.Name(), }) dependency = PBXTargetDependency({'name': other.Name(), 'targetProxy': container}) self.AppendProperty('dependencies', dependency) # Proxy all of these through to the build configuration list. def ConfigurationNamed(self, name): return self._properties['buildConfigurationList'].ConfigurationNamed(name) def DefaultConfiguration(self): return self._properties['buildConfigurationList'].DefaultConfiguration() def HasBuildSetting(self, key): return self._properties['buildConfigurationList'].HasBuildSetting(key) def GetBuildSetting(self, key): return self._properties['buildConfigurationList'].GetBuildSetting(key) def SetBuildSetting(self, key, value): return self._properties['buildConfigurationList'].SetBuildSetting(key, \ value) def AppendBuildSetting(self, key, value): return self._properties['buildConfigurationList'].AppendBuildSetting(key, \ value) def DelBuildSetting(self, key): return self._properties['buildConfigurationList'].DelBuildSetting(key) # Redefine the type of the "target" property. See PBXTargetDependency._schema # above. PBXTargetDependency._schema['target'][1] = XCTarget class PBXNativeTarget(XCTarget): # buildPhases is overridden in the schema to be able to set defaults. # # NOTE: Contrary to most objects, it is advisable to set parent when # constructing PBXNativeTarget. A parent of an XCTarget must be a PBXProject # object. A parent reference is required for a PBXNativeTarget during # construction to be able to set up the target defaults for productReference, # because a PBXBuildFile object must be created for the target and it must # be added to the PBXProject's mainGroup hierarchy. _schema = XCTarget._schema.copy() _schema.update({ 'buildPhases': [1, XCBuildPhase, 1, 1, [PBXSourcesBuildPhase(), PBXFrameworksBuildPhase()]], 'buildRules': [1, PBXBuildRule, 1, 1, []], 'productReference': [0, PBXFileReference, 0, 1], 'productType': [0, str, 0, 1], }) # Mapping from Xcode product-types to settings. The settings are: # filetype : used for explicitFileType in the project file # prefix : the prefix for the file name # suffix : the suffix for the file name _product_filetypes = { 'com.apple.product-type.application': ['wrapper.application', '', '.app'], 'com.apple.product-type.application.watchapp': ['wrapper.application', '', '.app'], 'com.apple.product-type.watchkit-extension': ['wrapper.app-extension', '', '.appex'], 'com.apple.product-type.app-extension': ['wrapper.app-extension', '', '.appex'], 'com.apple.product-type.bundle': ['wrapper.cfbundle', '', '.bundle'], 'com.apple.product-type.framework': ['wrapper.framework', '', '.framework'], 'com.apple.product-type.library.dynamic': ['compiled.mach-o.dylib', 'lib', '.dylib'], 'com.apple.product-type.library.static': ['archive.ar', 'lib', '.a'], 'com.apple.product-type.tool': ['compiled.mach-o.executable', '', ''], 'com.apple.product-type.bundle.unit-test': ['wrapper.cfbundle', '', '.xctest'], 'com.googlecode.gyp.xcode.bundle': ['compiled.mach-o.dylib', '', '.so'], 'com.apple.product-type.kernel-extension': ['wrapper.kext', '', '.kext'], } def __init__(self, properties=None, id=None, parent=None, force_outdir=None, force_prefix=None, force_extension=None): # super XCTarget.__init__(self, properties, id, parent) if 'productName' in self._properties and \ 'productType' in self._properties and \ not 'productReference' in self._properties and \ self._properties['productType'] in self._product_filetypes: products_group = None pbxproject = self.PBXProjectAncestor() if pbxproject != None: products_group = pbxproject.ProductsGroup() if products_group != None: (filetype, prefix, suffix) = \ self._product_filetypes[self._properties['productType']] # Xcode does not have a distinct type for loadable modules that are # pure BSD targets (not in a bundle wrapper). GYP allows such modules # to be specified by setting a target type to loadable_module without # having mac_bundle set. These are mapped to the pseudo-product type # com.googlecode.gyp.xcode.bundle. # # By picking up this special type and converting it to a dynamic # library (com.apple.product-type.library.dynamic) with fix-ups, # single-file loadable modules can be produced. # # MACH_O_TYPE is changed to mh_bundle to produce the proper file type # (as opposed to mh_dylib). In order for linking to succeed, # DYLIB_CURRENT_VERSION and DYLIB_COMPATIBILITY_VERSION must be # cleared. They are meaningless for type mh_bundle. # # Finally, the .so extension is forcibly applied over the default # (.dylib), unless another forced extension is already selected. # .dylib is plainly wrong, and .bundle is used by loadable_modules in # bundle wrappers (com.apple.product-type.bundle). .so seems an odd # choice because it's used as the extension on many other systems that # don't distinguish between linkable shared libraries and non-linkable # loadable modules, but there's precedent: Python loadable modules on # Mac OS X use an .so extension. if self._properties['productType'] == 'com.googlecode.gyp.xcode.bundle': self._properties['productType'] = \ 'com.apple.product-type.library.dynamic' self.SetBuildSetting('MACH_O_TYPE', 'mh_bundle') self.SetBuildSetting('DYLIB_CURRENT_VERSION', '') self.SetBuildSetting('DYLIB_COMPATIBILITY_VERSION', '') if force_extension is None: force_extension = suffix[1:] if self._properties['productType'] == \ 'com.apple.product-type-bundle.unit.test': if force_extension is None: force_extension = suffix[1:] if force_extension is not None: # If it's a wrapper (bundle), set WRAPPER_EXTENSION. # Extension override. suffix = '.' + force_extension if filetype.startswith('wrapper.'): self.SetBuildSetting('WRAPPER_EXTENSION', force_extension) else: self.SetBuildSetting('EXECUTABLE_EXTENSION', force_extension) if filetype.startswith('compiled.mach-o.executable'): product_name = self._properties['productName'] product_name += suffix suffix = '' self.SetProperty('productName', product_name) self.SetBuildSetting('PRODUCT_NAME', product_name) # Xcode handles most prefixes based on the target type, however there # are exceptions. If a "BSD Dynamic Library" target is added in the # Xcode UI, Xcode sets EXECUTABLE_PREFIX. This check duplicates that # behavior. if force_prefix is not None: prefix = force_prefix if filetype.startswith('wrapper.'): self.SetBuildSetting('WRAPPER_PREFIX', prefix) else: self.SetBuildSetting('EXECUTABLE_PREFIX', prefix) if force_outdir is not None: self.SetBuildSetting('TARGET_BUILD_DIR', force_outdir) # TODO(tvl): Remove the below hack. # http://code.google.com/p/gyp/issues/detail?id=122 # Some targets include the prefix in the target_name. These targets # really should just add a product_name setting that doesn't include # the prefix. For example: # target_name = 'libevent', product_name = 'event' # This check cleans up for them. product_name = self._properties['productName'] prefix_len = len(prefix) if prefix_len and (product_name[:prefix_len] == prefix): product_name = product_name[prefix_len:] self.SetProperty('productName', product_name) self.SetBuildSetting('PRODUCT_NAME', product_name) ref_props = { 'explicitFileType': filetype, 'includeInIndex': 0, 'path': prefix + product_name + suffix, 'sourceTree': 'BUILT_PRODUCTS_DIR', } file_ref = PBXFileReference(ref_props) products_group.AppendChild(file_ref) self.SetProperty('productReference', file_ref) def GetBuildPhaseByType(self, type): if not 'buildPhases' in self._properties: return None the_phase = None for phase in self._properties['buildPhases']: if isinstance(phase, type): # Some phases may be present in multiples in a well-formed project file, # but phases like PBXSourcesBuildPhase may only be present singly, and # this function is intended as an aid to GetBuildPhaseByType. Loop # over the entire list of phases and assert if more than one of the # desired type is found. assert the_phase is None the_phase = phase return the_phase def HeadersPhase(self): headers_phase = self.GetBuildPhaseByType(PBXHeadersBuildPhase) if headers_phase is None: headers_phase = PBXHeadersBuildPhase() # The headers phase should come before the resources, sources, and # frameworks phases, if any. insert_at = len(self._properties['buildPhases']) for index in xrange(0, len(self._properties['buildPhases'])): phase = self._properties['buildPhases'][index] if isinstance(phase, PBXResourcesBuildPhase) or \ isinstance(phase, PBXSourcesBuildPhase) or \ isinstance(phase, PBXFrameworksBuildPhase): insert_at = index break self._properties['buildPhases'].insert(insert_at, headers_phase) headers_phase.parent = self return headers_phase def ResourcesPhase(self): resources_phase = self.GetBuildPhaseByType(PBXResourcesBuildPhase) if resources_phase is None: resources_phase = PBXResourcesBuildPhase() # The resources phase should come before the sources and frameworks # phases, if any. insert_at = len(self._properties['buildPhases']) for index in xrange(0, len(self._properties['buildPhases'])): phase = self._properties['buildPhases'][index] if isinstance(phase, PBXSourcesBuildPhase) or \ isinstance(phase, PBXFrameworksBuildPhase): insert_at = index break self._properties['buildPhases'].insert(insert_at, resources_phase) resources_phase.parent = self return resources_phase def SourcesPhase(self): sources_phase = self.GetBuildPhaseByType(PBXSourcesBuildPhase) if sources_phase is None: sources_phase = PBXSourcesBuildPhase() self.AppendProperty('buildPhases', sources_phase) return sources_phase def FrameworksPhase(self): frameworks_phase = self.GetBuildPhaseByType(PBXFrameworksBuildPhase) if frameworks_phase is None: frameworks_phase = PBXFrameworksBuildPhase() self.AppendProperty('buildPhases', frameworks_phase) return frameworks_phase def AddDependency(self, other): # super XCTarget.AddDependency(self, other) static_library_type = 'com.apple.product-type.library.static' shared_library_type = 'com.apple.product-type.library.dynamic' framework_type = 'com.apple.product-type.framework' if isinstance(other, PBXNativeTarget) and \ 'productType' in self._properties and \ self._properties['productType'] != static_library_type and \ 'productType' in other._properties and \ (other._properties['productType'] == static_library_type or \ ((other._properties['productType'] == shared_library_type or \ other._properties['productType'] == framework_type) and \ ((not other.HasBuildSetting('MACH_O_TYPE')) or other.GetBuildSetting('MACH_O_TYPE') != 'mh_bundle'))): file_ref = other.GetProperty('productReference') pbxproject = self.PBXProjectAncestor() other_pbxproject = other.PBXProjectAncestor() if pbxproject != other_pbxproject: other_project_product_group = \ pbxproject.AddOrGetProjectReference(other_pbxproject)[0] file_ref = other_project_product_group.GetChildByRemoteObject(file_ref) self.FrameworksPhase().AppendProperty('files', PBXBuildFile({'fileRef': file_ref})) class PBXAggregateTarget(XCTarget): pass class PBXProject(XCContainerPortal): # A PBXProject is really just an XCObject, the XCContainerPortal thing is # just to allow PBXProject to be used in the containerPortal property of # PBXContainerItemProxy. """ Attributes: path: "sample.xcodeproj". TODO(mark) Document me! _other_pbxprojects: A dictionary, keyed by other PBXProject objects. Each value is a reference to the dict in the projectReferences list associated with the keyed PBXProject. """ _schema = XCContainerPortal._schema.copy() _schema.update({ 'attributes': [0, dict, 0, 0], 'buildConfigurationList': [0, XCConfigurationList, 1, 1, XCConfigurationList()], 'compatibilityVersion': [0, str, 0, 1, 'Xcode 3.2'], 'hasScannedForEncodings': [0, int, 0, 1, 1], 'mainGroup': [0, PBXGroup, 1, 1, PBXGroup()], 'projectDirPath': [0, str, 0, 1, ''], 'projectReferences': [1, dict, 0, 0], 'projectRoot': [0, str, 0, 1, ''], 'targets': [1, XCTarget, 1, 1, []], }) def __init__(self, properties=None, id=None, parent=None, path=None): self.path = path self._other_pbxprojects = {} # super return XCContainerPortal.__init__(self, properties, id, parent) def Name(self): name = self.path if name[-10:] == '.xcodeproj': name = name[:-10] return posixpath.basename(name) def Path(self): return self.path def Comment(self): return 'Project object' def Children(self): # super children = XCContainerPortal.Children(self) # Add children that the schema doesn't know about. Maybe there's a more # elegant way around this, but this is the only case where we need to own # objects in a dictionary (that is itself in a list), and three lines for # a one-off isn't that big a deal. if 'projectReferences' in self._properties: for reference in self._properties['projectReferences']: children.append(reference['ProductGroup']) return children def PBXProjectAncestor(self): return self def _GroupByName(self, name): if not 'mainGroup' in self._properties: self.SetProperty('mainGroup', PBXGroup()) main_group = self._properties['mainGroup'] group = main_group.GetChildByName(name) if group is None: group = PBXGroup({'name': name}) main_group.AppendChild(group) return group # SourceGroup and ProductsGroup are created by default in Xcode's own # templates. def SourceGroup(self): return self._GroupByName('Source') def ProductsGroup(self): return self._GroupByName('Products') # IntermediatesGroup is used to collect source-like files that are generated # by rules or script phases and are placed in intermediate directories such # as DerivedSources. def IntermediatesGroup(self): return self._GroupByName('Intermediates') # FrameworksGroup and ProjectsGroup are top-level groups used to collect # frameworks and projects. def FrameworksGroup(self): return self._GroupByName('Frameworks') def ProjectsGroup(self): return self._GroupByName('Projects') def RootGroupForPath(self, path): """Returns a PBXGroup child of this object to which path should be added. This method is intended to choose between SourceGroup and IntermediatesGroup on the basis of whether path is present in a source directory or an intermediates directory. For the purposes of this determination, any path located within a derived file directory such as PROJECT_DERIVED_FILE_DIR is treated as being in an intermediates directory. The returned value is a two-element tuple. The first element is the PBXGroup, and the second element specifies whether that group should be organized hierarchically (True) or as a single flat list (False). """ # TODO(mark): make this a class variable and bind to self on call? # Also, this list is nowhere near exhaustive. # INTERMEDIATE_DIR and SHARED_INTERMEDIATE_DIR are used by # gyp.generator.xcode. There should probably be some way for that module # to push the names in, rather than having to hard-code them here. source_tree_groups = { 'DERIVED_FILE_DIR': (self.IntermediatesGroup, True), 'INTERMEDIATE_DIR': (self.IntermediatesGroup, True), 'PROJECT_DERIVED_FILE_DIR': (self.IntermediatesGroup, True), 'SHARED_INTERMEDIATE_DIR': (self.IntermediatesGroup, True), } (source_tree, path) = SourceTreeAndPathFromPath(path) if source_tree != None and source_tree in source_tree_groups: (group_func, hierarchical) = source_tree_groups[source_tree] group = group_func() return (group, hierarchical) # TODO(mark): make additional choices based on file extension. return (self.SourceGroup(), True) def AddOrGetFileInRootGroup(self, path): """Returns a PBXFileReference corresponding to path in the correct group according to RootGroupForPath's heuristics. If an existing PBXFileReference for path exists, it will be returned. Otherwise, one will be created and returned. """ (group, hierarchical) = self.RootGroupForPath(path) return group.AddOrGetFileByPath(path, hierarchical) def RootGroupsTakeOverOnlyChildren(self, recurse=False): """Calls TakeOverOnlyChild for all groups in the main group.""" for group in self._properties['mainGroup']._properties['children']: if isinstance(group, PBXGroup): group.TakeOverOnlyChild(recurse) def SortGroups(self): # Sort the children of the mainGroup (like "Source" and "Products") # according to their defined order. self._properties['mainGroup']._properties['children'] = \ sorted(self._properties['mainGroup']._properties['children'], cmp=lambda x,y: x.CompareRootGroup(y)) # Sort everything else by putting group before files, and going # alphabetically by name within sections of groups and files. SortGroup # is recursive. for group in self._properties['mainGroup']._properties['children']: if not isinstance(group, PBXGroup): continue if group.Name() == 'Products': # The Products group is a special case. Instead of sorting # alphabetically, sort things in the order of the targets that # produce the products. To do this, just build up a new list of # products based on the targets. products = [] for target in self._properties['targets']: if not isinstance(target, PBXNativeTarget): continue product = target._properties['productReference'] # Make sure that the product is already in the products group. assert product in group._properties['children'] products.append(product) # Make sure that this process doesn't miss anything that was already # in the products group. assert len(products) == len(group._properties['children']) group._properties['children'] = products else: group.SortGroup() def AddOrGetProjectReference(self, other_pbxproject): """Add a reference to another project file (via PBXProject object) to this one. Returns [ProductGroup, ProjectRef]. ProductGroup is a PBXGroup object in this project file that contains a PBXReferenceProxy object for each product of each PBXNativeTarget in the other project file. ProjectRef is a PBXFileReference to the other project file. If this project file already references the other project file, the existing ProductGroup and ProjectRef are returned. The ProductGroup will still be updated if necessary. """ if not 'projectReferences' in self._properties: self._properties['projectReferences'] = [] product_group = None project_ref = None if not other_pbxproject in self._other_pbxprojects: # This project file isn't yet linked to the other one. Establish the # link. product_group = PBXGroup({'name': 'Products'}) # ProductGroup is strong. product_group.parent = self # There's nothing unique about this PBXGroup, and if left alone, it will # wind up with the same set of hashables as all other PBXGroup objects # owned by the projectReferences list. Add the hashables of the # remote PBXProject that it's related to. product_group._hashables.extend(other_pbxproject.Hashables()) # The other project reports its path as relative to the same directory # that this project's path is relative to. The other project's path # is not necessarily already relative to this project. Figure out the # pathname that this project needs to use to refer to the other one. this_path = posixpath.dirname(self.Path()) projectDirPath = self.GetProperty('projectDirPath') if projectDirPath: if posixpath.isabs(projectDirPath[0]): this_path = projectDirPath else: this_path = posixpath.join(this_path, projectDirPath) other_path = gyp.common.RelativePath(other_pbxproject.Path(), this_path) # ProjectRef is weak (it's owned by the mainGroup hierarchy). project_ref = PBXFileReference({ 'lastKnownFileType': 'wrapper.pb-project', 'path': other_path, 'sourceTree': 'SOURCE_ROOT', }) self.ProjectsGroup().AppendChild(project_ref) ref_dict = {'ProductGroup': product_group, 'ProjectRef': project_ref} self._other_pbxprojects[other_pbxproject] = ref_dict self.AppendProperty('projectReferences', ref_dict) # Xcode seems to sort this list case-insensitively self._properties['projectReferences'] = \ sorted(self._properties['projectReferences'], cmp=lambda x,y: cmp(x['ProjectRef'].Name().lower(), y['ProjectRef'].Name().lower())) else: # The link already exists. Pull out the relevnt data. project_ref_dict = self._other_pbxprojects[other_pbxproject] product_group = project_ref_dict['ProductGroup'] project_ref = project_ref_dict['ProjectRef'] self._SetUpProductReferences(other_pbxproject, product_group, project_ref) inherit_unique_symroot = self._AllSymrootsUnique(other_pbxproject, False) targets = other_pbxproject.GetProperty('targets') if all(self._AllSymrootsUnique(t, inherit_unique_symroot) for t in targets): dir_path = project_ref._properties['path'] product_group._hashables.extend(dir_path) return [product_group, project_ref] def _AllSymrootsUnique(self, target, inherit_unique_symroot): # Returns True if all configurations have a unique 'SYMROOT' attribute. # The value of inherit_unique_symroot decides, if a configuration is assumed # to inherit a unique 'SYMROOT' attribute from its parent, if it doesn't # define an explicit value for 'SYMROOT'. symroots = self._DefinedSymroots(target) for s in self._DefinedSymroots(target): if (s is not None and not self._IsUniqueSymrootForTarget(s) or s is None and not inherit_unique_symroot): return False return True if symroots else inherit_unique_symroot def _DefinedSymroots(self, target): # Returns all values for the 'SYMROOT' attribute defined in all # configurations for this target. If any configuration doesn't define the # 'SYMROOT' attribute, None is added to the returned set. If all # configurations don't define the 'SYMROOT' attribute, an empty set is # returned. config_list = target.GetProperty('buildConfigurationList') symroots = set() for config in config_list.GetProperty('buildConfigurations'): setting = config.GetProperty('buildSettings') if 'SYMROOT' in setting: symroots.add(setting['SYMROOT']) else: symroots.add(None) if len(symroots) == 1 and None in symroots: return set() return symroots def _IsUniqueSymrootForTarget(self, symroot): # This method returns True if all configurations in target contain a # 'SYMROOT' attribute that is unique for the given target. A value is # unique, if the Xcode macro '$SRCROOT' appears in it in any form. uniquifier = ['$SRCROOT', '$(SRCROOT)'] if any(x in symroot for x in uniquifier): return True return False def _SetUpProductReferences(self, other_pbxproject, product_group, project_ref): # TODO(mark): This only adds references to products in other_pbxproject # when they don't exist in this pbxproject. Perhaps it should also # remove references from this pbxproject that are no longer present in # other_pbxproject. Perhaps it should update various properties if they # change. for target in other_pbxproject._properties['targets']: if not isinstance(target, PBXNativeTarget): continue other_fileref = target._properties['productReference'] if product_group.GetChildByRemoteObject(other_fileref) is None: # Xcode sets remoteInfo to the name of the target and not the name # of its product, despite this proxy being a reference to the product. container_item = PBXContainerItemProxy({ 'containerPortal': project_ref, 'proxyType': 2, 'remoteGlobalIDString': other_fileref, 'remoteInfo': target.Name() }) # TODO(mark): Does sourceTree get copied straight over from the other # project? Can the other project ever have lastKnownFileType here # instead of explicitFileType? (Use it if so?) Can path ever be # unset? (I don't think so.) Can other_fileref have name set, and # does it impact the PBXReferenceProxy if so? These are the questions # that perhaps will be answered one day. reference_proxy = PBXReferenceProxy({ 'fileType': other_fileref._properties['explicitFileType'], 'path': other_fileref._properties['path'], 'sourceTree': other_fileref._properties['sourceTree'], 'remoteRef': container_item, }) product_group.AppendChild(reference_proxy) def SortRemoteProductReferences(self): # For each remote project file, sort the associated ProductGroup in the # same order that the targets are sorted in the remote project file. This # is the sort order used by Xcode. def CompareProducts(x, y, remote_products): # x and y are PBXReferenceProxy objects. Go through their associated # PBXContainerItem to get the remote PBXFileReference, which will be # present in the remote_products list. x_remote = x._properties['remoteRef']._properties['remoteGlobalIDString'] y_remote = y._properties['remoteRef']._properties['remoteGlobalIDString'] x_index = remote_products.index(x_remote) y_index = remote_products.index(y_remote) # Use the order of each remote PBXFileReference in remote_products to # determine the sort order. return cmp(x_index, y_index) for other_pbxproject, ref_dict in self._other_pbxprojects.iteritems(): # Build up a list of products in the remote project file, ordered the # same as the targets that produce them. remote_products = [] for target in other_pbxproject._properties['targets']: if not isinstance(target, PBXNativeTarget): continue remote_products.append(target._properties['productReference']) # Sort the PBXReferenceProxy children according to the list of remote # products. product_group = ref_dict['ProductGroup'] product_group._properties['children'] = sorted( product_group._properties['children'], cmp=lambda x, y, rp=remote_products: CompareProducts(x, y, rp)) class XCProjectFile(XCObject): _schema = XCObject._schema.copy() _schema.update({ 'archiveVersion': [0, int, 0, 1, 1], 'classes': [0, dict, 0, 1, {}], 'objectVersion': [0, int, 0, 1, 46], 'rootObject': [0, PBXProject, 1, 1], }) def ComputeIDs(self, recursive=True, overwrite=True, hash=None): # Although XCProjectFile is implemented here as an XCObject, it's not a # proper object in the Xcode sense, and it certainly doesn't have its own # ID. Pass through an attempt to update IDs to the real root object. if recursive: self._properties['rootObject'].ComputeIDs(recursive, overwrite, hash) def Print(self, file=sys.stdout): self.VerifyHasRequiredProperties() # Add the special "objects" property, which will be caught and handled # separately during printing. This structure allows a fairly standard # loop do the normal printing. self._properties['objects'] = {} self._XCPrint(file, 0, '// !$*UTF8*$!\n') if self._should_print_single_line: self._XCPrint(file, 0, '{ ') else: self._XCPrint(file, 0, '{\n') for property, value in sorted(self._properties.iteritems(), cmp=lambda x, y: cmp(x, y)): if property == 'objects': self._PrintObjects(file) else: self._XCKVPrint(file, 1, property, value) self._XCPrint(file, 0, '}\n') del self._properties['objects'] def _PrintObjects(self, file): if self._should_print_single_line: self._XCPrint(file, 0, 'objects = {') else: self._XCPrint(file, 1, 'objects = {\n') objects_by_class = {} for object in self.Descendants(): if object == self: continue class_name = object.__class__.__name__ if not class_name in objects_by_class: objects_by_class[class_name] = [] objects_by_class[class_name].append(object) for class_name in sorted(objects_by_class): self._XCPrint(file, 0, '\n') self._XCPrint(file, 0, '/* Begin ' + class_name + ' section */\n') for object in sorted(objects_by_class[class_name], cmp=lambda x, y: cmp(x.id, y.id)): object.Print(file) self._XCPrint(file, 0, '/* End ' + class_name + ' section */\n') if self._should_print_single_line: self._XCPrint(file, 0, '}; ') else: self._XCPrint(file, 1, '};\n')
mit
nikkisquared/servo
tests/wpt/css-tests/css-text-decor-3_dev/xhtml1print/support/generate-text-emphasis-position-property-tests.py
841
3343
#!/usr/bin/env python # - * - coding: UTF-8 - * - """ This script generates tests text-emphasis-position-property-001 ~ 006 which cover all possible values of text-emphasis-position property with all combination of three main writing modes and two orientations. Only test files are generated by this script. It also outputs a list of all tests it generated in the format of Mozilla reftest.list to the stdout. """ from __future__ import unicode_literals import itertools TEST_FILE = 'text-emphasis-position-property-{:03}{}.html' REF_FILE = 'text-emphasis-position-property-{:03}-ref.html' TEST_TEMPLATE = '''<!DOCTYPE html> <meta charset="utf-8"> <title>CSS Test: text-emphasis-position: {value}, {title}</title> <link rel="author" title="Xidorn Quan" href="https://www.upsuper.org"> <link rel="author" title="Mozilla" href="https://www.mozilla.org"> <link rel="help" href="https://drafts.csswg.org/css-text-decor-3/#text-emphasis-position-property"> <meta name="assert" content="'text-emphasis-position: {value}' with 'writing-mode: {wm}' puts emphasis marks {position} the text."> <link rel="match" href="text-emphasis-position-property-{index:03}-ref.html"> <p>Pass if the emphasis marks are {position} the text below:</p> <div style="line-height: 5; text-emphasis: circle; writing-mode: {wm}; text-orientation: {orient}; text-emphasis-position: {value}">試験テスト</div> ''' SUFFIXES = ['', 'a', 'b', 'c', 'd', 'e', 'f', 'g'] WRITING_MODES = ["horizontal-tb", "vertical-rl", "vertical-lr"] POSITION_HORIZONTAL = ["over", "under"] POSITION_VERTICAL = ["right", "left"] REF_MAP_MIXED = { "over": 1, "under": 2, "right": 3, "left": 4 } REF_MAP_SIDEWAYS = { "right": 5, "left": 6 } POSITION_TEXT = { "over": "over", "under": "under", "right": "to the right of", "left": "to the left of" } suffixes = [iter(SUFFIXES) for i in range(6)] reftest_items = [] def write_file(filename, content): with open(filename, 'wb') as f: f.write(content.encode('UTF-8')) def write_test_file(idx, suffix, wm, orient, value, position): filename = TEST_FILE.format(idx, suffix) write_file(filename, TEST_TEMPLATE.format( value=value, wm=wm, orient=orient, index=idx, position=position, title=(wm if orient == "mixed" else "{}, {}".format(wm, orient)))) reftest_items.append("== {} {}".format(filename, REF_FILE.format(idx))) def write_test_files(wm, orient, pos1, pos2): idx = (REF_MAP_MIXED if orient == "mixed" else REF_MAP_SIDEWAYS)[pos1] position = POSITION_TEXT[pos1] suffix = suffixes[idx - 1] write_test_file(idx, next(suffix), wm, orient, pos1 + " " + pos2, position) write_test_file(idx, next(suffix), wm, orient, pos2 + " " + pos1, position) for wm in WRITING_MODES: if wm == "horizontal-tb": effective_pos = POSITION_HORIZONTAL ineffective_pos = POSITION_VERTICAL else: effective_pos = POSITION_VERTICAL ineffective_pos = POSITION_HORIZONTAL for pos1, pos2 in itertools.product(effective_pos, ineffective_pos): write_test_files(wm, "mixed", pos1, pos2) if wm != "horizontal-tb": write_test_files(wm, "sideways", pos1, pos2) print("# START tests from {}".format(__file__)) reftest_items.sort() for item in reftest_items: print(item) print("# END tests from {}".format(__file__))
mpl-2.0
marrybird/flask-jwt
tests/test_jwt.py
3
9177
# -*- coding: utf-8 -*- """ tests.test_jwt ~~~~~~~~~~~~~~ Flask-JWT tests """ import time from datetime import timedelta from itsdangerous import TimedJSONWebSignatureSerializer from flask import Flask, json, jsonify import flask_jwt def post_json(client, url, data): resp = client.post( url, headers={'content-type': 'application/json'}, data=json.dumps(data) ) return resp, json.loads(resp.data) def assert_error_response(r, code, msg, desc): jdata = json.loads(r.data) assert r.status_code == code assert jdata['status_code'] == code assert jdata['error'] == msg assert jdata['description'] == desc def test_initialize(): app = Flask(__name__) app.config['SECRET_KEY'] = 'super-secret' jwt = flask_jwt.JWT(app) assert isinstance(jwt, flask_jwt.JWT) assert len(app.url_map._rules) == 2 def test_adds_auth_endpoint(): app = Flask(__name__) app.config['SECRET_KEY'] = 'super-secret' app.config['JWT_AUTH_URL_RULE'] = '/auth' app.config['JWT_AUTH_ENDPOINT'] = 'jwt_auth' flask_jwt.JWT(app) rules = [str(r) for r in app.url_map._rules] assert '/auth' in rules def test_auth_endpoint_with_valid_request(client, user): resp, jdata = post_json( client, '/auth', {'username': user.username, 'password': user.password} ) assert resp.status_code == 200 assert 'token' in jdata def test_custom_auth_endpoint_with_valid_request(app, client, user): app.config['JWT_AUTH_USERNAME_KEY'] = 'email' app.config['JWT_AUTH_PASSWORD_KEY'] = 'pass' resp, jdata = post_json( client, '/auth', {'email': user.username, 'pass': user.password} ) assert resp.status_code == 200 assert 'token' in jdata def test_auth_endpoint_with_invalid_request(client, user): # Invalid request (no password) resp, jdata = post_json(client, '/auth', {'username': user.username}) assert resp.status_code == 400 assert 'error' in jdata assert jdata['error'] == 'Bad Request' assert 'description' in jdata assert jdata['description'] == 'Missing required credentials' assert 'status_code' in jdata assert jdata['status_code'] == 400 def test_auth_endpoint_with_invalid_credentials(client): resp, jdata = post_json( client, '/auth', {'username': 'bogus', 'password': 'bogus'} ) assert resp.status_code == 400 assert 'error' in jdata assert jdata['error'] == 'Bad Request' assert 'description' in jdata assert jdata['description'] == 'Invalid credentials' assert 'status_code' in jdata assert jdata['status_code'] == 400 def test_jwt_required_decorator_with_valid_token(app, client, user): resp, jdata = post_json( client, '/auth', {'username': user.username, 'password': user.password} ) token = jdata['token'] resp = client.get( '/protected', headers={'authorization': 'JWT ' + token}) assert resp.status_code == 200 assert resp.data == b'success' def test_jwt_required_decorator_with_valid_request_current_user(app, client, user): with client as c: resp, jdata = post_json( client, '/auth', {'username': user.username, 'password': user.password} ) token = jdata['token'] c.get( '/protected', headers={'authorization': 'JWT ' + token}) assert flask_jwt.current_user def test_jwt_required_decorator_with_invalid_request_current_user(app, client): with client as c: c.get( '/protected', headers={'authorization': 'JWT bogus'}) assert not flask_jwt.current_user def test_jwt_required_decorator_with_invalid_authorization_headers(app, client): # Missing authorization header r = client.get('/protected') assert_error_response(r, 401, 'Authorization Required', 'Authorization header was missing') assert r.headers['WWW-Authenticate'] == 'JWT realm="Login Required"' # Not a JWT auth header prefix r = client.get('/protected', headers={'authorization': 'Bogus xxx'}) assert_error_response(r, 400, 'Invalid JWT header', 'Unsupported authorization type') # Missing token r = client.get('/protected', headers={'authorization': 'JWT'}) assert_error_response(r, 400, 'Invalid JWT header', 'Token missing') # Token with spaces r = client.get('/protected', headers={'authorization': 'JWT xxx xxx'}) assert_error_response(r, 400, 'Invalid JWT header', 'Token contains spaces') def test_jwt_required_decorator_with_invalid_jwt_tokens(client, user, app): app.config['JWT_EXPIRATION_DELTA'] = timedelta(milliseconds=200) resp, jdata = post_json( client, '/auth', {'username': user.username, 'password': user.password} ) token = jdata['token'] # Undecipherable r = client.get('/protected', headers={'authorization': 'JWT %sX' % token}) assert_error_response(r, 400, 'Invalid JWT', 'Token is undecipherable') # Expired time.sleep(1.5) r = client.get('/protected', headers={'authorization': 'JWT ' + token}) assert_error_response(r, 401, 'Expired JWT', 'Token is expired') def test_jwt_required_decorator_with_missing_user(client, jwt, user): resp, jdata = post_json( client, '/auth', {'username': user.username, 'password': user.password} ) token = jdata['token'] @jwt.user_handler def load_user(payload): return None r = client.get('/protected', headers={'authorization': 'JWT %s' % token}) assert_error_response(r, 400, 'Invalid JWT', 'User does not exist') def test_custom_error_handler(client, jwt): @jwt.error_handler def error_handler(e): return "custom" r = client.get('/protected') assert r.data == b'custom' def test_custom_response_handler(client, jwt, user): @jwt.response_handler def resp_handler(payload): return jsonify({'mytoken': payload}) resp, jdata = post_json( client, '/auth', {'username': user.username, 'password': user.password} ) assert 'mytoken' in jdata def test_default_encode_handler(client, user, app): resp, jdata = post_json( client, '/auth', {'username': user.username, 'password': user.password} ) serializer = TimedJSONWebSignatureSerializer( secret_key=app.config['JWT_SECRET_KEY'] ) decoded = serializer.loads(jdata['token']) assert decoded['user_id'] == user.id def test_custom_encode_handler(client, jwt, user, app): serializer = TimedJSONWebSignatureSerializer( app.config['JWT_SECRET_KEY'], algorithm_name=app.config['JWT_ALGORITHM'] ) @jwt.encode_handler def encode_data(payload): return serializer.dumps({'foo': 42}).decode('utf-8') resp, jdata = post_json( client, '/auth', {'username': user.username, 'password': user.password} ) decoded = serializer.loads(jdata['token']) assert decoded == {'foo': 42} def test_custom_decode_handler(client, user, jwt): @jwt.decode_handler def decode_data(data): return {'user_id': user.id} with client as c: resp, jdata = post_json( client, '/auth', {'username': user.username, 'password': user.password} ) token = jdata['token'] c.get( '/protected', headers={'authorization': 'JWT ' + token}) assert flask_jwt.current_user == user def test_custom_payload_handler(client, jwt, user): @jwt.user_handler def load_user(payload): if payload['id'] == user.id: return user @jwt.payload_handler def make_payload(u): return { 'id': u.id } with client as c: resp, jdata = post_json( client, '/auth', {'username': user.username, 'password': user.password} ) token = jdata['token'] c.get( '/protected', headers={'authorization': 'JWT ' + token}) assert flask_jwt.current_user == user def test_generate_token(user, jwt, app): with app.test_request_context(): token = flask_jwt.generate_token(user) assert token == jwt.encode_callback(jwt.payload_callback(user)) def test_custom_auth_header(app, client, user): app.config['JWT_AUTH_HEADER_PREFIX'] = 'Bearer' with client as c: resp, jdata = post_json( client, '/auth', {'username': user.username, 'password': user.password} ) token = jdata['token'] # Custom Bearer auth header prefix resp = c.get('/protected', headers={'authorization': 'Bearer ' + token}) assert resp.status_code == 200 assert resp.data == b'success' # Not custom Bearer auth header prefix resp = c.get('/protected', headers={'authorization': 'JWT ' + token}) assert_error_response(resp, 400, 'Invalid JWT header', 'Unsupported authorization type')
mit
nkhuyu/httpbin
setup.py
15
1055
from setuptools import setup, find_packages import codecs import os import re long_description = open( os.path.join(os.path.dirname(__file__), 'README.rst')).read() setup( name="httpbin", version="0.2.1", description="HTTP Request and Response Service", long_description=long_description, # The project URL. url='https://github.com/Runscope/httpbin', # Author details author='Runscope', author_email='httpbin@runscope.com', # Choose your license license='MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', ], packages=find_packages(), include_package_data = True, # include files listed in MANIFEST.in install_requires=['Flask','MarkupSafe','decorator','itsdangerous','six'], )
isc
sfu-cl-lab/NHL_Markov
analysis/extable_penaltysum.py
1
2153
import MySQLdb def transtime(timestr): timestr=str(timestr) timestr=timestr.split(":") return int(timestr[1])*60+int(timestr[2]) hometeamid=0 awayteamid=0 timetick=-1 homeps=0 awayps=0 conn=MySQLdb.connect(host='localhost', user='research', passwd='asdfgh', db='nhl_final') cur = conn.cursor() cur.execute ("SELECT DISTINCT `GameId` FROM `play-by-play`") gameids = cur.fetchall() for gameidr in gameids: homeps=0 awayps=0 for periodnumber in range(1,21): try: cur.execute("SELECT `AwayTeamId`,`HomeTeamId` FROM `play-by-play` WHERE `GameId`=%d AND `PeriodNumber`=%d AND `AwayTeamId` is not NULL AND `HomeTeamId` is not NULL LIMIT 1"%(int(gameidr[0]),periodnumber)) r=cur.fetchone() if r==None: break hometeamid=int(r[1]) awayteamid=int(r[0]) cur.execute("SELECT `EventNumber`,`EventTime`,`EventType`,`ActionSequence` From `play-by-play` WHERE `GameId`=%d AND `PeriodNumber`=%d ORDER BY `EventNumber` ASC"%(int(gameidr[0]),periodnumber)) records=cur.fetchall() for recordr in records: cur.execute("UPDATE `play-by-play` SET `HomePenaltySum`=%d, `AwayPenaltySum`=%d WHERE `GameId`=%d AND `PeriodNumber`=%d AND `EventNumber`=%d"%(homeps,awayps,int(gameidr[0]),periodnumber,int(recordr[0]))) conn.commit() #set number information if recordr[2]=="PENALTY": try: cur.execute("SELECT `TeamPenaltyId`,`PenaltyDuration` FROM `penalty-info` WHERE `GameId`=%d AND `PeriodNumber`=%d AND `EventNumber`=%d LIMIT 1"%(int(gameidr[0]),periodnumber,int(recordr[0]))) pt=cur.fetchone() ptd=int(pt[1]) if ptd!=0: if int(pt[0])==hometeamid: #hometeam get penalty homeps=homeps+1 else: awayps=awayps+1 except Exception,e: print 'error: gameid='+str(gameidr[0])+", periodnumber="+str(periodnumber) print e pass except Exception,e: print 'error: gameid='+str(gameidr[0])+", periodnumber="+str(periodnumber) print e pass #cur.execute("UPDATE `play-by-play` SET `HomePlayerNumber`=6, `AwayPlayerNumber`=6 WHERE `PeriodNumber`>5") #cur.commit() cur.close() conn.close()
gpl-3.0
futurepr0n/Books-solutions
Python-For-Everyone-Horstmann/Chapter9-Objects-and-Classes/P9_23.py
1
2102
# Design and implement a class Country that stores the name of the country, its popula- # tion, and its area. Then write a program that reads in a set of countries and prints # • The country with the largest area. # • The country with the largest population. # • The country with the largest population density (people per square kilometer (or mile)). class Country(): def __init__(self, name, population, area): self._name = name self._population = population self._area = area def get_name(self): return self._name def get_population(self): return self._population def get_area(self): return self._area def get_population_density(self): return int(self._population / self._area) def pretty_info(self): return "Name: {}, Population: {}, Area: {}, Population Density: {}".format(self.get_name(), self.get_population(), self.get_area(), self.get_population_density()) class Continent(): def __init__(self, name): self._name = name self._countries = set() def get_name(self): return self._name def add_country(self, country): self._countries.add(country) def show_largest_area_country(self): largest = self._countries[0] for i in range(1, len(self._countries)): if self._countries[i].get_area() > largest.get_area(): largest = self._countries[i] return largest.pretty_info() def show_largest_population_country(self): largest = self._countries[0] for i in range(1, len(self._countries)): if self._countries[i].get_population() > largest.get_population(): largest = self._countries[i] return largest.pretty_info() def show_largest_population_density_country(self): largest = self._countries[0] for i in range(1, len(self._countries)): if self._countries[i].get_population_density() > largest.get_population_density(): largest = self._countries[i] return largest.pretty_info()
mit
hanicker/odoo
addons/product_visible_discount/__openerp__.py
260
2082
############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Prices Visible Discounts', 'version': '1.0', 'author': 'OpenERP SA', 'category': 'Sales Management', 'website': 'https://www.odoo.com', 'description': """ This module lets you calculate discounts on Sale Order lines and Invoice lines base on the partner's pricelist. =============================================================================================================== To this end, a new check box named 'Visible Discount' is added to the pricelist form. **Example:** For the product PC1 and the partner "Asustek": if listprice=450, and the price calculated using Asustek's pricelist is 225. If the check box is checked, we will have on the sale order line: Unit price=450, Discount=50,00, Net price=225. If the check box is unchecked, we will have on Sale Order and Invoice lines: Unit price=225, Discount=0,00, Net price=225. """, 'depends': ["sale","purchase"], 'demo': [], 'data': ['product_visible_discount_view.xml'], 'auto_install': False, 'installable': True, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
snbuback/django-guardian
guardian/tests/shortcuts_test.py
37
28550
from __future__ import unicode_literals import warnings from django.contrib.contenttypes.models import ContentType from django.db.models.query import QuerySet from django.test import TestCase from guardian.shortcuts import get_perms_for_model from guardian.core import ObjectPermissionChecker from guardian.compat import get_user_model from guardian.compat import get_user_permission_full_codename from guardian.shortcuts import assign from guardian.shortcuts import assign_perm from guardian.shortcuts import remove_perm from guardian.shortcuts import get_perms from guardian.shortcuts import get_users_with_perms from guardian.shortcuts import get_groups_with_perms from guardian.shortcuts import get_objects_for_user from guardian.shortcuts import get_objects_for_group from guardian.exceptions import MixedContentTypeError from guardian.exceptions import NotUserNorGroup from guardian.exceptions import WrongAppError from guardian.tests.core_test import ObjectPermissionTestCase from guardian.models import Group, Permission User = get_user_model() user_app_label = User._meta.app_label user_module_name = User._meta.module_name class ShortcutsTests(ObjectPermissionTestCase): def test_get_perms_for_model(self): self.assertEqual(get_perms_for_model(self.user).count(), 3) self.assertTrue(list(get_perms_for_model(self.user)) == list(get_perms_for_model(User))) self.assertEqual(get_perms_for_model(Permission).count(), 3) model_str = 'contenttypes.ContentType' self.assertEqual( sorted(get_perms_for_model(model_str).values_list()), sorted(get_perms_for_model(ContentType).values_list())) obj = ContentType() self.assertEqual( sorted(get_perms_for_model(model_str).values_list()), sorted(get_perms_for_model(obj).values_list())) class AssignPermTest(ObjectPermissionTestCase): """ Tests permission assigning for user/group and object. """ def test_not_model(self): self.assertRaises(NotUserNorGroup, assign_perm, perm="change_object", user_or_group="Not a Model", obj=self.ctype) def test_global_wrong_perm(self): self.assertRaises(ValueError, assign_perm, perm="change_site", # for global permissions must provide app_label user_or_group=self.user) def test_user_assign_perm(self): assign_perm("change_contenttype", self.user, self.ctype) assign_perm("change_contenttype", self.group, self.ctype) self.assertTrue(self.user.has_perm("change_contenttype", self.ctype)) def test_group_assign_perm(self): assign_perm("change_contenttype", self.group, self.ctype) assign_perm("delete_contenttype", self.group, self.ctype) check = ObjectPermissionChecker(self.group) self.assertTrue(check.has_perm("change_contenttype", self.ctype)) self.assertTrue(check.has_perm("delete_contenttype", self.ctype)) def test_user_assign_perm_global(self): perm = assign_perm("contenttypes.change_contenttype", self.user) self.assertTrue(self.user.has_perm("contenttypes.change_contenttype")) self.assertTrue(isinstance(perm, Permission)) def test_group_assign_perm_global(self): perm = assign_perm("contenttypes.change_contenttype", self.group) self.assertTrue(self.user.has_perm("contenttypes.change_contenttype")) self.assertTrue(isinstance(perm, Permission)) def test_deprecation_warning(self): with warnings.catch_warnings(record=True) as warns: warnings.simplefilter('always') assign("contenttypes.change_contenttype", self.group) self.assertEqual(len(warns), 1) self.assertTrue(isinstance(warns[0].message, DeprecationWarning)) class RemovePermTest(ObjectPermissionTestCase): """ Tests object permissions removal. """ def test_not_model(self): self.assertRaises(NotUserNorGroup, remove_perm, perm="change_object", user_or_group="Not a Model", obj=self.ctype) def test_global_wrong_perm(self): self.assertRaises(ValueError, remove_perm, perm="change_site", # for global permissions must provide app_label user_or_group=self.user) def test_user_remove_perm(self): # assign perm first assign_perm("change_contenttype", self.user, self.ctype) remove_perm("change_contenttype", self.user, self.ctype) self.assertFalse(self.user.has_perm("change_contenttype", self.ctype)) def test_group_remove_perm(self): # assign perm first assign_perm("change_contenttype", self.group, self.ctype) remove_perm("change_contenttype", self.group, self.ctype) check = ObjectPermissionChecker(self.group) self.assertFalse(check.has_perm("change_contenttype", self.ctype)) def test_user_remove_perm_global(self): # assign perm first perm = "contenttypes.change_contenttype" assign_perm(perm, self.user) remove_perm(perm, self.user) self.assertFalse(self.user.has_perm(perm)) def test_group_remove_perm_global(self): # assign perm first perm = "contenttypes.change_contenttype" assign_perm(perm, self.group) remove_perm(perm, self.group) app_label, codename = perm.split('.') perm_obj = Permission.objects.get(codename=codename, content_type__app_label=app_label) self.assertFalse(perm_obj in self.group.permissions.all()) class GetPermsTest(ObjectPermissionTestCase): """ Tests get_perms function (already done at core tests but left here as a placeholder). """ def test_not_model(self): self.assertRaises(NotUserNorGroup, get_perms, user_or_group=None, obj=self.ctype) def test_user(self): perms_to_assign = ("change_contenttype",) for perm in perms_to_assign: assign_perm("change_contenttype", self.user, self.ctype) perms = get_perms(self.user, self.ctype) for perm in perms_to_assign: self.assertTrue(perm in perms) class GetUsersWithPermsTest(TestCase): """ Tests get_users_with_perms function. """ def setUp(self): self.obj1 = ContentType.objects.create(name='ct1', model='foo', app_label='guardian-tests') self.obj2 = ContentType.objects.create(name='ct2', model='bar', app_label='guardian-tests') self.user1 = User.objects.create(username='user1') self.user2 = User.objects.create(username='user2') self.user3 = User.objects.create(username='user3') self.group1 = Group.objects.create(name='group1') self.group2 = Group.objects.create(name='group2') self.group3 = Group.objects.create(name='group3') def test_empty(self): result = get_users_with_perms(self.obj1) self.assertTrue(isinstance(result, QuerySet)) self.assertEqual(list(result), []) result = get_users_with_perms(self.obj1, attach_perms=True) self.assertTrue(isinstance(result, dict)) self.assertFalse(bool(result)) def test_simple(self): assign_perm("change_contenttype", self.user1, self.obj1) assign_perm("delete_contenttype", self.user2, self.obj1) assign_perm("delete_contenttype", self.user3, self.obj2) result = get_users_with_perms(self.obj1) result_vals = result.values_list('username', flat=True) self.assertEqual( set(result_vals), set([user.username for user in (self.user1, self.user2)]), ) def test_users_groups_perms(self): self.user1.groups.add(self.group1) self.user2.groups.add(self.group2) self.user3.groups.add(self.group3) assign_perm("change_contenttype", self.group1, self.obj1) assign_perm("change_contenttype", self.group2, self.obj1) assign_perm("delete_contenttype", self.group3, self.obj2) result = get_users_with_perms(self.obj1).values_list('id', flat=True) self.assertEqual( set(result), set([u.id for u in (self.user1, self.user2)]) ) def test_users_groups_after_removal(self): self.test_users_groups_perms() remove_perm("change_contenttype", self.group1, self.obj1) result = get_users_with_perms(self.obj1).values_list('id', flat=True) self.assertEqual( set(result), set([self.user2.id]), ) def test_attach_perms(self): self.user1.groups.add(self.group1) self.user2.groups.add(self.group2) self.user3.groups.add(self.group3) assign_perm("change_contenttype", self.group1, self.obj1) assign_perm("change_contenttype", self.group2, self.obj1) assign_perm("delete_contenttype", self.group3, self.obj2) assign_perm("delete_contenttype", self.user2, self.obj1) assign_perm("change_contenttype", self.user3, self.obj2) # Check contenttype1 result = get_users_with_perms(self.obj1, attach_perms=True) expected = { self.user1: ["change_contenttype"], self.user2: ["change_contenttype", "delete_contenttype"], } self.assertEqual(result.keys(), expected.keys()) for key, perms in result.items(): self.assertEqual(set(perms), set(expected[key])) # Check contenttype2 result = get_users_with_perms(self.obj2, attach_perms=True) expected = { self.user3: ["change_contenttype", "delete_contenttype"], } self.assertEqual(result.keys(), expected.keys()) for key, perms in result.items(): self.assertEqual(set(perms), set(expected[key])) def test_attach_groups_only_has_perms(self): self.user1.groups.add(self.group1) assign_perm("change_contenttype", self.group1, self.obj1) result = get_users_with_perms(self.obj1, attach_perms=True) expected = {self.user1: ["change_contenttype"]} self.assertEqual(result, expected) def test_mixed(self): self.user1.groups.add(self.group1) assign_perm("change_contenttype", self.group1, self.obj1) assign_perm("change_contenttype", self.user2, self.obj1) assign_perm("delete_contenttype", self.user2, self.obj1) assign_perm("delete_contenttype", self.user2, self.obj2) assign_perm("change_contenttype", self.user3, self.obj2) assign_perm("change_%s" % user_module_name, self.user3, self.user1) result = get_users_with_perms(self.obj1) self.assertEqual( set(result), set([self.user1, self.user2]), ) def test_with_superusers(self): admin = User.objects.create(username='admin', is_superuser=True) assign_perm("change_contenttype", self.user1, self.obj1) result = get_users_with_perms(self.obj1, with_superusers=True) self.assertEqual( set(result), set([self.user1, admin]), ) def test_without_group_users(self): self.user1.groups.add(self.group1) self.user2.groups.add(self.group2) assign_perm("change_contenttype", self.group1, self.obj1) assign_perm("change_contenttype", self.user2, self.obj1) assign_perm("change_contenttype", self.group2, self.obj1) result = get_users_with_perms(self.obj1, with_group_users=False) expected = set([self.user2]) self.assertEqual(set(result), expected) def test_without_group_users_but_perms_attached(self): self.user1.groups.add(self.group1) self.user2.groups.add(self.group2) assign_perm("change_contenttype", self.group1, self.obj1) assign_perm("change_contenttype", self.user2, self.obj1) assign_perm("change_contenttype", self.group2, self.obj1) result = get_users_with_perms(self.obj1, with_group_users=False, attach_perms=True) expected = {self.user2: ["change_contenttype"]} self.assertEqual(result, expected) def test_without_group_users_no_result(self): self.user1.groups.add(self.group1) assign_perm("change_contenttype", self.group1, self.obj1) result = get_users_with_perms(self.obj1, attach_perms=True, with_group_users=False) expected = {} self.assertEqual(result, expected) def test_without_group_users_no_result_but_with_superusers(self): admin = User.objects.create(username='admin', is_superuser=True) self.user1.groups.add(self.group1) assign_perm("change_contenttype", self.group1, self.obj1) result = get_users_with_perms(self.obj1, with_group_users=False, with_superusers=True) expected = [admin] self.assertEqual(set(result), set(expected)) class GetGroupsWithPerms(TestCase): """ Tests get_groups_with_perms function. """ def setUp(self): self.obj1 = ContentType.objects.create(name='ct1', model='foo', app_label='guardian-tests') self.obj2 = ContentType.objects.create(name='ct2', model='bar', app_label='guardian-tests') self.user1 = User.objects.create(username='user1') self.user2 = User.objects.create(username='user2') self.user3 = User.objects.create(username='user3') self.group1 = Group.objects.create(name='group1') self.group2 = Group.objects.create(name='group2') self.group3 = Group.objects.create(name='group3') def test_empty(self): result = get_groups_with_perms(self.obj1) self.assertTrue(isinstance(result, QuerySet)) self.assertFalse(bool(result)) result = get_groups_with_perms(self.obj1, attach_perms=True) self.assertTrue(isinstance(result, dict)) self.assertFalse(bool(result)) def test_simple(self): assign_perm("change_contenttype", self.group1, self.obj1) result = get_groups_with_perms(self.obj1) self.assertEqual(len(result), 1) self.assertEqual(result[0], self.group1) def test_simple_after_removal(self): self.test_simple() remove_perm("change_contenttype", self.group1, self.obj1) result = get_groups_with_perms(self.obj1) self.assertEqual(len(result), 0) def test_simple_attach_perms(self): assign_perm("change_contenttype", self.group1, self.obj1) result = get_groups_with_perms(self.obj1, attach_perms=True) expected = {self.group1: ["change_contenttype"]} self.assertEqual(result, expected) def test_simple_attach_perms_after_removal(self): self.test_simple_attach_perms() remove_perm("change_contenttype", self.group1, self.obj1) result = get_groups_with_perms(self.obj1, attach_perms=True) self.assertEqual(len(result), 0) def test_mixed(self): assign_perm("change_contenttype", self.group1, self.obj1) assign_perm("change_contenttype", self.group1, self.obj2) assign_perm("change_%s" % user_module_name, self.group1, self.user3) assign_perm("change_contenttype", self.group2, self.obj2) assign_perm("change_contenttype", self.group2, self.obj1) assign_perm("delete_contenttype", self.group2, self.obj1) assign_perm("change_%s" % user_module_name, self.group3, self.user1) result = get_groups_with_perms(self.obj1) self.assertEqual(set(result), set([self.group1, self.group2])) def test_mixed_attach_perms(self): assign_perm("change_contenttype", self.group1, self.obj1) assign_perm("change_contenttype", self.group1, self.obj2) assign_perm("change_group", self.group1, self.group3) assign_perm("change_contenttype", self.group2, self.obj2) assign_perm("change_contenttype", self.group2, self.obj1) assign_perm("delete_contenttype", self.group2, self.obj1) assign_perm("change_group", self.group3, self.group1) result = get_groups_with_perms(self.obj1, attach_perms=True) expected = { self.group1: ["change_contenttype"], self.group2: ["change_contenttype", "delete_contenttype"], } self.assertEqual(result.keys(), expected.keys()) for key, perms in result.items(): self.assertEqual(set(perms), set(expected[key])) class GetObjectsForUser(TestCase): def setUp(self): self.user = User.objects.create(username='joe') self.group = Group.objects.create(name='group') self.ctype = ContentType.objects.create(name='foo', model='bar', app_label='fake-for-guardian-tests') def test_superuser(self): self.user.is_superuser = True ctypes = ContentType.objects.all() objects = get_objects_for_user(self.user, ['contenttypes.change_contenttype'], ctypes) self.assertEqual(set(ctypes), set(objects)) def test_mixed_perms(self): codenames = [ get_user_permission_full_codename('change'), 'auth.change_permission', ] self.assertRaises(MixedContentTypeError, get_objects_for_user, self.user, codenames) def test_perms_with_mixed_apps(self): codenames = [ get_user_permission_full_codename('change'), 'contenttypes.change_contenttype', ] self.assertRaises(MixedContentTypeError, get_objects_for_user, self.user, codenames) def test_mixed_perms_and_klass(self): self.assertRaises(MixedContentTypeError, get_objects_for_user, self.user, ['auth.change_group'], User) def test_no_app_label_nor_klass(self): self.assertRaises(WrongAppError, get_objects_for_user, self.user, ['change_group']) def test_empty_perms_sequence(self): self.assertEqual( set(get_objects_for_user(self.user, [], Group.objects.all())), set() ) def test_perms_single(self): perm = 'auth.change_group' assign_perm(perm, self.user, self.group) self.assertEqual( set(get_objects_for_user(self.user, perm)), set(get_objects_for_user(self.user, [perm]))) def test_klass_as_model(self): assign_perm('contenttypes.change_contenttype', self.user, self.ctype) objects = get_objects_for_user(self.user, ['contenttypes.change_contenttype'], ContentType) self.assertEqual([obj.name for obj in objects], [self.ctype.name]) def test_klass_as_manager(self): assign_perm('auth.change_group', self.user, self.group) objects = get_objects_for_user(self.user, ['auth.change_group'], Group.objects) self.assertEqual([obj.name for obj in objects], [self.group.name]) def test_klass_as_queryset(self): assign_perm('auth.change_group', self.user, self.group) objects = get_objects_for_user(self.user, ['auth.change_group'], Group.objects.all()) self.assertEqual([obj.name for obj in objects], [self.group.name]) def test_ensure_returns_queryset(self): objects = get_objects_for_user(self.user, ['auth.change_group']) self.assertTrue(isinstance(objects, QuerySet)) def test_simple(self): group_names = ['group1', 'group2', 'group3'] groups = [Group.objects.create(name=name) for name in group_names] for group in groups: assign_perm('change_group', self.user, group) objects = get_objects_for_user(self.user, ['auth.change_group']) self.assertEqual(len(objects), len(groups)) self.assertTrue(isinstance(objects, QuerySet)) self.assertEqual( set(objects), set(groups)) def test_multiple_perms_to_check(self): group_names = ['group1', 'group2', 'group3'] groups = [Group.objects.create(name=name) for name in group_names] for group in groups: assign_perm('auth.change_group', self.user, group) assign_perm('auth.delete_group', self.user, groups[1]) objects = get_objects_for_user(self.user, ['auth.change_group', 'auth.delete_group']) self.assertEqual(len(objects), 1) self.assertTrue(isinstance(objects, QuerySet)) self.assertEqual( set(objects.values_list('name', flat=True)), set([groups[1].name])) def test_any_of_multiple_perms_to_check(self): group_names = ['group1', 'group2', 'group3'] groups = [Group.objects.create(name=name) for name in group_names] assign_perm('auth.change_group', self.user, groups[0]) assign_perm('auth.delete_group', self.user, groups[2]) objects = get_objects_for_user(self.user, ['auth.change_group', 'auth.delete_group'], any_perm=True) self.assertEqual(len(objects), 2) self.assertTrue(isinstance(objects, QuerySet)) self.assertEqual( set(objects.values_list('name', flat=True)), set([groups[0].name, groups[2].name])) def test_groups_perms(self): group1 = Group.objects.create(name='group1') group2 = Group.objects.create(name='group2') group3 = Group.objects.create(name='group3') groups = [group1, group2, group3] for group in groups: self.user.groups.add(group) # Objects to operate on ctypes = dict(((ct.id, ct) for ct in ContentType.objects.all())) assign_perm('change_contenttype', self.user, ctypes[1]) assign_perm('change_contenttype', self.user, ctypes[2]) assign_perm('delete_contenttype', self.user, ctypes[2]) assign_perm('delete_contenttype', self.user, ctypes[3]) assign_perm('change_contenttype', groups[0], ctypes[4]) assign_perm('change_contenttype', groups[1], ctypes[4]) assign_perm('change_contenttype', groups[2], ctypes[5]) assign_perm('delete_contenttype', groups[0], ctypes[1]) objects = get_objects_for_user(self.user, ['contenttypes.change_contenttype']) self.assertEqual( set(objects.values_list('id', flat=True)), set([1, 2, 4, 5])) objects = get_objects_for_user(self.user, ['contenttypes.change_contenttype', 'contenttypes.delete_contenttype']) self.assertEqual( set(objects.values_list('id', flat=True)), set([1, 2])) objects = get_objects_for_user(self.user, ['contenttypes.change_contenttype']) self.assertEqual( set(objects.values_list('id', flat=True)), set([1, 2, 4, 5])) class GetObjectsForGroup(TestCase): """ Tests get_objects_for_group function. """ def setUp(self): self.obj1 = ContentType.objects.create(name='ct1', model='foo', app_label='guardian-tests') self.obj2 = ContentType.objects.create(name='ct2', model='bar', app_label='guardian-tests') self.obj3 = ContentType.objects.create(name='ct3', model='baz', app_label='guardian-tests') self.user1 = User.objects.create(username='user1') self.user2 = User.objects.create(username='user2') self.user3 = User.objects.create(username='user3') self.group1 = Group.objects.create(name='group1') self.group2 = Group.objects.create(name='group2') self.group3 = Group.objects.create(name='group3') def test_mixed_perms(self): codenames = [ get_user_permission_full_codename('change'), 'auth.change_permission', ] self.assertRaises(MixedContentTypeError, get_objects_for_group, self.group1, codenames) def test_perms_with_mixed_apps(self): codenames = [ get_user_permission_full_codename('change'), 'contenttypes.contenttypes.change_contenttype', ] self.assertRaises(MixedContentTypeError, get_objects_for_group, self.group1, codenames) def test_mixed_perms_and_klass(self): self.assertRaises(MixedContentTypeError, get_objects_for_group, self.group1, ['auth.change_group'], User) def test_no_app_label_nor_klass(self): self.assertRaises(WrongAppError, get_objects_for_group, self.group1, ['change_contenttype']) def test_empty_perms_sequence(self): self.assertEqual( set(get_objects_for_group(self.group1, [], ContentType)), set() ) def test_perms_single(self): perm = 'contenttypes.change_contenttype' assign_perm(perm, self.group1, self.obj1) self.assertEqual( set(get_objects_for_group(self.group1, perm)), set(get_objects_for_group(self.group1, [perm])) ) def test_klass_as_model(self): assign_perm('contenttypes.change_contenttype', self.group1, self.obj1) objects = get_objects_for_group(self.group1, ['contenttypes.change_contenttype'], ContentType) self.assertEqual([obj.name for obj in objects], [self.obj1.name]) def test_klass_as_manager(self): assign_perm('contenttypes.change_contenttype', self.group1, self.obj1) objects = get_objects_for_group(self.group1, ['change_contenttype'], ContentType.objects) self.assertEqual(list(objects), [self.obj1]) def test_klass_as_queryset(self): assign_perm('contenttypes.change_contenttype', self.group1, self.obj1) objects = get_objects_for_group(self.group1, ['change_contenttype'], ContentType.objects.all()) self.assertEqual(list(objects), [self.obj1]) def test_ensure_returns_queryset(self): objects = get_objects_for_group(self.group1, ['contenttypes.change_contenttype']) self.assertTrue(isinstance(objects, QuerySet)) def test_simple(self): assign_perm('change_contenttype', self.group1, self.obj1) assign_perm('change_contenttype', self.group1, self.obj2) objects = get_objects_for_group(self.group1, 'contenttypes.change_contenttype') self.assertEqual(len(objects), 2) self.assertTrue(isinstance(objects, QuerySet)) self.assertEqual( set(objects), set([self.obj1, self.obj2])) def test_simple_after_removal(self): self.test_simple() remove_perm('change_contenttype', self.group1, self.obj1) objects = get_objects_for_group(self.group1, 'contenttypes.change_contenttype') self.assertEqual(len(objects), 1) self.assertEqual(objects[0], self.obj2) def test_multiple_perms_to_check(self): assign_perm('change_contenttype', self.group1, self.obj1) assign_perm('delete_contenttype', self.group1, self.obj1) assign_perm('change_contenttype', self.group1, self.obj2) objects = get_objects_for_group(self.group1, [ 'contenttypes.change_contenttype', 'contenttypes.delete_contenttype']) self.assertEqual(len(objects), 1) self.assertTrue(isinstance(objects, QuerySet)) self.assertEqual(objects[0], self.obj1) def test_any_of_multiple_perms_to_check(self): assign_perm('change_contenttype', self.group1, self.obj1) assign_perm('delete_contenttype', self.group1, self.obj1) assign_perm('add_contenttype', self.group1, self.obj2) assign_perm('delete_contenttype', self.group1, self.obj3) objects = get_objects_for_group(self.group1, ['contenttypes.change_contenttype', 'contenttypes.delete_contenttype'], any_perm=True) self.assertTrue(isinstance(objects, QuerySet)) self.assertEqual([obj for obj in objects.order_by('name')], [self.obj1, self.obj3]) def test_results_for_different_groups_are_correct(self): assign_perm('change_contenttype', self.group1, self.obj1) assign_perm('delete_contenttype', self.group2, self.obj2) self.assertEqual(set(get_objects_for_group(self.group1, 'contenttypes.change_contenttype')), set([self.obj1])) self.assertEqual(set(get_objects_for_group(self.group2, 'contenttypes.change_contenttype')), set()) self.assertEqual(set(get_objects_for_group(self.group2, 'contenttypes.delete_contenttype')), set([self.obj2]))
bsd-2-clause
mlperf/training_results_v0.7
Google/benchmarks/bert/implementations/bert-cloud-TF2.0-tpu-v3-32/tf2_common/utils/testing/benchmark_wrappers.py
2
2850
# Lint as: python3 """Utils to annotate and trace benchmarks.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import REDACTED from absl import flags from absl import logging from absl.testing import flagsaver FLAGS = flags.FLAGS flags.DEFINE_multi_string( 'benchmark_method_flags', None, 'Optional list of runtime flags of the form key=value. Specify ' 'multiple times to specify different flags. These will override the FLAGS ' 'object directly after hardcoded settings in individual benchmark methods ' 'before they call _run_and_report benchmark. Example if we set ' '--benchmark_method_flags=train_steps=10 and a benchmark method hardcodes ' 'FLAGS.train_steps=10000 and later calls _run_and_report_benchmark, ' 'it\'ll only run for 10 steps. This is useful for ' 'debugging/profiling workflows.') def enable_runtime_flags(decorated_func): """Sets attributes from --benchmark_method_flags for method execution. @enable_runtime_flags decorator temporarily adds flags passed in via --benchmark_method_flags and runs the decorated function in that context. A user can set --benchmark_method_flags=train_steps=5 to run the benchmark method in the snippet below with FLAGS.train_steps=5 for debugging (without modifying the benchmark code). class ModelBenchmark(): @benchmark_wrappers.enable_runtime_flags def _run_and_report_benchmark(self): # run benchmark ... # report benchmark results ... def benchmark_method(self): FLAGS.train_steps = 1000 ... self._run_and_report_benchmark() Args: decorated_func: The method that runs the benchmark after previous setup execution that set some flags. Returns: new_func: The same method which executes in a temporary context where flag overrides from --benchmark_method_flags are active. """ def runner(*args, **kwargs): """Creates a temporary context to activate --benchmark_method_flags.""" if FLAGS.benchmark_method_flags: saved_flag_values = flagsaver.save_flag_values() for key_value in FLAGS.benchmark_method_flags: key, value = key_value.split('=', 1) try: numeric_float = float(value) numeric_int = int(numeric_float) if abs(numeric_int) == abs(numeric_float): flag_value = numeric_int else: flag_value = numeric_float except ValueError: flag_value = value logging.info('Setting --%s=%s', key, flag_value) setattr(FLAGS, key, flag_value) else: saved_flag_values = None try: result = decorated_func(*args, **kwargs) return result finally: if saved_flag_values: flagsaver.restore_flag_values(saved_flag_values) return runner
apache-2.0
zixiliuyue/pika
pika/compat.py
2
3696
import os import sys as _sys PY2 = _sys.version_info < (3,) PY3 = not PY2 if not PY2: # these were moved around for Python 3 from urllib.parse import (quote as url_quote, unquote as url_unquote, urlencode) # Python 3 does not have basestring anymore; we include # *only* the str here as this is used for textual data. basestring = (str,) # for assertions that the data is either encoded or non-encoded text str_or_bytes = (str, bytes) # xrange is gone, replace it with range xrange = range # the unicode type is str unicode_type = str def dictkeys(dct): """ Returns a list of keys of dictionary dict.keys returns a view that works like .keys in Python 2 *except* any modifications in the dictionary will be visible (and will cause errors if the view is being iterated over while it is modified). """ return list(dct.keys()) def dictvalues(dct): """ Returns a list of values of a dictionary dict.values returns a view that works like .values in Python 2 *except* any modifications in the dictionary will be visible (and will cause errors if the view is being iterated over while it is modified). """ return list(dct.values()) def dict_iteritems(dct): """ Returns an iterator of items (key/value pairs) of a dictionary dict.items returns a view that works like .items in Python 2 *except* any modifications in the dictionary will be visible (and will cause errors if the view is being iterated over while it is modified). """ return dct.items() def dict_itervalues(dct): """ :param dict dct: :returns: an iterator of the values of a dictionary """ return dct.values() def byte(*args): """ This is the same as Python 2 `chr(n)` for bytes in Python 3 Returns a single byte `bytes` for the given int argument (we optimize it a bit here by passing the positional argument tuple directly to the bytes constructor. """ return bytes(args) class long(int): """ A marker class that signifies that the integer value should be serialized as `l` instead of `I` """ def __repr__(self): return str(self) + 'L' def canonical_str(value): """ Return the canonical str value for the string. In both Python 3 and Python 2 this is str. """ return str(value) def is_integer(value): return isinstance(value, int) else: from urllib import quote as url_quote, unquote as url_unquote, urlencode basestring = basestring str_or_bytes = basestring xrange = xrange unicode_type = unicode dictkeys = dict.keys dictvalues = dict.values dict_iteritems = dict.iteritems dict_itervalues = dict.itervalues byte = chr long = long def canonical_str(value): """ Returns the canonical string value of the given string. In Python 2 this is the value unchanged if it is an str, otherwise it is the unicode value encoded as UTF-8. """ try: return str(value) except UnicodeEncodeError: return str(value.encode('utf-8')) def is_integer(value): return isinstance(value, (int, long)) def as_bytes(value): if not isinstance(value, bytes): return value.encode('UTF-8') return value HAVE_SIGNAL = os.name == 'posix' EINTR_IS_EXPOSED = _sys.version_info[:2] <= (3,4)
bsd-3-clause
yfcydyf/pyspider
pyspider/libs/pprint.py
81
12676
# Author: Fred L. Drake, Jr. # fdrake@... # # This is a simple little module I wrote to make life easier. I didn't # see anything quite like it in the library, though I may have overlooked # something. I wrote this when I was trying to read some heavily nested # tuples with fairly non-descriptive content. This is modeled very much # after Lisp/Scheme - style pretty-printing of lists. If you find it # useful, thank small children who sleep at night. """Support to pretty-print lists, tuples, & dictionaries recursively. Very simple, but useful, especially in debugging data structures. Classes ------- PrettyPrinter() Handle pretty-printing operations onto a stream using a configured set of formatting parameters. Functions --------- pformat() Format a Python object into a pretty-printed representation. pprint() Pretty-print a Python object to a stream [default is sys.stdout]. saferepr() Generate a 'standard' repr()-like value, but protect against recursive data structures. """ from __future__ import print_function import six import sys as _sys from io import BytesIO, StringIO __all__ = ["pprint", "pformat", "isreadable", "isrecursive", "saferepr", "PrettyPrinter"] # cache these for faster access: _commajoin = ", ".join _id = id _len = len _type = type def pprint(object, stream=None, indent=1, width=80, depth=None): """Pretty-print a Python object to a stream [default is sys.stdout].""" printer = PrettyPrinter( stream=stream, indent=indent, width=width, depth=depth) printer.pprint(object) def pformat(object, indent=1, width=80, depth=None): """Format a Python object into a pretty-printed representation.""" return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object) def saferepr(object): """Version of repr() which can handle recursive data structures.""" return _safe_repr(object, {}, None, 0)[0] def isreadable(object): """Determine if saferepr(object) is readable by eval().""" return _safe_repr(object, {}, None, 0)[1] def isrecursive(object): """Determine if object requires a recursive representation.""" return _safe_repr(object, {}, None, 0)[2] def _sorted(iterable): return sorted(iterable) class PrettyPrinter: def __init__(self, indent=1, width=80, depth=None, stream=None): """Handle pretty printing operations onto a stream using a set of configured parameters. indent Number of spaces to indent for each level of nesting. width Attempted maximum number of columns in the output. depth The maximum depth to print out nested structures. stream The desired output stream. If omitted (or false), the standard output stream available at construction will be used. """ indent = int(indent) width = int(width) assert indent >= 0, "indent must be >= 0" assert depth is None or depth > 0, "depth must be > 0" assert width, "width must be != 0" self._depth = depth self._indent_per_level = indent self._width = width if stream is not None: self._stream = stream else: self._stream = _sys.stdout def pprint(self, object): self._format(object, self._stream, 0, 0, {}, 0) self._stream.write("\n") def pformat(self, object): sio = BytesIO() self._format(object, sio, 0, 0, {}, 0) return sio.getvalue() def isrecursive(self, object): return self.format(object, {}, 0, 0)[2] def isreadable(self, object): s, readable, recursive = self.format(object, {}, 0, 0) return readable and not recursive def _format(self, object, stream, indent, allowance, context, level): level = level + 1 objid = _id(object) if objid in context: stream.write(_recursion(object)) self._recursive = True self._readable = False return rep = self._repr(object, context, level - 1) typ = _type(object) sepLines = _len(rep) > (self._width - 1 - indent - allowance) write = stream.write if self._depth and level > self._depth: write(rep) return r = getattr(typ, "__repr__", None) if issubclass(typ, dict) and r is dict.__repr__: write('{') if self._indent_per_level > 1: write((self._indent_per_level - 1) * ' ') length = _len(object) if length: context[objid] = 1 indent = indent + self._indent_per_level items = _sorted(object.items()) key, ent = items[0] rep = self._repr(key, context, level) write(rep) write(': ') self._format(ent, stream, indent + _len(rep) + 2, allowance + 1, context, level) if length > 1: for key, ent in items[1:]: rep = self._repr(key, context, level) if sepLines: write(',\n%s%s: ' % (' ' * indent, rep)) else: write(', %s: ' % rep) self._format(ent, stream, indent + _len(rep) + 2, allowance + 1, context, level) indent = indent - self._indent_per_level del context[objid] write('}') return if ( (issubclass(typ, list) and r is list.__repr__) or (issubclass(typ, tuple) and r is tuple.__repr__) or (issubclass(typ, set) and r is set.__repr__) or (issubclass(typ, frozenset) and r is frozenset.__repr__) ): length = _len(object) if issubclass(typ, list): write('[') endchar = ']' elif issubclass(typ, set): if not length: write('set()') return write('set([') endchar = '])' object = _sorted(object) indent += 4 elif issubclass(typ, frozenset): if not length: write('frozenset()') return write('frozenset([') endchar = '])' object = _sorted(object) indent += 10 else: write('(') endchar = ')' if self._indent_per_level > 1 and sepLines: write((self._indent_per_level - 1) * ' ') if length: context[objid] = 1 indent = indent + self._indent_per_level self._format(object[0], stream, indent, allowance + 1, context, level) if length > 1: for ent in object[1:]: if sepLines: write(',\n' + ' ' * indent) else: write(', ') self._format(ent, stream, indent, allowance + 1, context, level) indent = indent - self._indent_per_level del context[objid] if issubclass(typ, tuple) and length == 1: write(',') write(endchar) return write(rep) def _repr(self, object, context, level): repr, readable, recursive = self.format(object, context.copy(), self._depth, level) if not readable: self._readable = False if recursive: self._recursive = True return repr def format(self, object, context, maxlevels, level): """Format object for a specific context, returning a string and flags indicating whether the representation is 'readable' and whether the object represents a recursive construct. """ return _safe_repr(object, context, maxlevels, level) # Return triple (repr_string, isreadable, isrecursive). def _safe_repr(object, context, maxlevels, level): typ = _type(object) if typ is str: string = object string = string.replace('\n', '\\n').replace('\r', '\\r').replace('\t', '\\t') if 'locale' not in _sys.modules: return repr(object), True, False if "'" in object and '"' not in object: closure = '"' quotes = {'"': '\\"'} string = string.replace('"', '\\"') else: closure = "'" quotes = {"'": "\\'"} string = string.replace("'", "\\'") try: string.decode('utf8').encode('gbk', 'replace') return ("%s%s%s" % (closure, string, closure)), True, False except: pass qget = quotes.get sio = StringIO() write = sio.write for char in object: if char.isalpha(): write(char) else: write(qget(char, repr(char)[1:-1])) return ("%s%s%s" % (closure, sio.getvalue(), closure)), True, False if typ is six.text_type: string = object.encode("utf8", 'replace') string = string.replace('\n', '\\n').replace('\r', '\\r').replace('\t', '\\t') if "'" in object and '"' not in object: closure = '"' quotes = {'"': '\\"'} string = string.replace('"', '\\"') else: closure = "'" quotes = {"'": "\\'"} string = string.replace("'", "\\'") return ("u%s%s%s" % (closure, string, closure)), True, False r = getattr(typ, "__repr__", None) if issubclass(typ, dict) and r is dict.__repr__: if not object: return "{}", True, False objid = _id(object) if maxlevels and level >= maxlevels: return "{...}", False, objid in context if objid in context: return _recursion(object), False, True context[objid] = 1 readable = True recursive = False components = [] append = components.append level += 1 saferepr = _safe_repr for k, v in _sorted(object.items()): krepr, kreadable, krecur = saferepr(k, context, maxlevels, level) vrepr, vreadable, vrecur = saferepr(v, context, maxlevels, level) append("%s: %s" % (krepr, vrepr)) readable = readable and kreadable and vreadable if krecur or vrecur: recursive = True del context[objid] return "{%s}" % _commajoin(components), readable, recursive if (issubclass(typ, list) and r is list.__repr__) or \ (issubclass(typ, tuple) and r is tuple.__repr__): if issubclass(typ, list): if not object: return "[]", True, False format = "[%s]" elif _len(object) == 1: format = "(%s,)" else: if not object: return "()", True, False format = "(%s)" objid = _id(object) if maxlevels and level >= maxlevels: return format % "...", False, objid in context if objid in context: return _recursion(object), False, True context[objid] = 1 readable = True recursive = False components = [] append = components.append level += 1 for o in object: orepr, oreadable, orecur = _safe_repr(o, context, maxlevels, level) append(orepr) if not oreadable: readable = False if orecur: recursive = True del context[objid] return format % _commajoin(components), readable, recursive rep = repr(object) return rep, (rep and not rep.startswith('<')), False def _recursion(object): return ("<Recursion on %s with id=%s>" % (_type(object).__name__, _id(object))) def _perfcheck(object=None): import time if object is None: object = [("string", (1, 2), [3, 4], {5: 6, 7: 8})] * 100000 p = PrettyPrinter() t1 = time.time() _safe_repr(object, {}, None, 0) t2 = time.time() p.pformat(object) t3 = time.time() print("_safe_repr:", t2 - t1) print("pformat:", t3 - t2) if __name__ == "__main__": _perfcheck()
apache-2.0
kiran/bart-sign
venv/lib/python2.7/site-packages/pip/__init__.py
6
10273
#!/usr/bin/env python from __future__ import absolute_import import logging import os import optparse import warnings import sys import re from pip.exceptions import InstallationError, CommandError, PipError from pip.utils import get_installed_distributions, get_prog from pip.utils import deprecation, dist_is_editable from pip.vcs import git, mercurial, subversion, bazaar # noqa from pip.baseparser import ConfigOptionParser, UpdatingDefaultsHelpFormatter from pip.commands import get_summaries, get_similar_commands from pip.commands import commands_dict from pip._vendor.requests.packages.urllib3.exceptions import ( InsecureRequestWarning, ) # assignment for flake8 to be happy # This fixes a peculiarity when importing via __import__ - as we are # initialising the pip module, "from pip import cmdoptions" is recursive # and appears not to work properly in that situation. import pip.cmdoptions cmdoptions = pip.cmdoptions # The version as used in the setup.py and the docs conf.py __version__ = "8.1.0" logger = logging.getLogger(__name__) # Hide the InsecureRequestWArning from urllib3 warnings.filterwarnings("ignore", category=InsecureRequestWarning) def autocomplete(): """Command and option completion for the main option parser (and options) and its subcommands (and options). Enable by sourcing one of the completion shell scripts (bash or zsh). """ # Don't complete if user hasn't sourced bash_completion file. if 'PIP_AUTO_COMPLETE' not in os.environ: return cwords = os.environ['COMP_WORDS'].split()[1:] cword = int(os.environ['COMP_CWORD']) try: current = cwords[cword - 1] except IndexError: current = '' subcommands = [cmd for cmd, summary in get_summaries()] options = [] # subcommand try: subcommand_name = [w for w in cwords if w in subcommands][0] except IndexError: subcommand_name = None parser = create_main_parser() # subcommand options if subcommand_name: # special case: 'help' subcommand has no options if subcommand_name == 'help': sys.exit(1) # special case: list locally installed dists for uninstall command if subcommand_name == 'uninstall' and not current.startswith('-'): installed = [] lc = current.lower() for dist in get_installed_distributions(local_only=True): if dist.key.startswith(lc) and dist.key not in cwords[1:]: installed.append(dist.key) # if there are no dists installed, fall back to option completion if installed: for dist in installed: print(dist) sys.exit(1) subcommand = commands_dict[subcommand_name]() options += [(opt.get_opt_string(), opt.nargs) for opt in subcommand.parser.option_list_all if opt.help != optparse.SUPPRESS_HELP] # filter out previously specified options from available options prev_opts = [x.split('=')[0] for x in cwords[1:cword - 1]] options = [(x, v) for (x, v) in options if x not in prev_opts] # filter options by current input options = [(k, v) for k, v in options if k.startswith(current)] for option in options: opt_label = option[0] # append '=' to options which require args if option[1]: opt_label += '=' print(opt_label) else: # show main parser options only when necessary if current.startswith('-') or current.startswith('--'): opts = [i.option_list for i in parser.option_groups] opts.append(parser.option_list) opts = (o for it in opts for o in it) subcommands += [i.get_opt_string() for i in opts if i.help != optparse.SUPPRESS_HELP] print(' '.join([x for x in subcommands if x.startswith(current)])) sys.exit(1) def create_main_parser(): parser_kw = { 'usage': '\n%prog <command> [options]', 'add_help_option': False, 'formatter': UpdatingDefaultsHelpFormatter(), 'name': 'global', 'prog': get_prog(), } parser = ConfigOptionParser(**parser_kw) parser.disable_interspersed_args() pip_pkg_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) parser.version = 'pip %s from %s (python %s)' % ( __version__, pip_pkg_dir, sys.version[:3]) # add the general options gen_opts = cmdoptions.make_option_group(cmdoptions.general_group, parser) parser.add_option_group(gen_opts) parser.main = True # so the help formatter knows # create command listing for description command_summaries = get_summaries() description = [''] + ['%-27s %s' % (i, j) for i, j in command_summaries] parser.description = '\n'.join(description) return parser def parseopts(args): parser = create_main_parser() # Note: parser calls disable_interspersed_args(), so the result of this # call is to split the initial args into the general options before the # subcommand and everything else. # For example: # args: ['--timeout=5', 'install', '--user', 'INITools'] # general_options: ['--timeout==5'] # args_else: ['install', '--user', 'INITools'] general_options, args_else = parser.parse_args(args) # --version if general_options.version: sys.stdout.write(parser.version) sys.stdout.write(os.linesep) sys.exit() # pip || pip help -> print_help() if not args_else or (args_else[0] == 'help' and len(args_else) == 1): parser.print_help() sys.exit() # the subcommand name cmd_name = args_else[0] if cmd_name not in commands_dict: guess = get_similar_commands(cmd_name) msg = ['unknown command "%s"' % cmd_name] if guess: msg.append('maybe you meant "%s"' % guess) raise CommandError(' - '.join(msg)) # all the args without the subcommand cmd_args = args[:] cmd_args.remove(cmd_name) return cmd_name, cmd_args def check_isolated(args): isolated = False if "--isolated" in args: isolated = True return isolated def main(args=None): if args is None: args = sys.argv[1:] # Configure our deprecation warnings to be sent through loggers deprecation.install_warning_logger() autocomplete() try: cmd_name, cmd_args = parseopts(args) except PipError as exc: sys.stderr.write("ERROR: %s" % exc) sys.stderr.write(os.linesep) sys.exit(1) command = commands_dict[cmd_name](isolated=check_isolated(cmd_args)) return command.main(cmd_args) # ########################################################### # # Writing freeze files class FrozenRequirement(object): def __init__(self, name, req, editable, comments=()): self.name = name self.req = req self.editable = editable self.comments = comments _rev_re = re.compile(r'-r(\d+)$') _date_re = re.compile(r'-(20\d\d\d\d\d\d)$') @classmethod def from_dist(cls, dist, dependency_links): location = os.path.normcase(os.path.abspath(dist.location)) comments = [] from pip.vcs import vcs, get_src_requirement if dist_is_editable(dist) and vcs.get_backend_name(location): editable = True try: req = get_src_requirement(dist, location) except InstallationError as exc: logger.warning( "Error when trying to get requirement for VCS system %s, " "falling back to uneditable format", exc ) req = None if req is None: logger.warning( 'Could not determine repository location of %s', location ) comments.append( '## !! Could not determine repository location' ) req = dist.as_requirement() editable = False else: editable = False req = dist.as_requirement() specs = req.specs assert len(specs) == 1 and specs[0][0] in ["==", "==="], \ 'Expected 1 spec with == or ===; specs = %r; dist = %r' % \ (specs, dist) version = specs[0][1] ver_match = cls._rev_re.search(version) date_match = cls._date_re.search(version) if ver_match or date_match: svn_backend = vcs.get_backend('svn') if svn_backend: svn_location = svn_backend().get_location( dist, dependency_links, ) if not svn_location: logger.warning( 'Warning: cannot find svn location for %s', req) comments.append( '## FIXME: could not find svn URL in dependency_links ' 'for this package:' ) else: comments.append( '# Installing as editable to satisfy requirement %s:' % req ) if ver_match: rev = ver_match.group(1) else: rev = '{%s}' % date_match.group(1) editable = True req = '%s@%s#egg=%s' % ( svn_location, rev, cls.egg_name(dist) ) return cls(dist.project_name, req, editable, comments) @staticmethod def egg_name(dist): name = dist.egg_name() match = re.search(r'-py\d\.\d$', name) if match: name = name[:match.start()] return name def __str__(self): req = self.req if self.editable: req = '-e %s' % req return '\n'.join(list(self.comments) + [str(req)]) + '\n' if __name__ == '__main__': sys.exit(main())
mit
manojgudi/sandhi
modules/gr36/gr-wxgui/src/python/scopesink_gl.py
17
7879
# # Copyright 2008,2010 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later version. # # GNU Radio 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 GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ################################################## # Imports ################################################## import scope_window import common from gnuradio import gr from pubsub import pubsub from constants import * import math class ac_couple_block(gr.hier_block2): """ AC couple the incoming stream by subtracting out the low pass signal. Mute the low pass filter to disable ac coupling. """ def __init__(self, controller, ac_couple_key, sample_rate_key): gr.hier_block2.__init__( self, "ac_couple", gr.io_signature(1, 1, gr.sizeof_float), gr.io_signature(1, 1, gr.sizeof_float), ) #blocks lpf = gr.single_pole_iir_filter_ff(0.0) sub = gr.sub_ff() mute = gr.mute_ff() #connect self.connect(self, sub, self) self.connect(self, lpf, mute, (sub, 1)) #subscribe controller.subscribe(ac_couple_key, lambda x: mute.set_mute(not x)) controller.subscribe(sample_rate_key, lambda x: lpf.set_taps(0.05)) #initialize controller[ac_couple_key] = controller[ac_couple_key] controller[sample_rate_key] = controller[sample_rate_key] ################################################## # Scope sink block (wrapper for old wxgui) ################################################## class _scope_sink_base(gr.hier_block2, common.wxgui_hb): """ A scope block with a gui window. """ def __init__( self, parent, title='', sample_rate=1, size=scope_window.DEFAULT_WIN_SIZE, v_scale=0, t_scale=0, v_offset=0, xy_mode=False, ac_couple=False, num_inputs=1, trig_mode=scope_window.DEFAULT_TRIG_MODE, y_axis_label='Counts', frame_rate=scope_window.DEFAULT_FRAME_RATE, use_persistence=False, persist_alpha=None, **kwargs #do not end with a comma ): #ensure analog alpha if persist_alpha is None: actual_frame_rate=float(frame_rate) analog_cutoff_freq=0.5 # Hertz #calculate alpha from wanted cutoff freq persist_alpha = 1.0 - math.exp(-2.0*math.pi*analog_cutoff_freq/actual_frame_rate) if not t_scale: t_scale = 10.0/sample_rate #init gr.hier_block2.__init__( self, "scope_sink", gr.io_signature(num_inputs, num_inputs, self._item_size), gr.io_signature(0, 0, 0), ) #scope msgq = gr.msg_queue(2) scope = gr.oscope_sink_f(sample_rate, msgq) #controller self.controller = pubsub() self.controller.subscribe(SAMPLE_RATE_KEY, scope.set_sample_rate) self.controller.publish(SAMPLE_RATE_KEY, scope.sample_rate) self.controller.subscribe(DECIMATION_KEY, scope.set_decimation_count) self.controller.publish(DECIMATION_KEY, scope.get_decimation_count) self.controller.subscribe(TRIGGER_LEVEL_KEY, scope.set_trigger_level) self.controller.publish(TRIGGER_LEVEL_KEY, scope.get_trigger_level) self.controller.subscribe(TRIGGER_MODE_KEY, scope.set_trigger_mode) self.controller.publish(TRIGGER_MODE_KEY, scope.get_trigger_mode) self.controller.subscribe(TRIGGER_SLOPE_KEY, scope.set_trigger_slope) self.controller.publish(TRIGGER_SLOPE_KEY, scope.get_trigger_slope) self.controller.subscribe(TRIGGER_CHANNEL_KEY, scope.set_trigger_channel) self.controller.publish(TRIGGER_CHANNEL_KEY, scope.get_trigger_channel) actual_num_inputs = self._real and num_inputs or num_inputs*2 #init ac couple for i in range(actual_num_inputs): self.controller[common.index_key(AC_COUPLE_KEY, i)] = ac_couple #start input watcher common.input_watcher(msgq, self.controller, MSG_KEY) #create window self.win = scope_window.scope_window( parent=parent, controller=self.controller, size=size, title=title, frame_rate=frame_rate, num_inputs=actual_num_inputs, sample_rate_key=SAMPLE_RATE_KEY, t_scale=t_scale, v_scale=v_scale, v_offset=v_offset, xy_mode=xy_mode, trig_mode=trig_mode, y_axis_label=y_axis_label, ac_couple_key=AC_COUPLE_KEY, trigger_level_key=TRIGGER_LEVEL_KEY, trigger_mode_key=TRIGGER_MODE_KEY, trigger_slope_key=TRIGGER_SLOPE_KEY, trigger_channel_key=TRIGGER_CHANNEL_KEY, decimation_key=DECIMATION_KEY, msg_key=MSG_KEY, use_persistence=use_persistence, persist_alpha=persist_alpha, ) common.register_access_methods(self, self.win) #connect if self._real: for i in range(num_inputs): self.wxgui_connect( (self, i), ac_couple_block(self.controller, common.index_key(AC_COUPLE_KEY, i), SAMPLE_RATE_KEY), (scope, i), ) else: for i in range(num_inputs): c2f = gr.complex_to_float() self.wxgui_connect((self, i), c2f) for j in range(2): self.connect( (c2f, j), ac_couple_block(self.controller, common.index_key(AC_COUPLE_KEY, 2*i+j), SAMPLE_RATE_KEY), (scope, 2*i+j), ) class scope_sink_f(_scope_sink_base): _item_size = gr.sizeof_float _real = True class scope_sink_c(_scope_sink_base): _item_size = gr.sizeof_gr_complex _real = False # ---------------------------------------------------------------- # Stand-alone test application # ---------------------------------------------------------------- import wx from gnuradio.wxgui import stdgui2 class test_top_block (stdgui2.std_top_block): def __init__(self, frame, panel, vbox, argv): stdgui2.std_top_block.__init__ (self, frame, panel, vbox, argv) default_input_rate = 1e6 if len(argv) > 1: input_rate = int(argv[1]) else: input_rate = default_input_rate if len(argv) > 2: v_scale = float(argv[2]) # start up at this v_scale value else: v_scale = None # start up in autorange mode, default if len(argv) > 3: t_scale = float(argv[3]) # start up at this t_scale value else: t_scale = .00003*default_input_rate/input_rate # old behavior print "input rate %s v_scale %s t_scale %s" % (input_rate,v_scale,t_scale) # Generate a complex sinusoid ampl=1.0e3 self.src0 = gr.sig_source_c (input_rate, gr.GR_SIN_WAVE, 25.1e3*input_rate/default_input_rate, ampl) self.noise =gr.sig_source_c (input_rate, gr.GR_SIN_WAVE, 11.1*25.1e3*input_rate/default_input_rate, ampl/10) #self.noise =gr.noise_source_c(gr.GR_GAUSSIAN, ampl/10) self.combine=gr.add_cc() # We add this throttle block so that this demo doesn't suck down # all the CPU available. You normally wouldn't use it... self.thr = gr.throttle(gr.sizeof_gr_complex, input_rate) scope = scope_sink_c (panel,"Secret Data",sample_rate=input_rate, v_scale=v_scale, t_scale=t_scale) vbox.Add (scope.win, 1, wx.EXPAND) # Ultimately this will be # self.connect("src0 throttle scope") self.connect(self.src0,(self.combine,0)) self.connect(self.noise,(self.combine,1)) self.connect(self.combine, self.thr, scope) def main (): app = stdgui2.stdapp (test_top_block, "O'Scope Test App") app.MainLoop () if __name__ == '__main__': main ()
gpl-3.0
sinhrks/cesiumpy
cesiumpy/tests/test_datasource.py
1
3634
#!/usr/bin/env python # coding: utf-8 import unittest import nose import cesiumpy class TestDataSource(unittest.TestCase): def test_czmldatasource(self): ds = cesiumpy.CzmlDataSource('xxx.czml') exp = 'Cesium.CzmlDataSource.load("xxx.czml")' self.assertEqual(ds.script, exp) ds = cesiumpy.CzmlDataSource.load('xxx.czml') self.assertEqual(ds.script, exp) def test_geojsondatasource(self): ds = cesiumpy.GeoJsonDataSource('xxx.geojson') exp = 'Cesium.GeoJsonDataSource.load("xxx.geojson")' self.assertEqual(ds.script, exp) ds = cesiumpy.GeoJsonDataSource.load('xxx.geojson') self.assertEqual(ds.script, exp) ds = cesiumpy.GeoJsonDataSource('xxx.geojson', markerColor=cesiumpy.color.RED, stroke=cesiumpy.color.BLUE, fill=cesiumpy.color.GREEN) exp = 'Cesium.GeoJsonDataSource.load("xxx.geojson", {markerColor : Cesium.Color.RED, stroke : Cesium.Color.BLUE, fill : Cesium.Color.GREEN})' self.assertEqual(ds.script, exp) ds = cesiumpy.GeoJsonDataSource.load('xxx.geojson', markerColor=cesiumpy.color.RED, stroke=cesiumpy.color.BLUE, fill=cesiumpy.color.GREEN) self.assertEqual(ds.script, exp) ds = cesiumpy.GeoJsonDataSource('xxx.geojson', markerColor='red', stroke='blue', fill='green') self.assertEqual(ds.script, exp) ds = cesiumpy.GeoJsonDataSource.load('xxx.geojson', markerColor='red', stroke='blue', fill='green') self.assertEqual(ds.script, exp) def test_kmldatasource(self): ds = cesiumpy.KmlDataSource('xxx.kml') exp = 'Cesium.KmlDataSource.load("xxx.kml")' self.assertEqual(ds.script, exp) ds = cesiumpy.KmlDataSource.load('xxx.kml') self.assertEqual(ds.script, exp) def test_czml_viewer(self): v = cesiumpy.Viewer(divid='viewertest') d = cesiumpy.CzmlDataSource('data/simple.czml') v.dataSources.add(d) result = v.to_html() exp = """<script src="https://cesiumjs.org/Cesium/Build/Cesium/Cesium.js"></script> <link rel="stylesheet" href="https://cesiumjs.org/Cesium/Build/Cesium/Widgets/widgets.css" type="text/css"> <div id="viewertest" style="width:100%; height:100%;"><div> <script type="text/javascript"> var widget = new Cesium.Viewer("viewertest"); widget.dataSources.add(Cesium.CzmlDataSource.load("data/simple.czml")); </script>""" self.assertEqual(result, exp) def test_geojson_viewer(self): ds = cesiumpy.GeoJsonDataSource('./test.geojson', markerSymbol='?') viewer = cesiumpy.Viewer(divid='viewertest') viewer.dataSources.add(ds) viewer.camera.flyTo((-105.01621, 39.57422, 1000)) result = viewer.to_html() exp = """<script src="https://cesiumjs.org/Cesium/Build/Cesium/Cesium.js"></script> <link rel="stylesheet" href="https://cesiumjs.org/Cesium/Build/Cesium/Widgets/widgets.css" type="text/css"> <div id="viewertest" style="width:100%; height:100%;"><div> <script type="text/javascript"> var widget = new Cesium.Viewer("viewertest"); widget.dataSources.add(Cesium.GeoJsonDataSource.load("./test.geojson", {markerSymbol : "?"})); widget.camera.flyTo({destination : Cesium.Cartesian3.fromDegrees(-105.01621, 39.57422, 1000.0)}); </script>""" self.assertEqual(result, exp) if __name__ == '__main__': nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], exit=False)
apache-2.0
J0s3f/twittbot-nd
getuserbyid.py
1
1116
# This file is part of twittbot-nd # Copyright (C) 2013 nilsding # # 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/>. # This program gets the user ID of a given Twitter user (using sys.argv[1]) import sys import tweepy from config import oauth try: auth = tweepy.OAuthHandler(oauth.CONSUMER_KEY, oauth.CONSUMER_SECRET) auth.set_access_token(oauth.ACCESS_TOKEN, oauth.ACCESS_TOKEN_SECRET) print tweepy.API(auth).get_user(sys.argv[1]).screen_name except tweepy.error.TweepError, err: print(err.reason)
agpl-3.0
ismailsunni/geonode
geonode/services/forms.py
30
1667
from django import forms import taggit from geonode.services.models import Service, ServiceLayer from geonode.services.enumerations import SERVICE_TYPES from django.utils.translation import ugettext_lazy as _ class CreateServiceForm(forms.Form): # name = forms.CharField(label=_("Service Name"), max_length=512, # widget=forms.TextInput( # attrs={'size':'50', 'class':'inputText'})) url = forms.CharField(label=_("Service URL"), max_length=512, widget=forms.TextInput( attrs={'size': '65', 'class': 'inputText'})) name = forms.CharField(label=_('Service name'), max_length=128, widget=forms.TextInput( attrs={'size': '65', 'class': 'inputText'}), required=False) type = forms.ChoiceField( label=_("Service Type"), choices=SERVICE_TYPES, initial='AUTO', required=True) # method = forms.ChoiceField(label=_("Service Type"),choices=SERVICE_METHODS,initial='I',required=True) class ServiceForm(forms.ModelForm): title = forms.CharField(label=_('Title'), max_length=255, widget=forms.TextInput( attrs={'size': '60', 'class': 'inputText'})) description = forms.CharField( label=_('Description'), widget=forms.Textarea(attrs={'cols': 60})) abstract = forms.CharField( label=_("Abstract"), widget=forms.Textarea(attrs={'cols': 60})) keywords = taggit.forms.TagField(required=False) class Meta: model = Service fields = ('title', 'description', 'abstract', 'keywords', ) class ServiceLayerFormSet(forms.ModelForm): class Meta: model = ServiceLayer fields = ('typename',)
gpl-3.0
euhmeuh/django-ponies
ponies/apps/main/views.py
1
1088
# -*- coding: utf-8 -*- # # django-ponies # Sample Django project to get started # # Inspired by mibou # # Copyright (C) 2016 euhmeuh # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from django.shortcuts import render from ponies.common.views import BaseView from ponies.apps.main.models import Pony class HomeView(BaseView): template_name = "main/home.jade" def get(self, request): return render(request, self.template_name, { 'ponies': Pony.objects.all() })
gpl-3.0
south-coast-science/scs_core
tests/aqcsv/data/aqcsv_datetime_test.py
1
2628
#!/usr/bin/env python3 """ Created on 5 Mar 2019 @author: Bruno Beloff (bruno.beloff@southcoastscience.com) """ import pytz from scs_core.aqcsv.data.aqcsv_datetime import AQCSVDatetime from scs_core.data.datetime import LocalizedDatetime from scs_core.data.json import JSONify # -------------------------------------------------------------------------------------------------------------------- print("LocalizedDatetime...") now = LocalizedDatetime.construct_from_iso8601("2019-03-05T23:00:00.709+00:00") print("now: %s" % now) print("-") datetime = now.datetime print("datetime: %s" % datetime) print("-") tzinfo = now.tzinfo print("tzinfo: %s" % tzinfo) print("-") timezone = pytz.timezone('Europe/Athens') print("timezone: %s" % timezone) localised = now.localize(timezone) print("localised: %s" % localised) print("=") print("") print("") print("AQCSVDatetime without zone...") utc_aqcsv = AQCSVDatetime(now.datetime) print("utc_aqcsv: %s" % utc_aqcsv) print("filename_prefix: %s" % utc_aqcsv.filename_prefix()) print("-") print("utc_aqcsv localised: %s" % utc_aqcsv.localised()) print("-") code = JSONify.dumps(utc_aqcsv).strip('"') print(code) utc_aqcsv = AQCSVDatetime.construct_from_code(code) print("utc_aqcsv: %s" % utc_aqcsv) print("-") jstr = JSONify.dumps(utc_aqcsv).strip('"') print(jstr) print("=") print("") print("") print("AQCSVDatetime with zone...") local_aqcsv = AQCSVDatetime(localised.datetime, timezone) print("local_aqcsv: %s" % local_aqcsv) print("filename_prefix: %s" % local_aqcsv.filename_prefix()) print("-") print("local_aqcsv localised: %s" % local_aqcsv.localised()) print("-") code = JSONify.dumps(local_aqcsv).strip('"') print(code) local_aqcsv = AQCSVDatetime.construct_from_code(code) print("local_aqcsv: %s" % local_aqcsv) print("-") jstr = JSONify.dumps(local_aqcsv).strip('"') print(jstr) print("=") print("") print("") print("AQCSVDatetime with unreported zone...") nrz_aqcsv = AQCSVDatetime(localised.datetime) print("nrz_aqcsv: %s" % nrz_aqcsv) print("filename_prefix: %s" % nrz_aqcsv.filename_prefix()) print("-") print("nrz_aqcsv localised: %s" % nrz_aqcsv.localised()) print("-") code = JSONify.dumps(nrz_aqcsv).strip('"') print(code) nrz_aqcsv = AQCSVDatetime.construct_from_code(code) print("nrz_aqcsv: %s" % nrz_aqcsv) print("-") jstr = JSONify.dumps(nrz_aqcsv).strip('"') print(jstr) print("=") print("") print("") print("utc_aqcsv == local_aqcsv...") equality = local_aqcsv == utc_aqcsv print("equality: %s" % equality) print("-") print("utc_aqcsv == nrz_aqcsv...") equality = utc_aqcsv == nrz_aqcsv print("equality: %s" % equality) print("-")
mit
code-disaster/fips
tools/android-create-apk.py
1
7461
#------------------------------------------------------------------------------- # android-create-apk.py # # Helper script to create an APK project directory and create # an APK. # # The Android SDK is expected under "fips-sdks/android/" # # Arguments: # # --path the current cmake binary dir (where the .so file resides) # --deploy path where the .apk file will be copied to # --name the target name (result will be target.apk) # --abi "armeabi-v7a", "mips" or "x86" (default is armeabi-v7a) # --version the Android SDK platform version (default is "21") # --package the APK main package name (e.g. org.fips.bla) # import sys import os import argparse import shutil import subprocess import platform fips_dir = os.path.normpath(os.path.dirname(os.path.abspath(__file__)) + '/..') # find the path of rt.jar jre_paths = subprocess.check_output(['java', 'GetRT'], cwd=fips_dir+'/tools').decode("utf-8") if platform.system() == 'Windows': jre_paths = jre_paths.replace('\\','/').split(';') else: jre_paths = jre_paths.split(':') RT_JAR = None for jre_path in jre_paths: if jre_path.endswith('rt.jar'): RT_JAR = jre_path break SDK_HOME = os.path.abspath(fips_dir + '/../fips-sdks/android/') + '/' BUILD_TOOLS = SDK_HOME + 'build-tools/27.0.3/' EXE = '.exe' if platform.system() == 'Windows' else '' BAT = '.bat' if platform.system() == 'Windows' else '' AAPT = BUILD_TOOLS + 'aapt' + EXE DX = BUILD_TOOLS + 'dx' + BAT ZIPALIGN = BUILD_TOOLS + 'zipalign' + EXE APKSIGNER = BUILD_TOOLS + 'apksigner' + BAT if not RT_JAR: print("Can't find rt.jar (is the Java JDK installed?)") sys.exit(10) if not os.path.isfile(RT_JAR): print("Can't find Java runtime package '{}'!".format(RT_JAR)) sys.exit(10) if not os.path.isdir(SDK_HOME): print("Can't find Android SDK '{}'!".format(SDK_HOME)) sys.exit(10) for tool in [AAPT, DX, ZIPALIGN, APKSIGNER]: if not os.path.isfile(tool): print("Can't find required tool in Android SDK: {}".format(tool)) sys.exit(10) parser = argparse.ArgumentParser(description="Android APK package helper.") parser.add_argument('--path', help='path to the cmake build dir', required=True) parser.add_argument('--deploy', help='path where resulting APK will be copied to', required=True) parser.add_argument('--name', help='cmake target name', required=True) parser.add_argument('--abi', help='the NDK ABI string (armeabi-v7a, mips or x86', default='armeabi-v7a') parser.add_argument('--version', help='the Android SDK platform version (e.g. 21)', default='21') parser.add_argument('--package', help='the Java package name', required=True) args = parser.parse_args() if not args.path.endswith('/'): args.path += '/' if not args.deploy.endswith('/'): args.deploy += '/' if not os.path.exists(args.deploy): os.makedirs(args.deploy) pkg_name = args.package.replace('-','_') # create the empty project apk_dir = args.path + 'android/' + args.name + '/' if not os.path.exists(apk_dir): os.makedirs(apk_dir) libs_dir = apk_dir + 'lib/' + args.abi + '/' if not os.path.exists(libs_dir): os.makedirs(libs_dir) src_dir = apk_dir + 'src/' + pkg_name.replace('.', '/') if not os.path.exists(src_dir): os.makedirs(src_dir) obj_dir = apk_dir + '/obj' if not os.path.exists(obj_dir): os.makedirs(obj_dir) bin_dir = apk_dir + '/bin' if not os.path.exists(bin_dir): os.makedirs(bin_dir) # copy the native shared library so_name = 'lib' + args.name + '.so' src_so = args.path + so_name dst_so = libs_dir + so_name shutil.copy(src_so, dst_so) # copy the dummy assets directory res_dir = apk_dir + 'res/' if not os.path.exists(res_dir): shutil.copytree(fips_dir + '/templates/android_assets/res', res_dir) # generate AndroidManifest.xml with open(apk_dir + 'AndroidManifest.xml', 'w') as f: f.write('<manifest xmlns:android="http://schemas.android.com/apk/res/android"\n') f.write(' package="{}"\n'.format(pkg_name)) f.write(' android:versionCode="1"\n') f.write(' android:versionName="1.0">\n') f.write(' <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="{}"/>\n'.format(args.version)) f.write(' <uses-permission android:name="android.permission.INTERNET"></uses-permission>\n') f.write(' <uses-feature android:glEsVersion="0x00030000"></uses-feature>\n') f.write(' <application android:label="{}" android:debuggable="true" android:hasCode="false">\n'.format(args.name)) f.write(' <activity android:name="android.app.NativeActivity"\n'); f.write(' android:label="{}"\n'.format(args.name)) f.write(' android:launchMode="singleTask"\n') f.write(' android:screenOrientation="fullUser"\n') f.write(' android:configChanges="orientation|screenSize|keyboard|keyboardHidden">\n') f.write(' <meta-data android:name="android.app.lib_name" android:value="{}"/>\n'.format(args.name)) f.write(' <intent-filter>\n') f.write(' <action android:name="android.intent.action.MAIN"/>\n') f.write(' <category android:name="android.intent.category.LAUNCHER"/>\n') f.write(' </intent-filter>\n') f.write(' </activity>\n') f.write(' </application>\n') f.write('</manifest>\n') # prepare APK structure cmd = [ AAPT, 'package', '-v', '-f', '-m', '-S', 'res', '-J', 'src', '-M', 'AndroidManifest.xml', '-I', SDK_HOME + 'platforms/android-' + args.version + '/android.jar' ] subprocess.call(cmd, cwd=apk_dir) # compile Java sources cmd = [ 'javac', '-d', './obj', '-source', '1.7', '-target', '1.7', '-sourcepath', 'src', '-bootclasspath', RT_JAR, src_dir + '/R.java' ] subprocess.call(cmd, cwd=apk_dir) # convert Java byte code to DEX cmd = [ DX, '--verbose', '--dex', '--output=bin/classes.dex', './obj' ] subprocess.call(cmd, cwd=apk_dir) # package the APK cmd = [ AAPT, 'package', '-v', '-f', '-S', 'res', '-M', 'AndroidManifest.xml', '-I', SDK_HOME + 'platforms/android-' + args.version + '/android.jar', '-F', args.path + args.name + '-unaligned.apk', 'bin' ] subprocess.call(cmd, cwd=apk_dir) cmd = [ AAPT, 'add', '-v', args.path + args.name + '-unaligned.apk', 'lib/'+args.abi+'/'+so_name ] subprocess.call(cmd, cwd=apk_dir) # run zipalign on the package cmd = [ ZIPALIGN, '-f', '4', args.path + args.name + '-unaligned.apk', args.path + args.name + '.apk' ] subprocess.call(cmd, cwd=apk_dir) # create debug signing key keystore_path = args.path + 'debug.keystore' if not os.path.exists(keystore_path): cmd = [ 'keytool', '-genkeypair', '-keystore', keystore_path, '-storepass', 'android', '-alias', 'androiddebugkey', '-keypass', 'android', '-keyalg', 'RSA', '-validity', '10000', '-dname', 'CN=,OU=,O=,L=,S=,C=' ] subprocess.call(cmd, cwd=apk_dir) # sign the APK cmd = [ APKSIGNER, 'sign', '-v', '--ks', keystore_path, '--ks-pass', 'pass:android', '--key-pass', 'pass:android', '--ks-key-alias', 'androiddebugkey', args.path + args.name + '.apk' ] subprocess.call(cmd, cwd=apk_dir) # verify the APK cmd = [ APKSIGNER, 'verify', '-v', args.path + args.name + '.apk' ] subprocess.call(cmd, cwd=apk_dir) # copy APK to the fips-deploy directory shutil.copy(args.path+args.name+'.apk', args.deploy+args.name+'.apk')
mit
whereismyjetpack/ansible
lib/ansible/modules/storage/netapp/na_cdot_user.py
14
10605
#!/usr/bin/python # (c) 2017, NetApp, Inc # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' module: na_cdot_users short_description: useradmin configuration and management extends_documentation_fragment: - netapp.ontap version_added: '2.3' author: Sumit Kumar (sumit4@netapp.com) description: - Create or destroy users. options: state: description: - Whether the specified user should exist or not. required: true choices: ['present', 'absent'] name: description: - The name of the user to manage. required: true application: description: - Applications to grant access to. required: true choices: ['console', 'http','ontapi','rsh','snmp','sp','ssh','telnet'] authentication_method: description: - Authentication method for the application. - Not all authentication methods are valid for an application. - Valid authentication methods for each application are as denoted in I(authentication_choices_description). authentication_choices_description: - password for console application - password, domain, nsswitch, cert for http application. - password, domain, nsswitch, cert for ontapi application. - community for snmp application (when creating SNMPv1 and SNMPv2 users). - usm and community for snmp application (when creating SNMPv3 users). - password for sp application. - password for rsh application. - password for telnet application. - password, publickey, domain, nsswitch for ssh application. required: true choices: ['community', 'password', 'publickey', 'domain', 'nsswitch', 'usm'] set_password: description: - Password for the user account. - It is ignored for creating snmp users, but is required for creating non-snmp users. - For an existing user, this value will be used as the new password. default: None role_name: description: - The name of the role. note: required when C(state=present) vserver: description: - The name of the vserver to use. required: true ''' EXAMPLES = """ - name: Create User na_cdot_user: state: present name: SampleUser application: ssh authentication_method: password set_password: apn1242183u1298u41 role_name: vsadmin vserver: ansibleVServer hostname: "{{ netapp_hostname }}" username: "{{ netapp_username }}" password: "{{ netapp_password }}" """ RETURN = """ """ from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.pycompat24 import get_exception import ansible.module_utils.netapp as netapp_utils HAS_NETAPP_LIB = netapp_utils.has_netapp_lib() class NetAppCDOTUser(object): """ Common operations to manage users and roles. """ def __init__(self): 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'), application=dict(required=True, type='str', choices=[ 'console', 'http', 'ontapi', 'rsh', 'snmp', 'sp', 'ssh', 'telnet']), authentication_method=dict(required=True, type='str', choices=['community', 'password', 'publickey', 'domain', 'nsswitch', 'usm']), set_password=dict(required=False, type='str', default=None), role_name=dict(required=False, type='str'), vserver=dict(required=True, type='str'), )) self.module = AnsibleModule( argument_spec=self.argument_spec, required_if=[ ('state', 'present', ['role_name']) ], supports_check_mode=True ) p = self.module.params # set up state variables self.state = p['state'] self.name = p['name'] self.application = p['application'] self.authentication_method = p['authentication_method'] self.set_password = p['set_password'] self.role_name = p['role_name'] self.vserver = p['vserver'] 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) def get_user(self): """ Checks if the user exists. :return: True if user found False if user is not found :rtype: bool """ security_login_get_iter = netapp_utils.zapi.NaElement('security-login-get-iter') query_details = netapp_utils.zapi.NaElement.create_node_with_children( 'security-login-account-info', **{'vserver': self.vserver, 'user-name': self.name, 'application': self.application, 'authentication-method': self.authentication_method}) query = netapp_utils.zapi.NaElement('query') query.add_child_elem(query_details) security_login_get_iter.add_child_elem(query) try: result = self.server.invoke_successfully(security_login_get_iter, enable_tunneling=False) if result.get_child_by_name('num-records') and int(result.get_child_content('num-records')) >= 1: return True else: return False except netapp_utils.zapi.NaApiError: e = get_exception() # Error 16034 denotes a user not being found. if str(e.code) == "16034": return False else: self.module.fail_json(msg='Error getting user %s' % self.name, exception=str(e)) def create_user(self): user_create = netapp_utils.zapi.NaElement.create_node_with_children( 'security-login-create', **{'vserver': self.vserver, 'user-name': self.name, 'application': self.application, 'authentication-method': self.authentication_method, 'role-name': self.role_name}) if self.set_password is not None: user_create.add_new_child('password', self.set_password) try: self.server.invoke_successfully(user_create, enable_tunneling=False) except netapp_utils.zapi.NaApiError: err = get_exception() self.module.fail_json(msg='Error creating user %s' % self.name, exception=str(err)) def delete_user(self): user_delete = netapp_utils.zapi.NaElement.create_node_with_children( 'security-login-delete', **{'vserver': self.vserver, 'user-name': self.name, 'application': self.application, 'authentication-method': self.authentication_method}) try: self.server.invoke_successfully(user_delete, enable_tunneling=False) except netapp_utils.zapi.NaApiError: err = get_exception() self.module.fail_json(msg='Error removing user %s' % self.name, exception=str(err)) def change_password(self): """ Changes the password :return: True if password updated False if password is not updated :rtype: bool """ self.server.set_vserver(self.vserver) modify_password = netapp_utils.zapi.NaElement.create_node_with_children( 'security-login-modify-password', **{ 'new-password': str(self.set_password), 'user-name': self.name}) try: self.server.invoke_successfully(modify_password, enable_tunneling=True) except netapp_utils.zapi.NaApiError: e = get_exception() if str(e.code) == '13114': return False else: err = get_exception() self.module.fail_json(msg='Error setting password for user %s' % self.name, exception=str(err)) self.server.set_vserver(None) return True def apply(self): property_changed = False password_changed = False user_exists = self.get_user() if user_exists: if self.state == 'absent': property_changed = True elif self.state == 'present': if self.set_password is not None: password_changed = self.change_password() else: if self.state == 'present': # Check if anything needs to be updated property_changed = True if property_changed: if self.module.check_mode: pass else: if self.state == 'present': if not user_exists: self.create_user() # Add ability to update parameters. elif self.state == 'absent': self.delete_user() changed = property_changed or password_changed self.module.exit_json(changed=changed) def main(): v = NetAppCDOTUser() v.apply() if __name__ == '__main__': main()
gpl-3.0
nucular/AutobahnPython
examples/twisted/wamp/rpc/timeservice/backend.py
8
2290
############################################################################### # # The MIT License (MIT) # # Copyright (c) Tavendo GmbH # # 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 os import environ import datetime from twisted.internet.defer import inlineCallbacks from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner class Component(ApplicationSession): """ A simple time service application component. """ @inlineCallbacks def onJoin(self, details): print("session attached") def utcnow(): now = datetime.datetime.utcnow() return now.strftime("%Y-%m-%dT%H:%M:%SZ") try: yield self.register(utcnow, u'com.timeservice.now') except Exception as e: print("failed to register procedure: {}".format(e)) else: print("procedure registered") if __name__ == '__main__': runner = ApplicationRunner( environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws"), u"crossbardemo", debug_wamp=False, # optional; log many WAMP details debug=False, # optional; log even more details ) runner.run(Component)
mit
heromod/migrid
mig/server/grid_monitor.py
1
28123
#!/usr/bin/python # -*- coding: utf-8 -*- # # --- BEGIN_HEADER --- # # grid_monitor - Monitor page generator # Copyright (C) 2003-2015 The MiG Project lead by Brian Vinter # # This file is part of MiG. # # MiG 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. # # MiG is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # -- END_HEADER --- # """Creating the MiG monitor page""" import os import time import datetime from shared.conf import get_configuration_object from shared.defaults import default_vgrid from shared.fileio import unpickle from shared.gridstat import GridStat from shared.html import get_cgi_html_header, get_cgi_html_footer, themed_styles from shared.output import format_timedelta from shared.resource import anon_resource_id from shared.vgrid import vgrid_list_vgrids print """ Running grid monitor generator. Set the MIG_CONF environment to the server configuration path unless it is available in mig/server/MiGserver.conf """ configuration = get_configuration_object() logger = configuration.logger # Make sure that the default VGrid home used by monitor exists default_vgrid_dir = os.path.join(configuration.vgrid_home, default_vgrid) if not os.path.isdir(default_vgrid_dir): try: os.makedirs(default_vgrid_dir) except OSError, ose: logger.error('Failed to create default VGrid home: %s' % ose) def create_monitor(vgrid_name): """Write monitor HTML file for vgrid_name""" html_file = os.path.join(configuration.vgrid_home, vgrid_name, '%s.html' % configuration.vgrid_monitor) print 'collecting statistics for VGrid %s' % vgrid_name sleep_secs = configuration.sleep_secs slackperiod = configuration.slackperiod now = time.asctime(time.localtime()) html_vars = { 'sleep_secs': sleep_secs, 'vgrid_name': vgrid_name, 'logo_url': '/images/logo.jpg', 'now': now, 'short_title': configuration.short_title, } html = get_cgi_html_header( configuration, '%(short_title)s Monitor, VGrid %(vgrid_name)s' % html_vars, '', True, '''<meta http-equiv="refresh" content="%(sleep_secs)s" /> ''' % html_vars, themed_styles(configuration), ''' <script type="text/javascript" src="/images/js/jquery.js"></script> <script type="text/javascript" src="/images/js/jquery.tablesorter.js"></script> <script type="text/javascript" > $(document).ready(function() { // table initially sorted by col. 1 (name) var sortOrder = [[1,0]]; // use image path for sorting if there is any inside var imgTitle = function(contents) { var key = $(contents).find("a").attr("class"); if (key == null) { key = $(contents).html(); } return key; } $("table.monitor").tablesorter({widgets: ["zebra"], textExtraction: imgTitle, }); $("table.monitor").each(function () { try { $(this).trigger("sorton", [sortOrder]); } catch(err) { /* tablesorter chokes on empty tables - just continue */ } }); } ); </script> ''', '', False, ) html += \ ''' <!-- end of raw header: this line is used by showvgridmonitor --> <h1>Statistics/monitor for the %(vgrid_name)s VGrid</h1> <div class="generatornote smallcontent"> This page was generated %(now)s (automatic refresh every %(sleep_secs)s secs). </div> '''\ % html_vars # loop and get totals parse_count = 0 queued_count = 0 frozen_count = 0 executing_count = 0 finished_count = 0 failed_count = 0 retry_count = 0 canceled_count = 0 cpucount_requested = 0 cpucount_done = 0 nodecount_requested = 0 nodecount_done = 0 cputime_requested = 0 cputime_done = 0 used_walltime = 0 disk_requested = 0 disk_done = 0 memory_requested = 0 memory_done = 0 runtimeenv_dict = {'': 0} runtimeenv_requested = 0 runtimeenv_done = 0 number_of_jobs = 0 up_count = 0 down_count = 0 slack_count = 0 job_assigned = 0 job_assigned_cpus = 0 gstat = GridStat(configuration, logger) runtimeenv_dict = gstat.get_value(gstat.VGRID, vgrid_name.upper(), 'RUNTIMEENVIRONMENT', {}) parse_count = gstat.get_value(gstat.VGRID, vgrid_name.upper(), 'PARSE') queued_count = gstat.get_value(gstat.VGRID, vgrid_name.upper(), 'QUEUED') frozen_count = gstat.get_value(gstat.VGRID, vgrid_name.upper(), 'FROZEN') executing_count = gstat.get_value(gstat.VGRID, vgrid_name.upper(), 'EXECUTING') failed_count = gstat.get_value(gstat.VGRID, vgrid_name.upper(), 'FAILED') retry_count = gstat.get_value(gstat.VGRID, vgrid_name.upper(), 'RETRY') canceled_count = gstat.get_value(gstat.VGRID, vgrid_name.upper(), 'CANCELED') expired_count = gstat.get_value(gstat.VGRID, vgrid_name.upper(), 'EXPIRED') finished_count = gstat.get_value(gstat.VGRID, vgrid_name.upper(), 'FINISHED') nodecount_requested = gstat.get_value(gstat.VGRID, vgrid_name.upper(), 'NODECOUNT_REQ') nodecount_done = gstat.get_value(gstat.VGRID, vgrid_name.upper(), 'NODECOUNT_DONE') cputime_requested = gstat.get_value(gstat.VGRID, vgrid_name.upper(), 'CPUTIME_REQ') cputime_done = gstat.get_value(gstat.VGRID, vgrid_name.upper(), 'CPUTIME_DONE') used_walltime = gstat.get_value(gstat.VGRID, vgrid_name.upper(), 'USED_WALLTIME') if (used_walltime == 0): used_walltime = datetime.timedelta(0) used_walltime = format_timedelta(used_walltime) disk_requested = gstat.get_value(gstat.VGRID, vgrid_name.upper(), 'DISK_REQ') disk_done = gstat.get_value(gstat.VGRID, vgrid_name.upper(), 'DISK_DONE') memory_requested = gstat.get_value(gstat.VGRID, vgrid_name.upper(), 'MEMORY_REQ') memory_done = gstat.get_value(gstat.VGRID, vgrid_name.upper(), 'MEMORY_DONE') cpucount_requested = gstat.get_value(gstat.VGRID, vgrid_name.upper(), 'CPUCOUNT_REQ') cpucount_done = gstat.get_value(gstat.VGRID, vgrid_name.upper(), 'CPUCOUNT_DONE') runtimeenv_requested = gstat.get_value(gstat.VGRID, vgrid_name.upper(), 'RUNTIMEENVIRONMENT_REQ') runtimeenv_done = gstat.get_value(gstat.VGRID, vgrid_name.upper(), 'RUNTIMEENVIRONMENT_DONE') number_of_jobs = parse_count number_of_jobs += queued_count number_of_jobs += frozen_count number_of_jobs += expired_count number_of_jobs += canceled_count number_of_jobs += failed_count number_of_jobs += executing_count number_of_jobs += finished_count number_of_jobs += retry_count html_vars = { 'parse_count': parse_count, 'queued_count': queued_count, 'frozen_count': frozen_count, 'executing_count': executing_count, 'failed_count': failed_count, 'retry_count': retry_count, 'canceled_count': canceled_count, 'expired_count': expired_count, 'finished_count': finished_count, 'number_of_jobs': number_of_jobs, 'cpucount_requested': cpucount_requested, 'cpucount_done': cpucount_done, 'nodecount_requested': nodecount_requested, 'nodecount_done': nodecount_done, 'cputime_requested': cputime_requested, 'cputime_done': cputime_done, 'used_walltime': used_walltime, 'disk_requested': disk_requested, 'disk_done': disk_done, 'memory_requested': memory_requested, 'memory_done': memory_done, 'runtimeenv_requested': runtimeenv_requested, 'runtimeenv_done': runtimeenv_done, } html += \ """<h2>Job Stats</h2><table class=monitorstats><tr><td> <table class=monitorjobs><tr class=title><td>Job State</td><td>Number of jobs</td></tr> <tr><td>Parse</td><td>%(parse_count)s</td></tr> <tr><td>Queued</td><td>%(queued_count)s</td></tr> <tr><td>Frozen</td><td>%(frozen_count)s</td></tr> <tr><td>Executing</td><td>%(executing_count)s</td></tr> <tr><td>Failed</td><td>%(failed_count)s</td></tr> <tr><td>Retry</td><td>%(retry_count)s</td></tr> <tr><td>Canceled</td><td>%(canceled_count)s</td></tr> <tr><td>Expired</td><td>%(expired_count)s</td></tr> <tr><td>Finished</td><td>%(finished_count)s</td></tr> <tr><td>Total</td><td>%(number_of_jobs)s</td></tr> </table> </td><td> <table class=monitorresreq> <tr class=title><td>Requirement</td><td>Requested</td><td>Done</td></tr> <tr><td>Cpucount</td><td>%(cpucount_requested)s</td><td>%(cpucount_done)s</td></tr> <tr><td>Nodecount</td><td>%(nodecount_requested)s</td><td>%(nodecount_done)s</td></tr> <tr><td>Cputime</td><td>%(cputime_requested)s</td><td>%(cputime_done)s</td></tr> <tr><td>GB Disk</td><td>%(disk_requested)s</td><td>%(disk_done)s</td></tr> <tr><td>MB Memory</td><td>%(memory_requested)s</td><td>%(memory_done)s</td></tr> <tr><td>Runtime Envs</td><td>%(runtimeenv_requested)s</td><td>%(runtimeenv_done)s</td></tr> <tr><td>Used Walltime</td><td colspan='2'>%(used_walltime)s</td></tr> </table><br /> </td><td> <div class=monitorruntimeenvdetails> <table class=monitorruntimeenvdone> <tr class=title><td>Runtime Envs Done</td><td></td></tr> """\ % html_vars if len(runtimeenv_dict.keys()) < 1: # No runtimeenv requests html += '<tr><td></td><td>-</td></tr>\n' else: for entry in runtimeenv_dict.keys(): if not entry == '': html += '<tr><td>' + entry + '</td><td>'\ + str(runtimeenv_dict[entry]) + '</td></tr>\n' total_number_of_exe_resources, total_number_of_store_resources = 0, 0 total_number_of_exe_cpus, total_number_of_store_gigs= 0, 0 vgrid_name_list = vgrid_name.split('/') current_dir = '' exes, stores = '', '' for vgrid_name_part in vgrid_name_list: current_dir = os.path.join(current_dir, vgrid_name_part) abs_mon_dir = os.path.join(configuration.vgrid_home, current_dir) # print 'dir: %s' % abs_mon_dir # Potential race - just ignore if it disappeared try: sorted_names = os.listdir(abs_mon_dir) except OSError: continue sorted_names.sort() for filename in sorted_names: # print filename if filename.startswith('monitor_last_request_'): # read last request helper file mon_file_name = os.path.join(abs_mon_dir, filename) print 'found ' + mon_file_name last_request_dict = unpickle(mon_file_name, logger) if not last_request_dict: print 'could not open and unpickle: '\ + mon_file_name continue difference = datetime.datetime.now()\ - last_request_dict['CREATED_TIME'] days = str(difference.days) hours = str(difference.seconds / 3600) minutes = str((difference.seconds % 3600) / 60) seconds = str((difference.seconds % 60) % 60) if last_request_dict.has_key('CPUTIME'): cputime = last_request_dict['CPUTIME'] elif last_request_dict.has_key('cputime'): cputime = last_request_dict['cputime'] else: print 'ERROR: last request does not contain cputime field!: %s'\ % last_request_dict continue try: cpusec = int(cputime) except ValueError: try: cpusec = int(float(cputime)) except ValueError, verr: print 'ERROR: failed to parse cputime %s: %s'\ % (cputime, verr) # Include execution delay guesstimate for strict fill # LRMS resources try: delay = int(last_request_dict['EXECUTION_DELAY']) except KeyError: delay = 0 except ValueError: delay = 0 time_remaining = (last_request_dict['CREATED_TIME'] + datetime.timedelta(seconds=cpusec) + datetime.timedelta(seconds=delay))\ - datetime.datetime.now() days_rem = str(time_remaining.days) hours_rem = str(time_remaining.seconds / 3600) minutes_rem = str((time_remaining.seconds % 3600) / 60) seconds_rem = str((time_remaining.seconds % 60) % 60) if time_remaining.days < -7: try: print 'removing: %s as we havent seen him for %s days.'\ % (mon_file_name, abs(time_remaining).days) os.remove(mon_file_name) except Exception, err: print "could not remove: '%s' Error: %s"\ % (mon_file_name, str(err)) pass else: unique_res_name_and_exe_list = \ filename.split('monitor_last_request_', 1) if cpusec == 0: resource_status = 'unavailable' elif time_remaining.days < 0: # time_remaining.days < 0 means that we have passed the specified time time_rem_abs = abs(time_remaining) if time_rem_abs.days == 0\ and int(time_rem_abs.seconds)\ < int(slackperiod): resource_status = 'slack' slack_count = slack_count + 1 else: resource_status = 'offline' down_count = down_count + 1 else: resource_status = 'online' up_count = up_count + 1 exes += '<tr>' exes += \ '<td><img src=/images/status-icons/%s.png /></td>'\ % resource_status public_id = unique_res_name_and_exe_list[1] if last_request_dict['RESOURCE_CONFIG'].get('ANONYMOUS', True): public_id = anon_resource_id(public_id) public_name = last_request_dict['RESOURCE_CONFIG'].get('PUBLICNAME', '') resource_parts = public_id.split('_', 2) resource_name = "<a href='viewres.py?unique_resource_name=%s'>%s</a>" % \ (resource_parts[0], resource_parts[0]) if public_name: resource_name += "<br />(alias %s)" % public_name else: resource_name += "<br />(no alias)" resource_name += "<br />%s" % resource_parts[1] exes += '<td>%s</td>' % resource_name exes += '<td>%s<br />(%sd %sh %sm %ss ago)</td>' % \ (time.asctime(last_request_dict['CREATED_TIME'].timetuple()), days, hours, minutes, seconds) exes += '<td>' + vgrid_name + '</td>' runtime_envs = last_request_dict['RESOURCE_CONFIG' ]['RUNTIMEENVIRONMENT'] re_list_text = ', '.join([i[0] for i in runtime_envs]) exes += '<td title="%s">' % re_list_text \ + str(len(runtime_envs)) + '</td>' exes += '<td>'\ + str(last_request_dict['RESOURCE_CONFIG' ]['CPUTIME']) + '</td><td>'\ + str(last_request_dict['RESOURCE_CONFIG' ]['NODECOUNT']) + '</td><td>'\ + str(last_request_dict['RESOURCE_CONFIG' ]['CPUCOUNT']) + '</td><td>'\ + str(last_request_dict['RESOURCE_CONFIG' ]['DISK']) + '</td><td>'\ + str(last_request_dict['RESOURCE_CONFIG' ]['MEMORY']) + '</td><td>'\ + str(last_request_dict['RESOURCE_CONFIG' ]['ARCHITECTURE']) + '</td>' exes += '<td>' + last_request_dict['STATUS']\ + '</td><td>' + str(last_request_dict['CPUTIME' ]) + '</td>' exes += '<td class=status_%s>' % resource_status if 'unavailable' == resource_status: exes += '-' elif 'slack' == resource_status: exes += 'Within slack period (%s < %s secs)'\ % (time_rem_abs.seconds, slackperiod) elif 'offline' == resource_status: exes += 'down?' else: exes += '%sd, %sh, %sm, %ss'\ % (days_rem, hours_rem, minutes_rem, seconds_rem) exes += '</td>' exes += '</tr>\n' if last_request_dict['STATUS'] == 'Job assigned': job_assigned = job_assigned + 1 job_assigned_cpus = job_assigned_cpus\ + int(last_request_dict['RESOURCE_CONFIG' ]['NODECOUNT'])\ * int(last_request_dict['RESOURCE_CONFIG' ]['CPUCOUNT']) total_number_of_exe_resources += 1 total_number_of_exe_cpus += int( last_request_dict['RESOURCE_CONFIG']['NODECOUNT']) \ * int(last_request_dict['RESOURCE_CONFIG']['CPUCOUNT']) elif filename.startswith('monitor_last_status_'): # store must be linked to this vgrid, not only parent vgrid: # inheritance only covers access, not automatic participation if current_dir != vgrid_name: continue # read last resource action status file mon_file_name = os.path.join(abs_mon_dir, filename) print 'found ' + mon_file_name last_status_dict = unpickle(mon_file_name, logger) if not last_status_dict: print 'could not open and unpickle: '\ + mon_file_name continue difference = datetime.datetime.now()\ - last_status_dict['CREATED_TIME'] days = str(difference.days) hours = str(difference.seconds / 3600) minutes = str((difference.seconds % 3600) / 60) seconds = str((difference.seconds % 60) % 60) if last_status_dict['STATUS'] == 'stopped': time_stopped = datetime.datetime.now() - \ last_status_dict['CREATED_TIME'] if time_stopped.days > 7: try: print 'removing: %s as we havent seen him for %s days.'\ % (mon_file_name, abs(time_stopped).days) os.remove(mon_file_name) except Exception, err: print "could not remove: '%s' Error: %s"\ % (mon_file_name, str(err)) continue unique_res_name_and_store_list = filename.split( 'monitor_last_status_', 1) mount_point = last_status_dict.get('MOUNT_POINT', 'UNKNOWN') is_live = os.path.ismount(mount_point) public_id = unique_res_name_and_store_list[1] if last_status_dict['RESOURCE_CONFIG'].get('ANONYMOUS', True): public_id = anon_resource_id(public_id) vgrid_link = os.path.join( configuration.vgrid_files_home, vgrid_name, public_id) is_linked = (os.path.realpath(vgrid_link) == mount_point) total_disk = last_status_dict['RESOURCE_CONFIG']['DISK'] free_disk, avail_disk, used_disk, used_percent = 0, 0, 0, 0 gig_bytes = 1.0 * 2**30 # Fall back status - show last action unless statvfs succeeds store_status = '<td>%s %s<br />(%sd %sh %sm %ss ago)</td>' % \ (last_status_dict['STATUS'], time.asctime(last_status_dict['CREATED_TIME'].timetuple()), days, hours, minutes, seconds) # These disk stats are slightly confusing but match 'df' # 'available' is the space that can actually be used so it # is typically less than 'free'. try: disk_stats = os.statvfs(mount_point) total_disk = disk_stats.f_bsize * disk_stats.f_blocks / \ gig_bytes avail_disk = disk_stats.f_bsize * disk_stats.f_bavail / \ gig_bytes free_disk = disk_stats.f_bsize * disk_stats.f_bfree / \ gig_bytes used_disk = total_disk - free_disk used_percent = 100.0 * used_disk / (avail_disk + used_disk) store_status = '<td>%s %s<br />(%sd %sh %sm %ss ago)</td>' % \ ('checked', time.asctime(), 0, 0, 0, 0) except OSError, ose: print 'could not stat mount point %s: %s' % \ (mount_point, ose) is_live = False if last_status_dict['STATUS'] == 'stopped': resource_status = 'offline' down_count = down_count + 1 elif last_status_dict['STATUS'] == 'started': if is_live and is_linked: resource_status = 'online' up_count = up_count + 1 else: resource_status = 'slack' down_count = down_count + 1 else: resource_status = 'unknown' stores += '<tr>' stores += \ '<td><img src=/images/status-icons/%s.png /></td>'\ % resource_status public_name = last_status_dict['RESOURCE_CONFIG'].get('PUBLICNAME', '') resource_parts = public_id.split('_', 2) resource_name = "<a href='viewres.py?unique_resource_name=%s'>%s</a>" % \ (resource_parts[0], resource_parts[0]) if public_name: resource_name += "<br />(alias %s)" % public_name else: resource_name += "<br />(no alias)" resource_name += "<br />%s" % resource_parts[1] stores += '<td>%s</td>' % resource_name stores += store_status stores += '<td>' + vgrid_name + '</td>' stores += '<td>%d</td>' % total_disk stores += '<td>%d</td>' % used_disk stores += '<td>%d</td>' % avail_disk stores += '<td>%d</td>' % used_percent stores += '<td class=status_%s>' % resource_status stores += resource_status + '</td>' stores += '</tr>\n' total_number_of_store_resources += 1 total_number_of_store_gigs += total_disk html += """</table> </div> </td></tr> </table> <h2>Resource Job Requests</h2> Listing the last request from each resource<br /> <br /> <table class="monitor columnsort"> <thead class="title"> <tr> <th class="icon"><!-- Status icon --></th> <th>Resource ID, unit</th> <th>Last seen</th> <th>VGrid</th> <th>Runtime envs</th> <th>CPU time (s)</th> <th>Node count</th> <th>CPU count</th> <th>Disk (GB)</th> <th>Memory (MB)</th> <th>Arch</th> <th>Status</th> <th>Job (s)</th> <th>Remaining</th> </tr> </thead> <tbody> """ html += exes html += '</tbody>\n</table>\n' html += """ <h2>Resource Storage</h2> Listing the last check for each resource<br /> <br /> <table class="monitor columnsort"> <thead class="title"> <tr> <th class="icon"><!-- Status icon --></th> <th>Resource ID, unit</th> <th>Last Status</th> <th>VGrid</th> <th>Total Disk (GB)</th> <th>Used Disk (GB)</th> <th>Available Disk (GB)</th> <th>Disk Use %</th> <th>Status</th> </tr> </thead> <tbody> """ html += stores html += '</tbody>\n</table>\n' html += ''' <h2>VGrid Totals</h2> A total of <b>'''\ + str(total_number_of_exe_resources) + '</b> exe resources ('\ + str(total_number_of_exe_cpus) + " cpu's) and <b>"\ + str(total_number_of_store_resources) + '</b> store resources ('\ + str(int(total_number_of_store_gigs)) + " GB) joined this VGrid ("\ + str(up_count) + ' up, ' + str(down_count) + ' down?, '\ + str(slack_count) + ' slack)<br />' html += str(job_assigned) + ' exe resources (' + str(job_assigned_cpus)\ + """ cpu's) appear to be executing a job<br /> <br /> """ html += \ '<!-- begin raw footer: this line is used by showvgridmonitor -->' html += get_cgi_html_footer(configuration, '') try: file_handle = open(html_file, 'w') file_handle.write(html) file_handle.close() except Exception, exc: print 'Could not write monitor page %s: %s' % (html_file, exc) while True: (status, vgrids_list) = vgrid_list_vgrids(configuration) # create global statistics ("") # vgrids_list.append("") print 'Updating cache.' grid_stat = GridStat(configuration, logger) grid_stat.update() for vgrid_name in vgrids_list: print 'creating monitor for vgrid: %s' % vgrid_name create_monitor(vgrid_name) print 'sleeping for %s seconds' % configuration.sleep_secs time.sleep(float(configuration.sleep_secs))
gpl-2.0
mat128/netman
netman/api/switch_session_api.py
2
3616
# Copyright 2015 Internap. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from flask import request from netman.api.api_utils import BadRequest, to_response from netman.api.switch_api_base import SwitchApiBase from netman.api.validators import resource, content, Session, \ Resource, is_session class SwitchSessionApi(SwitchApiBase): def __init__(self, switch_factory, sessions_manager): super(SwitchSessionApi, self).__init__(switch_factory, sessions_manager) self.server = None def hook_to(self, server): server.add_url_rule('/switches-sessions/<session_id>', view_func=self.open_session, methods=['POST']) server.add_url_rule('/switches-sessions/<session_id>', view_func=self.close_session, methods=['DELETE']) server.add_url_rule('/switches-sessions/<session_id>/actions', view_func=self.act_on_session, methods=['POST']) server.add_url_rule('/switches-sessions/<session_id>/<path:resource>', view_func=self.on_session, methods=['GET', 'PUT', 'POST', 'DELETE']) self.server = server return self @to_response @content(is_session) def open_session(self, session_id, hostname): """ Open a locked session on a switch :arg str hostname: Hostname or IP of the switch :body: .. literalinclude:: ../../../tests/api/fixtures/post_switch_session.json :language: json :code 201 CREATED: Example output: .. literalinclude:: ../../../tests/api/fixtures/post_switch_session_result.json :language: json """ switch = self.resolve_switch(hostname) session_id = self.sessions_manager.open_session(switch, session_id) return 201, {'session_id': session_id} @to_response @resource(Session) def close_session(self, session_id): """ Close a session on a switch :arg str session: ID of the session """ self.sessions_manager.close_session(session_id) return 204, None @to_response @resource(Session, Resource) def on_session(self, session_id, resource_name): self.sessions_manager.keep_alive(session_id) with self.server.test_client() as http_client: response = http_client.open( '/switches/{}/{}'.format(session_id, resource_name), method=request.method, headers={k: v for k, v in request.headers.items()}, data=request.data) return response @to_response @resource(Session) def act_on_session(self, session_id): """ Commit or rollback a session on a switch :arg str session: ID of the session :body: ``commit`` or ``rollback`` """ action = request.data.lower() if action == 'commit': self.sessions_manager.commit_session(session_id) elif action == 'rollback': self.sessions_manager.rollback_session(session_id) else: raise BadRequest('Unknown action {}'.format(action)) return 204, None
apache-2.0
AOSP-S4-KK/platform_external_chromium_org
third_party/protobuf/python/google/protobuf/descriptor_database.py
230
4411
# Protocol Buffers - Google's data interchange format # Copyright 2008 Google Inc. All rights reserved. # http://code.google.com/p/protobuf/ # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Provides a container for DescriptorProtos.""" __author__ = 'matthewtoia@google.com (Matt Toia)' class DescriptorDatabase(object): """A container accepting FileDescriptorProtos and maps DescriptorProtos.""" def __init__(self): self._file_desc_protos_by_file = {} self._file_desc_protos_by_symbol = {} def Add(self, file_desc_proto): """Adds the FileDescriptorProto and its types to this database. Args: file_desc_proto: The FileDescriptorProto to add. """ self._file_desc_protos_by_file[file_desc_proto.name] = file_desc_proto package = file_desc_proto.package for message in file_desc_proto.message_type: self._file_desc_protos_by_symbol.update( (name, file_desc_proto) for name in _ExtractSymbols(message, package)) for enum in file_desc_proto.enum_type: self._file_desc_protos_by_symbol[ '.'.join((package, enum.name))] = file_desc_proto def FindFileByName(self, name): """Finds the file descriptor proto by file name. Typically the file name is a relative path ending to a .proto file. The proto with the given name will have to have been added to this database using the Add method or else an error will be raised. Args: name: The file name to find. Returns: The file descriptor proto matching the name. Raises: KeyError if no file by the given name was added. """ return self._file_desc_protos_by_file[name] def FindFileContainingSymbol(self, symbol): """Finds the file descriptor proto containing the specified symbol. The symbol should be a fully qualified name including the file descriptor's package and any containing messages. Some examples: 'some.package.name.Message' 'some.package.name.Message.NestedEnum' The file descriptor proto containing the specified symbol must be added to this database using the Add method or else an error will be raised. Args: symbol: The fully qualified symbol name. Returns: The file descriptor proto containing the symbol. Raises: KeyError if no file contains the specified symbol. """ return self._file_desc_protos_by_symbol[symbol] def _ExtractSymbols(desc_proto, package): """Pulls out all the symbols from a descriptor proto. Args: desc_proto: The proto to extract symbols from. package: The package containing the descriptor type. Yields: The fully qualified name found in the descriptor. """ message_name = '.'.join((package, desc_proto.name)) yield message_name for nested_type in desc_proto.nested_type: for symbol in _ExtractSymbols(nested_type, message_name): yield symbol for enum_type in desc_proto.enum_type: yield '.'.join((message_name, enum_type.name))
bsd-3-clause
psaavedra/matrix-bot
matrixbot/plugins/trac.py
1
3472
import xmlrpc.client from datetime import datetime, timedelta from matrixbot import utils class TracPlugin: def __init__(self, bot, settings): self.logger = utils.get_logger() self.name = "TracPlugin" self.bot = bot self.settings = settings self.logger.info("TracPlugin loaded (%(name)s)" % settings) self.timestamp = datetime.utcnow() self.server = xmlrpc.client.ServerProxy( '%(url_protocol)s://%(url_auth_user)s:%(url_auth_password)s@%(url_domain)s%(url_path)s/login/xmlrpc' % self.settings ) def pretty_ticket(self, ticket): ticket[3]["ticket_id"] = ticket[0] url = '%(url_protocol)s://%(url_domain)s%(url_path)s' % self.settings ticket[3]["ticket_url"] = "%s/ticket/%s" % (url, ticket[0]) res = """%(summary)s: * URL: %(ticket_url)s * [severity: %(severity)s] [owner: %(owner)s] [reporter: %(reporter)s] [status: %(status)s]""" % ticket[3] return res def dispatch(self, handler): self.logger.debug("TracPlugin dispatch") server = self.server d = self.timestamp self.timestamp = datetime.utcnow() res = [] for t in server.ticket.getRecentChanges(d): ticket = server.ticket.get(t) changes = server.ticket.changeLog(t) if len(changes) == 0 and 'new' in self.settings['status']: # No changes implies New ticket res.append(ticket) for c in changes: if ( c[0] > d and c[2] == 'status' and c[4] in self.settings['status'] ): res.append(ticket) if len(res) == 0: return res = list(map( self.pretty_ticket, res )) message = "\n".join(res) for room_id in self.settings["rooms"]: room_id = self.bot.get_real_room_id(room_id) self.bot.send_notice(room_id, message) def command(self, sender, room_id, body, handler): self.logger.debug("TracPlugin command") plugin_name = self.settings["name"] # TODO: This should be a decorator if self.bot.only_local_domain and not self.bot.is_local_user_id(sender): self.logger.warning( "TracPlugin %s plugin is not allowed for external sender (%s)" % (plugin_name, sender) ) return sender = sender.replace('@','') sender = sender.split(':')[0] command_list = body.split()[1:] if len(command_list) > 0 and command_list[0] == plugin_name: if command_list[1] == "create": summary = ' '.join(command_list[2:]) self.logger.debug( "TracPlugin command: %s(%s)" % ( "create", summary ) ) self.server.ticket.create( summary, "", {"cc": sender}, True ) def help(self, sender, room_id, handler): self.logger.debug("TracPlugin help") if self.bot.is_private_room(room_id, self.bot.get_user_id()): message = "%(name)s create This is the issue summary\n" % self.settings else: message = "%(username)s: %(name)s create This is the issue summary\n" % self.settings handler(room_id, message)
mit
wmvanvliet/mne-python
mne/beamformer/_dics.py
3
32914
"""Dynamic Imaging of Coherent Sources (DICS).""" # Authors: Marijn van Vliet <w.m.vanvliet@gmail.com> # Britta Westner <britta.wstnr@gmail.com> # Susanna Aro <susanna.aro@aalto.fi> # Roman Goj <roman.goj@gmail.com> # # License: BSD (3-clause) import numpy as np from ..channels import equalize_channels from ..io.pick import pick_info, pick_channels from ..utils import (logger, verbose, warn, _check_one_ch_type, _check_channels_spatial_filter, _check_rank, _check_option, _validate_type) from ..forward import _subject_from_forward from ..minimum_norm.inverse import combine_xyz, _check_reference, _check_depth from ..rank import compute_rank from ..source_estimate import _make_stc, _get_src_type from ..time_frequency import csd_fourier, csd_multitaper, csd_morlet from ._compute_beamformer import (_prepare_beamformer_input, _compute_beamformer, _check_src_type, Beamformer, _compute_power, _proj_whiten_data) @verbose def make_dics(info, forward, csd, reg=0.05, noise_csd=None, label=None, pick_ori=None, rank=None, weight_norm=None, reduce_rank=False, depth=1., real_filter=False, inversion='matrix', verbose=None): """Compute a Dynamic Imaging of Coherent Sources (DICS) spatial filter. This is a beamformer filter that can be used to estimate the source power at a specific frequency range :footcite:`GrossEtAl2001`. It does this by constructing a spatial filter for each source point. The computation of these filters is very similar to those of the LCMV beamformer (:func:`make_lcmv`), but instead of operating on a covariance matrix, the CSD matrix is used. When applying these filters to a CSD matrix (see :func:`apply_dics_csd`), the source power can be estimated for each source point. Parameters ---------- info : instance of Info Measurement info, e.g. ``epochs.info``. forward : instance of Forward Forward operator. csd : instance of CrossSpectralDensity The data cross-spectral density (CSD) matrices. A source estimate is performed for each frequency or frequency-bin defined in the CSD object. reg : float The regularization to apply to the cross-spectral density before computing the inverse. noise_csd : instance of CrossSpectralDensity | None Noise cross-spectral density (CSD) matrices. If provided, whitening will be done. The noise CSDs need to have been computed for the same frequencies as the data CSDs. Providing noise CSDs is mandatory if you mix sensor types, e.g. gradiometers with magnetometers or EEG with MEG. .. versionadded:: 0.20 label : Label | None Restricts the solution to a given label. %(bf_pick_ori)s %(rank_None)s .. versionadded:: 0.17 %(weight_norm)s Defaults to ``None``, in which case no normalization is performed. %(reduce_rank)s %(depth)s real_filter : bool If ``True``, take only the real part of the cross-spectral-density matrices to compute real filters. Defaults to ``False``. %(bf_inversion)s .. versionchanged:: 0.21 Default changed to ``'matrix'``. %(verbose)s Returns ------- filters : instance of Beamformer Dictionary containing filter weights from DICS beamformer. Contains the following keys: 'kind' : str The type of beamformer, in this case 'DICS'. 'weights' : ndarray, shape (n_frequencies, n_weights) For each frequency, the filter weights of the beamformer. 'csd' : instance of CrossSpectralDensity The data cross-spectral density matrices used to compute the beamformer. 'ch_names' : list of str Channels used to compute the beamformer. 'proj' : ndarray, shape (n_channels, n_channels) Projections used to compute the beamformer. 'vertices' : list of ndarray Vertices for which the filter weights were computed. 'n_sources' : int Number of source location for which the filter weight were computed. 'subject' : str The subject ID. 'pick-ori' : None | 'max-power' | 'normal' | 'vector' The orientation in which the beamformer filters were computed. 'inversion' : 'single' | 'matrix' Whether the spatial filters were computed for each dipole separately or jointly for all dipoles at each vertex using a matrix inversion. 'weight_norm' : None | 'unit-noise-gain' The normalization of the weights. 'src_type' : str Type of source space. 'is_free_ori' : bool Whether the filter was computed in a fixed direction (pick_ori='max-power', pick_ori='normal') or not. 'whitener' : None | ndarray, shape (n_channels, n_channels) Whitening matrix, provided if whitening was applied to the covariance matrix and leadfield during computation of the beamformer weights. 'max-power-ori' : ndarray, shape (n_sources, 3) | None When pick_ori='max-power', this fields contains the estimated direction of maximum power at each source location. See Also -------- apply_dics_csd, tf_dics Notes ----- The original reference is :footcite:`GrossEtAl2001`. See :footcite:`vanVlietEtAl2018` for a tutorial style paper on the topic. The DICS beamformer is very similar to the LCMV (:func:`make_lcmv`) beamformer and many of the parameters are shared. However, :func:`make_dics` and :func:`make_lcmv` currently have different defaults for these parameters, which were settled on separately through extensive practical use case testing (but not necessarily exhaustive parameter space searching), and it remains to be seen how functionally interchangeable they could be. The default setting reproduce the DICS beamformer as described in :footcite:`vanVlietEtAl2018`:: inversion='single', weight_norm=None, depth=1. To use the :func:`make_lcmv` defaults, use:: inversion='matrix', weight_norm='unit-noise-gain-invariant', depth=None For more information about ``real_filter``, see the supplemental information from :footcite:`HippEtAl2011`. References ---------- .. footbibliography:: """ # noqa: E501 rank = _check_rank(rank) _check_option('pick_ori', pick_ori, [None, 'normal', 'max-power']) _check_option('inversion', inversion, ['single', 'matrix']) _validate_type(weight_norm, (str, None), 'weight_norm') frequencies = [np.mean(freq_bin) for freq_bin in csd.frequencies] n_freqs = len(frequencies) _, _, allow_mismatch = _check_one_ch_type('dics', info, forward, csd, noise_csd) # remove bads so that equalize_channels only keeps all good info = pick_info(info, pick_channels(info['ch_names'], [], info['bads'])) info, forward, csd = equalize_channels([info, forward, csd]) csd, noise_csd = _prepare_noise_csd(csd, noise_csd, real_filter) depth = _check_depth(depth, 'depth_sparse') if inversion == 'single': depth['combine_xyz'] = False is_free_ori, info, proj, vertices, G, whitener, nn, orient_std = \ _prepare_beamformer_input( info, forward, label, pick_ori, noise_cov=noise_csd, rank=rank, pca=False, **depth) # Compute ranks csd_int_rank = [] if not allow_mismatch: noise_rank = compute_rank(noise_csd, info=info, rank=rank) for i in range(len(frequencies)): csd_rank = compute_rank(csd.get_data(index=i, as_cov=True), info=info, rank=rank) if not allow_mismatch: for key in csd_rank: if key not in noise_rank or csd_rank[key] != noise_rank[key]: raise ValueError('%s data rank (%s) did not match the ' 'noise rank (%s)' % (key, csd_rank[key], noise_rank.get(key, None))) csd_int_rank.append(sum(csd_rank.values())) del noise_csd ch_names = list(info['ch_names']) logger.info('Computing DICS spatial filters...') Ws = [] max_oris = [] for i, freq in enumerate(frequencies): if n_freqs > 1: logger.info(' computing DICS spatial filter at %sHz (%d/%d)' % (freq, i + 1, n_freqs)) Cm = csd.get_data(index=i) # XXX: Weird that real_filter happens *before* whitening, which could # make things complex again...? if real_filter: Cm = Cm.real # compute spatial filter n_orient = 3 if is_free_ori else 1 W, max_power_ori = _compute_beamformer( G, Cm, reg, n_orient, weight_norm, pick_ori, reduce_rank, rank=csd_int_rank[i], inversion=inversion, nn=nn, orient_std=orient_std, whitener=whitener) Ws.append(W) max_oris.append(max_power_ori) Ws = np.array(Ws) if pick_ori == 'max-power': max_oris = np.array(max_oris) else: max_oris = None src_type = _get_src_type(forward['src'], vertices) subject = _subject_from_forward(forward) is_free_ori = is_free_ori if pick_ori in [None, 'vector'] else False n_sources = np.sum([len(v) for v in vertices]) filters = Beamformer( kind='DICS', weights=Ws, csd=csd, ch_names=ch_names, proj=proj, vertices=vertices, n_sources=n_sources, subject=subject, pick_ori=pick_ori, inversion=inversion, weight_norm=weight_norm, src_type=src_type, is_free_ori=is_free_ori, whitener=whitener, max_power_ori=max_oris) return filters def _prepare_noise_csd(csd, noise_csd, real_filter): if noise_csd is not None: csd, noise_csd = equalize_channels([csd, noise_csd]) # Use the same noise CSD for all frequencies if len(noise_csd.frequencies) > 1: noise_csd = noise_csd.mean() noise_csd = noise_csd.get_data(as_cov=True) if real_filter: noise_csd['data'] = noise_csd['data'].real return csd, noise_csd def _apply_dics(data, filters, info, tmin): """Apply DICS spatial filter to data for source reconstruction.""" if isinstance(data, np.ndarray) and data.ndim == 2: data = [data] one_epoch = True else: one_epoch = False Ws = filters['weights'] one_freq = len(Ws) == 1 subject = filters['subject'] # compatibility with 0.16, add src_type as None if not present: filters, warn_text = _check_src_type(filters) for i, M in enumerate(data): if not one_epoch: logger.info("Processing epoch : %d" % (i + 1)) # Apply SSPs M = _proj_whiten_data(M, info['projs'], filters) stcs = [] for W in Ws: # project to source space using beamformer weights sol = np.dot(W, M) if filters['is_free_ori']: logger.info('combining the current components...') sol = combine_xyz(sol) tstep = 1.0 / info['sfreq'] stcs.append(_make_stc(sol, vertices=filters['vertices'], src_type=filters['src_type'], tmin=tmin, tstep=tstep, subject=subject, warn_text=warn_text)) if one_freq: yield stcs[0] else: yield stcs logger.info('[done]') @verbose def apply_dics(evoked, filters, verbose=None): """Apply Dynamic Imaging of Coherent Sources (DICS) beamformer weights. Apply Dynamic Imaging of Coherent Sources (DICS) beamformer weights on evoked data. .. warning:: The result of this function is meant as an intermediate step for further processing (such as computing connectivity). If you are interested in estimating source time courses, use an LCMV beamformer (:func:`make_lcmv`, :func:`apply_lcmv`) instead. If you are interested in estimating spectral power at the source level, use :func:`apply_dics_csd`. .. warning:: This implementation has not been heavily tested so please report any issues or suggestions. Parameters ---------- evoked : Evoked Evoked data to apply the DICS beamformer weights to. filters : instance of Beamformer DICS spatial filter (beamformer weights) Filter weights returned from :func:`make_dics`. %(verbose)s Returns ------- stc : SourceEstimate | VolSourceEstimate | list Source time courses. If the DICS beamformer has been computed for more than one frequency, a list is returned containing for each frequency the corresponding time courses. See Also -------- apply_dics_epochs apply_dics_csd """ # noqa: E501 _check_reference(evoked) info = evoked.info data = evoked.data tmin = evoked.times[0] sel = _check_channels_spatial_filter(evoked.ch_names, filters) data = data[sel] stc = _apply_dics(data=data, filters=filters, info=info, tmin=tmin) return next(stc) @verbose def apply_dics_epochs(epochs, filters, return_generator=False, verbose=None): """Apply Dynamic Imaging of Coherent Sources (DICS) beamformer weights. Apply Dynamic Imaging of Coherent Sources (DICS) beamformer weights on single trial data. .. warning:: The result of this function is meant as an intermediate step for further processing (such as computing connectivity). If you are interested in estimating source time courses, use an LCMV beamformer (:func:`make_lcmv`, :func:`apply_lcmv`) instead. If you are interested in estimating spectral power at the source level, use :func:`apply_dics_csd`. .. warning:: This implementation has not been heavily tested so please report any issue or suggestions. Parameters ---------- epochs : Epochs Single trial epochs. filters : instance of Beamformer DICS spatial filter (beamformer weights) Filter weights returned from :func:`make_dics`. The DICS filters must have been computed for a single frequency only. return_generator : bool Return a generator object instead of a list. This allows iterating over the stcs without having to keep them all in memory. %(verbose)s Returns ------- stc: list | generator of (SourceEstimate | VolSourceEstimate) The source estimates for all epochs. See Also -------- apply_dics apply_dics_csd """ _check_reference(epochs) if len(filters['weights']) > 1: raise ValueError( 'This function only works on DICS beamformer weights that have ' 'been computed for a single frequency. When calling make_dics(), ' 'make sure to use a CSD object with only a single frequency (or ' 'frequency-bin) defined.' ) info = epochs.info tmin = epochs.times[0] sel = _check_channels_spatial_filter(epochs.ch_names, filters) data = epochs.get_data()[:, sel, :] stcs = _apply_dics(data=data, filters=filters, info=info, tmin=tmin) if not return_generator: stcs = list(stcs) return stcs @verbose def apply_dics_csd(csd, filters, verbose=None): """Apply Dynamic Imaging of Coherent Sources (DICS) beamformer weights. Apply a previously computed DICS beamformer to a cross-spectral density (CSD) object to estimate source power in time and frequency windows specified in the CSD object :footcite:`GrossEtAl2001`. Parameters ---------- csd : instance of CrossSpectralDensity The data cross-spectral density (CSD) matrices. A source estimate is performed for each frequency or frequency-bin defined in the CSD object. filters : instance of Beamformer DICS spatial filter (beamformer weights) Filter weights returned from `make_dics`. %(verbose)s Returns ------- stc : SourceEstimate Source power with frequency instead of time. frequencies : list of float The frequencies for which the source power has been computed. If the data CSD object defines frequency-bins instead of exact frequencies, the mean of each bin is returned. References ---------- .. footbibliography:: """ # noqa: E501 ch_names = filters['ch_names'] vertices = filters['vertices'] n_orient = 3 if filters['is_free_ori'] else 1 subject = filters['subject'] whitener = filters['whitener'] n_sources = filters['n_sources'] # If CSD is summed over multiple frequencies, take the average frequency frequencies = [np.mean(dfreq) for dfreq in csd.frequencies] n_freqs = len(frequencies) source_power = np.zeros((n_sources, len(csd.frequencies))) # Ensure the CSD is in the same order as the weights csd_picks = [csd.ch_names.index(ch) for ch in ch_names] logger.info('Computing DICS source power...') for i, freq in enumerate(frequencies): if n_freqs > 1: logger.info(' applying DICS spatial filter at %sHz (%d/%d)' % (freq, i + 1, n_freqs)) Cm = csd.get_data(index=i) Cm = Cm[csd_picks, :][:, csd_picks] W = filters['weights'][i] # Whiten the CSD Cm = np.dot(whitener, np.dot(Cm, whitener.conj().T)) source_power[:, i] = _compute_power(Cm, W, n_orient) logger.info('[done]') # compatibility with 0.16, add src_type as None if not present: filters, warn_text = _check_src_type(filters) return (_make_stc(source_power, vertices=vertices, src_type=filters['src_type'], tmin=0., tstep=1., subject=subject, warn_text=warn_text), frequencies) @verbose def tf_dics(epochs, forward, noise_csds, tmin, tmax, tstep, win_lengths, subtract_evoked=False, mode='fourier', freq_bins=None, frequencies=None, n_ffts=None, mt_bandwidths=None, mt_adaptive=False, mt_low_bias=True, cwt_n_cycles=7, decim=1, reg=0.05, label=None, pick_ori=None, rank=None, inversion='single', weight_norm=None, depth=1., real_filter=False, reduce_rank=False, verbose=None): """5D time-frequency beamforming based on DICS. Calculate source power in time-frequency windows using a spatial filter based on the Dynamic Imaging of Coherent Sources (DICS) beamforming approach :footcite:`DalalEtAl2008`. For each time window and frequency bin combination, cross-spectral density (CSD) is computed and used to create a DICS beamformer spatial filter. Parameters ---------- epochs : Epochs Single trial epochs. forward : dict Forward operator. noise_csds : list of instances of CrossSpectralDensity | None Noise cross-spectral density for each frequency bin. If these are specified, the DICS filters will be applied to both the signal and noise CSDs. The source power estimates for each frequency bin will be scaled by the estimated noise power (signal / noise). Specifying ``None`` will disable performing noise normalization. tmin : float Minimum time instant to consider. tmax : float Maximum time instant to consider. tstep : float Spacing between consecutive time windows, should be smaller than or equal to the shortest time window length. win_lengths : list of float Time window lengths in seconds. One time window length should be provided for each frequency bin. subtract_evoked : bool If True, subtract the averaged evoked response prior to computing the tf source grid. Defaults to False. mode : 'fourier' | 'multitaper' | 'cwt_morlet' Spectrum estimation mode. Defaults to 'fourier'. freq_bins : list of tuple of float Start and end point of frequency bins of interest. Only used in 'multitaper' or 'fourier' mode. For 'cwt_morlet' mode, use the ``frequencies`` parameter instead. frequencies : list of float | list of list of float The frequencies to compute the source power for. If you want to compute the average power for multiple frequency bins, specify a list of lists: each list containing the frequencies for the corresponding bin. Only used in 'cwt_morlet' mode. In other modes, use the ``freq_bins`` parameter instead. n_ffts : list | None Length of the FFT for each frequency bin. If ``None`` (the default), the exact number of samples between ``tmin`` and ``tmax`` will be used. Only used in 'multitaper' or 'fourier' mode. mt_bandwidths : list of float The bandwidths of the multitaper windowing function in Hz. Only used in 'multitaper' mode. One value should be provided for each frequency bin. Defaults to None. mt_adaptive : bool Use adaptive weights to combine the tapered spectra into CSD. Only used in 'multitaper' mode. Defaults to False. mt_low_bias : bool Only use tapers with more than 90%% spectral concentration within bandwidth. Only used in 'multitaper' mode. Defaults to True. cwt_n_cycles : float | list of float | None Number of cycles to use when constructing Morlet wavelets. Fixed number or one per frequency. Defaults to 7. Only used in 'cwt_morlet' mode. decim : int | slice To reduce memory usage, decimation factor during time-frequency decomposition. Defaults to 1 (no decimation). Only used in 'cwt_morlet' mode. If `int`, uses tfr[..., ::decim]. If `slice`, uses tfr[..., decim]. reg : float Regularization to use for the DICS beamformer computation. Defaults to 0.05. label : Label | None Restricts the solution to a given label. Defaults to None. pick_ori : None | 'normal' | 'max-power' The source orientation to estimate source power for: ``None`` : orientations are pooled. (Default) 'normal' : filters are computed for the orientation tangential to the cortical surface 'max-power' : filters are computer for the orientation that maximizes spectral power. Defaults to ``None``. rank : None | int | 'full' This controls the effective rank of the covariance matrix when computing the inverse. The rank can be set explicitly by specifying an integer value. If ``None``, the rank will be automatically estimated. Since applying regularization will always make the covariance matrix full rank, the rank is estimated before regularization in this case. If 'full', the rank will be estimated after regularization and hence will mean using the full rank, unless ``reg=0`` is used. The default is None. .. versionadded:: 0.17 inversion : 'single' | 'matrix' This determines how the beamformer deals with source spaces in "free" orientation. Such source spaces define three orthogonal dipoles at each source point. When ``inversion='single'``, each dipole is considered as an individual source and the corresponding spatial filter is computed for each dipole separately. When ``inversion='matrix'``, all three dipoles at a source vertex are considered as a group and the spatial filters are computed jointly using a matrix inversion. While ``inversion='single'`` is more stable, ``inversion='matrix'`` is more precise. See Notes of :func:`make_dics`. Defaults to 'single'. weight_norm : None | 'unit-noise-gain' How to normalize the beamformer weights. None means no normalization is performed. If 'unit-noise-gain', the unit-noise gain minimum variance beamformer will be computed (Borgiotti-Kaplan beamformer) :footcite:`SekiharaNagarajan2008`. Defaults to ``None``. %(depth)s real_filter : bool If ``True``, take only the real part of the cross-spectral-density matrices to compute real filters. Defaults to ``False``. %(reduce_rank)s %(verbose)s Returns ------- stcs : list of SourceEstimate | VolSourceEstimate Source power at each time window. One SourceEstimate object is returned for each frequency bin. Notes ----- Dalal et al. :footcite:`DalalEtAl2008` used a synthetic aperture magnetometry beamformer (SAM) in each time-frequency window instead of DICS. An alternative to using noise CSDs is to normalize the forward solution (``depth``) or the beamformer weights (``weight_norm``). In this case, ``noise_csds`` may be set to ``None``. References ---------- .. footbibliography:: """ _check_reference(epochs) rank = _check_rank(rank) if mode == 'cwt_morlet' and frequencies is None: raise ValueError('In "cwt_morlet" mode, the "frequencies" parameter ' 'should be used.') elif mode != 'cwt_morlet' and freq_bins is None: raise ValueError('In "%s" mode, the "freq_bins" parameter should be ' 'used.' % mode) if frequencies is not None: # Make sure frequencies are always in the form of a list of lists frequencies = [np.atleast_1d(f) for f in frequencies] n_freq_bins = len(frequencies) else: n_freq_bins = len(freq_bins) if len(win_lengths) != n_freq_bins: raise ValueError('One time window length expected per frequency bin') if any(win_length < tstep for win_length in win_lengths): raise ValueError('Time step should not be larger than any of the ' 'window lengths') if noise_csds is not None and len(noise_csds) != n_freq_bins: raise ValueError('One noise CSD object expected per frequency bin') if n_ffts is not None and len(n_ffts) != n_freq_bins: raise ValueError('When specifying number of FFT samples, one value ' 'must be provided per frequency bin') if mt_bandwidths is not None and len(mt_bandwidths) != n_freq_bins: raise ValueError('When using multitaper mode and specifying ' 'multitaper transform bandwidth, one value must be ' 'provided per frequency bin') # Multiplying by 1e3 to avoid numerical issues, e.g. 0.3 // 0.05 == 5 n_time_steps = int(((tmax - tmin) * 1e3) // (tstep * 1e3)) # Subtract evoked response if subtract_evoked: epochs = epochs.copy().subtract_evoked() sol_final = [] # Compute source power for each frequency bin for i_freq in range(n_freq_bins): win_length = win_lengths[i_freq] n_overlap = int((win_length * 1e3) // (tstep * 1e3)) # Scale noise CSD to allow data and noise CSDs to have different length if noise_csds is not None: noise_csd = noise_csds[i_freq].copy() noise_csd._data /= noise_csd.n_fft if mode == 'cwt_morlet': freq_bin = frequencies[i_freq] fmin = np.min(freq_bin) fmax = np.max(freq_bin) else: fmin, fmax = freq_bins[i_freq] if n_ffts is None: n_fft = None else: n_fft = n_ffts[i_freq] if mt_bandwidths is None: mt_bandwidth = None else: mt_bandwidth = mt_bandwidths[i_freq] sol_single = [] sol_overlap = [] for i_time in range(n_time_steps): win_tmin = tmin + i_time * tstep win_tmax = win_tmin + win_length # If in the last step the last time point was not covered in # previous steps and will not be covered now, a solution needs to # be calculated for an additional time window if (i_time == n_time_steps - 1 and win_tmax - tstep < tmax and win_tmax >= tmax + (epochs.times[-1] - epochs.times[-2])): warn('Adding a time window to cover last time points') win_tmin = tmax - win_length win_tmax = tmax if win_tmax < tmax + (epochs.times[-1] - epochs.times[-2]): # Counteracts unsafe floating point arithmetic ensuring all # relevant samples will be taken into account when selecting # data in time windows logger.info( 'Computing time-frequency DICS beamformer for time ' 'window %d to %d ms, in frequency range %d to %d Hz' % (win_tmin * 1e3, win_tmax * 1e3, fmin, fmax) ) # Calculating data CSD in current time window if mode == 'fourier': csd = csd_fourier( epochs, fmin=fmin, fmax=fmax, tmin=win_tmin, tmax=win_tmax, n_fft=n_fft, verbose=False) elif mode == 'multitaper': csd = csd_multitaper( epochs, fmin=fmin, fmax=fmax, tmin=win_tmin, tmax=win_tmax, n_fft=n_fft, bandwidth=mt_bandwidth, low_bias=mt_low_bias, verbose=False) elif mode == 'cwt_morlet': csd = csd_morlet( epochs, frequencies=freq_bin, tmin=win_tmin, tmax=win_tmax, n_cycles=cwt_n_cycles, decim=decim, verbose=False) else: raise ValueError('Invalid mode, choose either ' "'fourier' or 'multitaper'") csd = csd.sum() # Scale data CSD to allow data and noise CSDs to have different # length csd._data /= csd.n_fft filters = make_dics(epochs.info, forward, csd, reg=reg, label=label, pick_ori=pick_ori, rank=rank, inversion=inversion, weight_norm=weight_norm, depth=depth, reduce_rank=reduce_rank, real_filter=real_filter, verbose=False) stc, _ = apply_dics_csd(csd, filters, verbose=False) if noise_csds is not None: # Scale signal power by noise power noise_stc, _ = apply_dics_csd(noise_csd, filters, verbose=False) stc /= noise_stc sol_single.append(stc.data[:, 0]) # Average over all time windows that contain the current time # point, which is the current time window along with # n_overlap - 1 previous ones if i_time - n_overlap < 0: curr_sol = np.mean(sol_single[0:i_time + 1], axis=0) else: curr_sol = np.mean(sol_single[i_time - n_overlap + 1: i_time + 1], axis=0) # The final result for the current time point in the current # frequency bin sol_overlap.append(curr_sol) # Gathering solutions for all time points for current frequency bin sol_final.append(sol_overlap) sol_final = np.array(sol_final) # Creating stc objects containing all time points for each frequency bin stcs = [] # compatibility with 0.16, add src_type as None if not present: filters, warn_text = _check_src_type(filters) for i_freq in range(n_freq_bins): stc = _make_stc(sol_final[i_freq, :, :].T, vertices=stc.vertices, src_type=filters['src_type'], tmin=tmin, tstep=tstep, subject=stc.subject, warn_text=warn_text) stcs.append(stc) return stcs
bsd-3-clause
s20121035/rk3288_android5.1_repo
external/chromium_org/tools/memory_inspector/memory_inspector/classification/native_heap_classifier.py
89
8377
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """This module classifies NativeHeap objects filtering their allocations. The only filter currently available is 'stacktrace', which works as follows: {'name': 'rule-1', 'stacktrace': 'foo' } {'name': 'rule-2', 'stacktrace': ['foo', r'bar\s+baz']} {'name': 'rule-3', 'source_path': 'sk.*allocator'} {'name': 'rule-3', 'source_path': 'sk', 'stacktrace': 'SkAllocator'} rule-1 will match any allocation that has 'foo' in one of its stack frames. rule-2 will match any allocation that has a stack frame matching 'foo' AND a followed by a stack frame matching 'bar baz'. Note that order matters, so rule-2 will not match a stacktrace like ['bar baz', 'foo']. rule-3 will match any allocation in which at least one of the source paths in its stack frames matches the regex sk.*allocator. rule-4 will match any allocation which satisfies both the conditions. TODO(primiano): introduce more filters after the first prototype with UI, for instance, filter by library file name or by allocation size. """ import collections import posixpath import re from memory_inspector.classification import results from memory_inspector.classification import rules from memory_inspector.core import exceptions from memory_inspector.core import native_heap _RESULT_KEYS = ['bytes_allocated', 'bytes_resident'] def LoadRules(content): """Loads and parses a native-heap rule tree from a content (string). Returns: An instance of |rules.Rule|, which nodes are |_NHeapRule| instances. """ return rules.Load(content, _NHeapRule) def Classify(nativeheap, rule_tree): """Creates aggregated results of native heaps using the provided rules. Args: nativeheap: the heap dump being processed (a |NativeHeap| instance). rule_tree: the user-defined rules that define the filtering categories. Returns: An instance of |AggreatedResults|. """ assert(isinstance(nativeheap, native_heap.NativeHeap)) assert(isinstance(rule_tree, rules.Rule)) res = results.AggreatedResults(rule_tree, _RESULT_KEYS) for allocation in nativeheap.allocations: res.AddToMatchingNodes(allocation, [allocation.size, allocation.resident_size]) return res def InferHeuristicRulesFromHeap(nheap, max_depth=3, threshold=0.02): """Infers the rules tree from a symbolized heap snapshot. In lack of a specific set of rules, this method can be invoked to infer a meaningful rule tree starting from a heap snapshot. It will build a compact radix tree from the source paths of the stack traces, which height is at most |max_depth|, selecting only those nodes which contribute for at least |threshold| (1.0 = 100%) w.r.t. the total allocation of the heap snapshot. """ assert(isinstance(nheap, native_heap.NativeHeap)) def RadixTreeInsert(node, path): """Inserts a string (path) into a radix tree (a python recursive dict). e.g.: [/a/b/c, /a/b/d, /z/h] -> {'/a/b/': {'c': {}, 'd': {}}, '/z/h': {}} """ def GetCommonPrefix(args): """Returns the common prefix between two paths (no partial paths). e.g.: /tmp/bar, /tmp/baz will return /tmp/ (and not /tmp/ba as the dumb posixpath.commonprefix implementation would do) """ parts = posixpath.commonprefix(args).rpartition(posixpath.sep)[0] return parts + posixpath.sep if parts else '' for node_path in node.iterkeys(): pfx = GetCommonPrefix([node_path, path]) if not pfx: continue if len(pfx) < len(node_path): node[pfx] = {node_path[len(pfx):] : node[node_path]} del node[node_path] if len(path) > len(pfx): RadixTreeInsert(node[pfx], path[len(pfx):]) return node[path] = {} # No common prefix, create new child in current node. # Given an allocation of size N and its stack trace, heuristically determines # the source directory to be blamed for the N bytes. # The blamed_dir is the one which appears more times in the top 8 stack frames # (excluding the first 2, which usually are just the (m|c)alloc call sites). # At the end, this will generate a *leaderboard* (|blamed_dirs|) which # associates, to each source path directory, the number of bytes allocated. blamed_dirs = collections.Counter() # '/s/path' : bytes_from_this_path (int) total_allocated = 0 for alloc in nheap.allocations: dir_histogram = collections.Counter() for frame in alloc.stack_trace.frames[2:10]: # Compute a histogram (for each allocation) of the top source dirs. if not frame.symbol or not frame.symbol.source_info: continue src_file = frame.symbol.source_info[0].source_file_path src_dir = posixpath.dirname(src_file.replace('\\', '/')) + '/' dir_histogram.update([src_dir]) if not dir_histogram: continue # Add the blamed dir to the leaderboard. blamed_dir = dir_histogram.most_common()[0][0] blamed_dirs.update({blamed_dir : alloc.size}) total_allocated += alloc.size # Select only the top paths from the leaderboard which contribute for more # than |threshold| and make a radix tree out of them. radix_tree = {} for blamed_dir, alloc_size in blamed_dirs.most_common(): if (1.0 * alloc_size / total_allocated) < threshold: break RadixTreeInsert(radix_tree, blamed_dir) # The final step consists in generating a rule tree from the radix tree. This # is a pretty straightforward tree-clone operation, they have the same shape. def GenRulesFromRadixTree(radix_tree_node, max_depth, parent_path=''): children = [] if max_depth > 0: for node_path, node_children in radix_tree_node.iteritems(): child_rule = { 'name': node_path[-16:], 'source_path': '^' + re.escape(parent_path + node_path), 'children': GenRulesFromRadixTree( node_children, max_depth - 1, parent_path + node_path)} children += [child_rule] return children rules_tree = GenRulesFromRadixTree(radix_tree, max_depth) return LoadRules(str(rules_tree)) class _NHeapRule(rules.Rule): def __init__(self, name, filters): super(_NHeapRule, self).__init__(name) # The 'stacktrace' filter can be either a string (simple case, one regex) or # a list of strings (complex case, see doc in the header of this file). stacktrace_regexs = filters.get('stacktrace', []) if isinstance(stacktrace_regexs, basestring): stacktrace_regexs = [stacktrace_regexs] self._stacktrace_regexs = [] for regex in stacktrace_regexs: try: self._stacktrace_regexs.append(re.compile(regex)) except re.error, descr: raise exceptions.MemoryInspectorException( 'Stacktrace regex error "%s" : %s' % (regex, descr)) # The 'source_path' regex, instead, simply matches the source file path. self._path_regex = None path_regex = filters.get('source_path') if path_regex: try: self._path_regex = re.compile(path_regex) except re.error, descr: raise exceptions.MemoryInspectorException( 'Path regex error "%s" : %s' % (path_regex, descr)) def Match(self, allocation): # Match the source file path, if the 'source_path' filter is specified. if self._path_regex: path_matches = False for frame in allocation.stack_trace.frames: if frame.symbol and frame.symbol.source_info: if self._path_regex.search( frame.symbol.source_info[0].source_file_path): path_matches = True break if not path_matches: return False # Match the stack traces symbols, if the 'stacktrace' filter is specified. if not self._stacktrace_regexs: return True cur_regex_idx = 0 cur_regex = self._stacktrace_regexs[0] for frame in allocation.stack_trace.frames: if frame.symbol and cur_regex.search(frame.symbol.name): # The current regex has been matched. if cur_regex_idx == len(self._stacktrace_regexs) - 1: return True # All the provided regexs have been matched, we're happy. cur_regex_idx += 1 cur_regex = self._stacktrace_regexs[cur_regex_idx] return False # Not all the provided regexs have been matched.
gpl-3.0
GRArmstrong/invenio-inspire-ops
modules/bibedit/lib/bibedit_dblayer.py
12
7628
## This file is part of Invenio. ## Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. # pylint: disable=C0103 """BibEdit Database Layer.""" __revision__ = "$Id$" try: import cPickle as Pickle except ImportError: import Pickle import zlib from datetime import datetime, timedelta from invenio.dbquery import run_sql from invenio.config import CFG_BIBEDIT_TIMEOUT def get_name_tags_all(): """Return a dictionary of all MARC tag's textual names.""" result = run_sql("SELECT name, value FROM tag") # Collect names in a dictionary with field codes as keys. nametags = {} for el in result: nametags[el[1]] = el[0] return nametags def get_bibupload_task_opts(task_ids): """Return a list with all set options for list of task IDs TASK_IDS.""" res = [] for task_id in task_ids: res.append(run_sql("SELECT arguments FROM schTASK WHERE id=%s", (task_id, ))) return res def get_marcxml_of_record_revision(recid, job_date): """Return MARCXML string of record revision specified by RECID and JOB_DATE. """ return run_sql("""SELECT marcxml FROM hstRECORD WHERE id_bibrec=%s AND job_date=%s""", (recid, job_date)) def get_info_of_record_revision(recid, job_date): """Return info string regarding record revision specified by RECID and JOB_DATE. """ return run_sql("""SELECT job_id, job_person, job_details FROM hstRECORD WHERE id_bibrec=%s AND job_date=%s""", (recid, job_date)) def get_record_revisions(recid): """Return dates for all known revisions of record RECID. returns a list of tuples (record_id, revision_date) """ return run_sql("""SELECT id_bibrec, DATE_FORMAT(job_date, '%%Y%%m%%d%%H%%i%%s') FROM hstRECORD WHERE id_bibrec=%s ORDER BY job_date DESC""", (recid, )) def get_record_last_modification_date(recid): """Return last modification date, as timetuple, of record RECID.""" sql_res = run_sql('SELECT max(job_date) FROM hstRECORD WHERE id_bibrec=%s', (recid, )) if sql_res[0][0] is None: return None else: return sql_res[0][0].timetuple() def reserve_record_id(): """Reserve a new record ID in the bibrec table.""" return run_sql("""INSERT INTO bibrec (creation_date, modification_date) VALUES (NOW(), NOW())""") def get_related_hp_changesets(recId): """ A function returning the changesets saved in the Holding Pen, related to the given record. """ return run_sql("""SELECT changeset_id, changeset_date FROM bibHOLDINGPEN WHERE id_bibrec=%s ORDER BY changeset_date""", (recId, )) def get_hp_update_xml(changeId): """ Get the MARC XML of the Holding Pen update """ res = run_sql("""SELECT changeset_xml, id_bibrec from bibHOLDINGPEN WHERE changeset_id=%s""", (changeId,)) if res: try: changeset_xml = zlib.decompress(res[0][0]) return changeset_xml, res[0][1] except zlib.error: # Legacy: the xml can be in TEXT format, leave it unchanged pass return res[0] def delete_hp_change(changeId): """ Delete a change of a given number """ return run_sql("""DELETE from bibHOLDINGPEN where changeset_id=%s""", (str(changeId), )) def delete_related_holdingpen_changes(recId): """ A function removing all the Holding Pen changes related to a given record """ return run_sql("""DELETE FROM bibHOLDINGPEN WHERE id_bibrec=%s""", (recId, )) def get_record_revision_author(recid, td): """ Returns the author of a specific record revision """ # obtaining job date from the recvision identifier datestring = "%04i-%02i-%02i %02i:%02i:%02i" % (td.tm_year, td.tm_mon, td.tm_mday, td.tm_hour, td.tm_min, td.tm_sec) result = run_sql("""SELECT job_person from hstRECORD where id_bibrec=%s AND job_date=%s""", (recid, datestring)) if result != (): return result[0] else: return "" # Cache Related functions def cache_exists(recid, uid): """Check if the BibEdit cache file exists.""" r = run_sql("""SELECT 1 FROM bibEDITCACHE WHERE id_bibrec = %s AND uid = %s""", (recid, uid)) return bool(r) def cache_active(recid, uid): """Check if the BibEdit cache is active (an editor is opened).""" r = run_sql("""SELECT 1 FROM bibEDITCACHE WHERE id_bibrec = %s AND uid = %s AND is_active = 1""", (recid, uid)) return bool(r) def deactivate_cache(recid, uid): """Mark BibEdit cache as non active.""" return run_sql("""UPDATE bibEDITCACHE SET is_active = 0 WHERE id_bibrec = %s AND uid = %s""", (recid, uid)) def update_cache_post_date(recid, uid): """Touch a BibEdit cache file. This should be used to indicate that the user has again accessed the record, so that locking will work correctly. """ run_sql("""UPDATE bibEDITCACHE SET post_date = NOW(), is_active = 1 WHERE id_bibrec = %s AND uid = %s""", (recid, uid)) def get_cache(recid, uid): """Return a BibEdit cache object from the database.""" r = run_sql("""SELECT data FROM bibEDITCACHE WHERE id_bibrec = %s AND uid = %s""", (recid, uid)) if r: return Pickle.loads(r[0][0]) def update_cache(recid, uid, data): data_str = Pickle.dumps(data) r = run_sql("""INSERT INTO bibEDITCACHE (id_bibrec, uid, data, post_date) VALUES (%s, %s, %s, NOW()) ON DUPLICATE KEY UPDATE data = %s, post_date = NOW(), is_active = 1""", (recid, uid, data_str, data_str)) def get_cache_post_date(recid, uid): r = run_sql("""SELECT post_date FROM bibEDITCACHE WHERE id_bibrec = %s AND uid = %s""", (recid, uid)) if r: return r[0][0] def delete_cache(recid, uid): run_sql("""DELETE FROM bibEDITCACHE WHERE id_bibrec = %s AND uid = %s""", (recid, uid)) def uids_with_active_caches(recid): """Return list of uids with active caches for record RECID. Active caches are caches that have been modified a number of seconds ago that is less than the one given by CFG_BIBEDIT_TIMEOUT. """ datecut = datetime.now() - timedelta(seconds=CFG_BIBEDIT_TIMEOUT) rows = run_sql("""SELECT uid FROM bibEDITCACHE WHERE id_bibrec = %s AND post_date > %s""", (recid, datecut)) return [int(row[0]) for row in rows] # End of cache related functions
gpl-2.0
mpeuster/estate
experiments/scaleability-dynamic/pox/tests/unit/lib/ioworker/io_worker_test.py
45
4338
#!/usr/bin/env python # # Copyright 2011-2012 Andreas Wundsam # Copyright 2011-2012 Colin Scott # Copyright 2011-2013 James McCauley # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import itertools import os.path import sys import unittest sys.path.append(os.path.join(os.path.dirname(__file__), *itertools.repeat("..", 3))) from pox.lib.mock_socket import MockSocket from pox.lib.ioworker import IOWorker, RecocoIOLoop from nose.tools import eq_ class IOWorkerTest(unittest.TestCase): def test_basic_send(self): i = IOWorker() i.send("foo") self.assertTrue(i._ready_to_send) self.assertEqual(i.send_buf, "foo") i._consume_send_buf(3) self.assertFalse(i._ready_to_send) def test_basic_receive(self): i = IOWorker() self.data = None def d(worker): self.data = worker.peek() i.rx_handler = d i._push_receive_data("bar") self.assertEqual(self.data, "bar") # d does not consume the data i._push_receive_data("hepp") self.assertEqual(self.data, "barhepp") def test_receive_consume(self): i = IOWorker() self.data = None def consume(worker): self.data = worker.peek() worker.consume_receive_buf(len(self.data)) i.rx_handler = consume i._push_receive_data("bar") self.assertEqual(self.data, "bar") # data has been consumed i._push_receive_data("hepp") self.assertEqual(self.data, "hepp") class RecocoIOLoopTest(unittest.TestCase): def test_basic(self): loop = RecocoIOLoop() (left, right) = MockSocket.pair() loop.new_worker(left) def test_stop(self): loop = RecocoIOLoop() loop.stop() def test_run_read(self): loop = RecocoIOLoop() (left, right) = MockSocket.pair() worker = loop.new_worker(left) # callback for ioworker to record receiving self.received = None def r(worker): self.received = worker.peek() worker.rx_handler = r # 'start' the run (dark generator magic here). # Does not actually execute run, but 'yield' a generator g = loop.run() # g.next() will call it, and get as far as the 'yield select' select = g.next() # send data on other socket half right.send("hallo") # now we emulate the return value of the select ([rlist],[wlist], [elist]) g.send(([worker], [], [])) # that should result in the socket being red the data being handed # to the ioworker, the callback being called. Everybody happy. self.assertEquals(self.received, "hallo") def test_run_close(self): loop = RecocoIOLoop() (left, right) = MockSocket.pair() worker = loop.new_worker(left) self.assertFalse(worker in loop._workers, "Should not add to _workers yet, until we start up the loop") self.assertTrue(len(loop._pending_commands) == 1, "Should have added pending create() command") worker.close() # This causes the worker to be scheduled to be closed -- it also # calls pinger.ping(). However, the Select task won't receive the ping # Until after this method has completed! Thus, we only test whether # worker has been added to the pending close queue self.assertTrue(len(loop._pending_commands) == 2, "Should have added pending close() command") def test_run_write(self): loop = RecocoIOLoop() (left, right) = MockSocket.pair() worker = loop.new_worker(left) worker.send("heppo") # 'start' the run (dark generator magic here). # Does not actually execute run, but 'yield' a generator g = loop.run() # g.next() will call it, and get as far as the 'yield select' select = g.next() # now we emulate the return value of the select ([rlist],[wlist], [elist]) g.send(([], [worker], [])) # that should result in the stuff being sent on the socket self.assertEqual(right.recv(), "heppo")
apache-2.0
isrohutamahopetechnik/MissionPlanner
Lib/site-packages/numpy/matrixlib/tests/test_regression.py
54
1035
from numpy.testing import * import numpy as np rlevel = 1 class TestRegression(TestCase): def test_kron_matrix(self,level=rlevel): """Ticket #71""" x = np.matrix('[1 0; 1 0]') assert_equal(type(np.kron(x,x)),type(x)) def test_matrix_properties(self,level=rlevel): """Ticket #125""" a = np.matrix([1.0],dtype=float) assert(type(a.real) is np.matrix) assert(type(a.imag) is np.matrix) c,d = np.matrix([0.0]).nonzero() assert(type(c) is np.matrix) assert(type(d) is np.matrix) def test_matrix_multiply_by_1d_vector(self, level=rlevel) : """Ticket #473""" def mul() : np.mat(np.eye(2))*np.ones(2) self.assertRaises(ValueError,mul) def test_matrix_std_argmax(self,level=rlevel): """Ticket #83""" x = np.asmatrix(np.random.uniform(0,1,(3,3))) self.assertEqual(x.std().shape, ()) self.assertEqual(x.argmax().shape, ()) if __name__ == "__main__": run_module_suite()
gpl-3.0
kevinr/750book-web
750book-web-env/lib/python2.7/site-packages/django/contrib/gis/db/models/proxy.py
404
2512
""" The GeometryProxy object, allows for lazy-geometries. The proxy uses Python descriptors for instantiating and setting Geometry objects corresponding to geographic model fields. Thanks to Robert Coup for providing this functionality (see #4322). """ class GeometryProxy(object): def __init__(self, klass, field): """ Proxy initializes on the given Geometry class (not an instance) and the GeometryField. """ self._field = field self._klass = klass def __get__(self, obj, type=None): """ This accessor retrieves the geometry, initializing it using the geometry class specified during initialization and the HEXEWKB value of the field. Currently, only GEOS or OGR geometries are supported. """ if obj is None: # Accessed on a class, not an instance return self # Getting the value of the field. geom_value = obj.__dict__[self._field.attname] if isinstance(geom_value, self._klass): geom = geom_value elif (geom_value is None) or (geom_value==''): geom = None else: # Otherwise, a Geometry object is built using the field's contents, # and the model's corresponding attribute is set. geom = self._klass(geom_value) setattr(obj, self._field.attname, geom) return geom def __set__(self, obj, value): """ This accessor sets the proxied geometry with the geometry class specified during initialization. Values of None, HEXEWKB, or WKT may be used to set the geometry as well. """ # The OGC Geometry type of the field. gtype = self._field.geom_type # The geometry type must match that of the field -- unless the # general GeometryField is used. if isinstance(value, self._klass) and (str(value.geom_type).upper() == gtype or gtype == 'GEOMETRY'): # Assigning the SRID to the geometry. if value.srid is None: value.srid = self._field.srid elif value is None or isinstance(value, (basestring, buffer)): # Set with None, WKT, HEX, or WKB pass else: raise TypeError('cannot set %s GeometryProxy with value of type: %s' % (obj.__class__.__name__, type(value))) # Setting the objects dictionary with the value, and returning. obj.__dict__[self._field.attname] = value return value
mit
Dunkas12/BeepBoopBot
lib/youtube_dl/extractor/abcnews.py
14
5019
# coding: utf-8 from __future__ import unicode_literals import calendar import re import time from .amp import AMPIE from .common import InfoExtractor from ..compat import compat_urlparse class AbcNewsVideoIE(AMPIE): IE_NAME = 'abcnews:video' _VALID_URL = r'https?://abcnews\.go\.com/[^/]+/video/(?P<display_id>[0-9a-z-]+)-(?P<id>\d+)' _TESTS = [{ 'url': 'http://abcnews.go.com/ThisWeek/video/week-exclusive-irans-foreign-minister-zarif-20411932', 'info_dict': { 'id': '20411932', 'ext': 'mp4', 'display_id': 'week-exclusive-irans-foreign-minister-zarif', 'title': '\'This Week\' Exclusive: Iran\'s Foreign Minister Zarif', 'description': 'George Stephanopoulos goes one-on-one with Iranian Foreign Minister Dr. Javad Zarif.', 'duration': 180, 'thumbnail': r're:^https?://.*\.jpg$', }, 'params': { # m3u8 download 'skip_download': True, }, }, { 'url': 'http://abcnews.go.com/2020/video/2020-husband-stands-teacher-jail-student-affairs-26119478', 'only_matching': True, }] def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) display_id = mobj.group('display_id') video_id = mobj.group('id') info_dict = self._extract_feed_info( 'http://abcnews.go.com/video/itemfeed?id=%s' % video_id) info_dict.update({ 'id': video_id, 'display_id': display_id, }) return info_dict class AbcNewsIE(InfoExtractor): IE_NAME = 'abcnews' _VALID_URL = r'https?://abcnews\.go\.com/(?:[^/]+/)+(?P<display_id>[0-9a-z-]+)/story\?id=(?P<id>\d+)' _TESTS = [{ 'url': 'http://abcnews.go.com/Blotter/News/dramatic-video-rare-death-job-america/story?id=10498713#.UIhwosWHLjY', 'info_dict': { 'id': '10498713', 'ext': 'flv', 'display_id': 'dramatic-video-rare-death-job-america', 'title': 'Occupational Hazards', 'description': 'Nightline investigates the dangers that lurk at various jobs.', 'thumbnail': r're:^https?://.*\.jpg$', 'upload_date': '20100428', 'timestamp': 1272412800, }, 'add_ie': ['AbcNewsVideo'], }, { 'url': 'http://abcnews.go.com/Entertainment/justin-timberlake-performs-stop-feeling-eurovision-2016/story?id=39125818', 'info_dict': { 'id': '39125818', 'ext': 'mp4', 'display_id': 'justin-timberlake-performs-stop-feeling-eurovision-2016', 'title': 'Justin Timberlake Drops Hints For Secret Single', 'description': 'Lara Spencer reports the buzziest stories of the day in "GMA" Pop News.', 'upload_date': '20160515', 'timestamp': 1463329500, }, 'params': { # m3u8 download 'skip_download': True, # The embedded YouTube video is blocked due to copyright issues 'playlist_items': '1', }, 'add_ie': ['AbcNewsVideo'], }, { 'url': 'http://abcnews.go.com/Technology/exclusive-apple-ceo-tim-cook-iphone-cracking-software/story?id=37173343', 'only_matching': True, }] def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) display_id = mobj.group('display_id') video_id = mobj.group('id') webpage = self._download_webpage(url, video_id) video_url = self._search_regex( r'window\.abcnvideo\.url\s*=\s*"([^"]+)"', webpage, 'video URL') full_video_url = compat_urlparse.urljoin(url, video_url) youtube_url = self._html_search_regex( r'<iframe[^>]+src="(https://www\.youtube\.com/embed/[^"]+)"', webpage, 'YouTube URL', default=None) timestamp = None date_str = self._html_search_regex( r'<span[^>]+class="timestamp">([^<]+)</span>', webpage, 'timestamp', fatal=False) if date_str: tz_offset = 0 if date_str.endswith(' ET'): # Eastern Time tz_offset = -5 date_str = date_str[:-3] date_formats = ['%b. %d, %Y', '%b %d, %Y, %I:%M %p'] for date_format in date_formats: try: timestamp = calendar.timegm(time.strptime(date_str.strip(), date_format)) except ValueError: continue if timestamp is not None: timestamp -= tz_offset * 3600 entry = { '_type': 'url_transparent', 'ie_key': AbcNewsVideoIE.ie_key(), 'url': full_video_url, 'id': video_id, 'display_id': display_id, 'timestamp': timestamp, } if youtube_url: entries = [entry, self.url_result(youtube_url, 'Youtube')] return self.playlist_result(entries) return entry
gpl-3.0
vmindru/ansible
lib/ansible/modules/packaging/language/composer.py
86
9536
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2014, Dimitrios Tydeas Mengidis <tydeas.dr@gmail.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 = ''' --- module: composer author: - "Dimitrios Tydeas Mengidis (@dmtrs)" - "René Moser (@resmo)" short_description: Dependency Manager for PHP version_added: "1.6" description: - > Composer is a tool for dependency management in PHP. It allows you to declare the dependent libraries your project needs and it will install them in your project for you. options: command: version_added: "1.8" description: - Composer command like "install", "update" and so on. default: install arguments: version_added: "2.0" description: - Composer arguments like required package, version and so on. executable: version_added: "2.4" description: - Path to PHP Executable on the remote host, if PHP is not in PATH. aliases: [ php_path ] working_dir: description: - Directory of your project (see --working-dir). This is required when the command is not run globally. - Will be ignored if C(global_command=true). aliases: [ working-dir ] global_command: version_added: "2.4" description: - Runs the specified command globally. type: bool default: false aliases: [ global-command ] prefer_source: description: - Forces installation from package sources when possible (see --prefer-source). default: false type: bool aliases: [ prefer-source ] prefer_dist: description: - Forces installation from package dist even for dev versions (see --prefer-dist). default: false type: bool aliases: [ prefer-dist ] no_dev: description: - Disables installation of require-dev packages (see --no-dev). default: true type: bool aliases: [ no-dev ] no_scripts: description: - Skips the execution of all scripts defined in composer.json (see --no-scripts). default: false type: bool aliases: [ no-scripts ] no_plugins: description: - Disables all plugins ( see --no-plugins ). default: false type: bool aliases: [ no-plugins ] optimize_autoloader: description: - Optimize autoloader during autoloader dump (see --optimize-autoloader). - Convert PSR-0/4 autoloading to classmap to get a faster autoloader. - Recommended especially for production, but can take a bit of time to run. default: true type: bool aliases: [ optimize-autoloader ] classmap_authoritative: version_added: "2.7" description: - Autoload classes from classmap only. - Implicitely enable optimize_autoloader. - Recommended especially for production, but can take a bit of time to run. default: false type: bool aliases: [ classmap-authoritative ] apcu_autoloader: version_added: "2.7" description: - Uses APCu to cache found/not-found classes default: false type: bool aliases: [ apcu-autoloader ] ignore_platform_reqs: version_added: "2.0" description: - Ignore php, hhvm, lib-* and ext-* requirements and force the installation even if the local machine does not fulfill these. default: false type: bool aliases: [ ignore-platform-reqs ] requirements: - php - composer installed in bin path (recommended /usr/local/bin) notes: - Default options that are always appended in each execution are --no-ansi, --no-interaction and --no-progress if available. - We received reports about issues on macOS if composer was installed by Homebrew. Please use the official install method to avoid issues. ''' EXAMPLES = ''' # Downloads and installs all the libs and dependencies outlined in the /path/to/project/composer.lock - composer: command: install working_dir: /path/to/project - composer: command: require arguments: my/package working_dir: /path/to/project # Clone project and install with all dependencies - composer: command: create-project arguments: package/package /path/to/project ~1.0 working_dir: /path/to/project prefer_dist: yes # Installs package globally - composer: command: require global_command: yes arguments: my/package ''' import re from ansible.module_utils.basic import AnsibleModule def parse_out(string): return re.sub(r"\s+", " ", string).strip() def has_changed(string): return "Nothing to install or update" not in string def get_available_options(module, command='install'): # get all available options from a composer command using composer help to json rc, out, err = composer_command(module, "help %s --format=json" % command) if rc != 0: output = parse_out(err) module.fail_json(msg=output) command_help_json = module.from_json(out) return command_help_json['definition']['options'] def composer_command(module, command, arguments="", options=None, global_command=False): if options is None: options = [] if module.params['executable'] is None: php_path = module.get_bin_path("php", True, ["/usr/local/bin"]) else: php_path = module.params['executable'] composer_path = module.get_bin_path("composer", True, ["/usr/local/bin"]) cmd = "%s %s %s %s %s %s" % (php_path, composer_path, "global" if global_command else "", command, " ".join(options), arguments) return module.run_command(cmd) def main(): module = AnsibleModule( argument_spec=dict( command=dict(default="install", type="str"), arguments=dict(default="", type="str"), executable=dict(type="path", aliases=["php_path"]), working_dir=dict(type="path", aliases=["working-dir"]), global_command=dict(default=False, type="bool", aliases=["global-command"]), prefer_source=dict(default=False, type="bool", aliases=["prefer-source"]), prefer_dist=dict(default=False, type="bool", aliases=["prefer-dist"]), no_dev=dict(default=True, type="bool", aliases=["no-dev"]), no_scripts=dict(default=False, type="bool", aliases=["no-scripts"]), no_plugins=dict(default=False, type="bool", aliases=["no-plugins"]), apcu_autoloader=dict(default=False, type="bool", aliases=["apcu-autoloader"]), optimize_autoloader=dict(default=True, type="bool", aliases=["optimize-autoloader"]), classmap_authoritative=dict(default=False, type="bool", aliases=["classmap-authoritative"]), ignore_platform_reqs=dict(default=False, type="bool", aliases=["ignore-platform-reqs"]), ), required_if=[('global_command', False, ['working_dir'])], supports_check_mode=True ) # Get composer command with fallback to default command = module.params['command'] if re.search(r"\s", command): module.fail_json(msg="Use the 'arguments' param for passing arguments with the 'command'") arguments = module.params['arguments'] global_command = module.params['global_command'] available_options = get_available_options(module=module, command=command) options = [] # Default options default_options = [ 'no-ansi', 'no-interaction', 'no-progress', ] for option in default_options: if option in available_options: option = "--%s" % option options.append(option) if not global_command: options.extend(['--working-dir', "'%s'" % module.params['working_dir']]) option_params = { 'prefer_source': 'prefer-source', 'prefer_dist': 'prefer-dist', 'no_dev': 'no-dev', 'no_scripts': 'no-scripts', 'no_plugins': 'no-plugins', 'apcu_autoloader': 'acpu-autoloader', 'optimize_autoloader': 'optimize-autoloader', 'classmap_authoritative': 'classmap-authoritative', 'ignore_platform_reqs': 'ignore-platform-reqs', } for param, option in option_params.items(): if module.params.get(param) and option in available_options: option = "--%s" % option options.append(option) if module.check_mode: if 'dry-run' in available_options: options.append('--dry-run') else: module.exit_json(skipped=True, msg="command '%s' does not support check mode, skipping" % command) rc, out, err = composer_command(module, command, arguments, options, global_command) if rc != 0: output = parse_out(err) module.fail_json(msg=output, stdout=err) else: # Composer version > 1.0.0-alpha9 now use stderr for standard notification messages output = parse_out(out + err) module.exit_json(changed=has_changed(output), msg=output, stdout=out + err) if __name__ == '__main__': main()
gpl-3.0
pdeesawat/PSIT58_test_01
Test_Python_code/final_code/Indonesia/Indo_Flood.py
1
1312
data = open('Real_Final_database_02.csv') alldata = data.readlines() listdata = [] for i in alldata: listdata.append(i.strip().split(',')) #Seperate each list to display in graph year = [] affect = [] damage = [] death =[] for j in listdata: if j[0] == 'Indonesia'and j[2] == 'Flood': year.append(int(j[1])) affect.append(int(j[3])) damage.append(int(j[4])) death.append(int(j[5])) import plotly.plotly as py import plotly.graph_objs as go death = go.Scatter( x=year, y=death, mode='markers', marker=dict( color=['#FF8C00' for i in death], opacity=[0.4 for i in death], size=[15 for i in death], ) ) damage = go.Scatter( x=year, y=damage, mode='markers', marker=dict( color=['#FF0000' for i in damage], opacity=[0.6 for i in damage], size=[25 for i in damage], ) ) affect = go.Scatter( x=year, y=affect, mode='markers', marker=dict( color=['#FFBBFF' for i in damage], opacity=[0.8 for i in damage], size=[10 for i in damage], ) ) data = [death, damage, affect] layout = go.Layout( showlegend=True, height=600, width=600, ) fig = go.Figure(data=data, layout=layout) plot_url = py.plot(fig, filename='pdeesawat69_2')
apache-2.0
TalShafir/ansible
lib/ansible/modules/database/influxdb/influxdb_write.py
111
2493
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2017, René Moser <mail@renemoser.net> # 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: influxdb_write short_description: Write data points into InfluxDB. description: - Write data points into InfluxDB. version_added: 2.5 author: "René Moser (@resmo)" requirements: - "python >= 2.6" - "influxdb >= 0.9" options: data_points: description: - Data points as dict to write into the database. required: true database_name: description: - Name of the database. required: true extends_documentation_fragment: influxdb ''' EXAMPLES = r''' - name: Write points into database influxdb_write: hostname: "{{influxdb_ip_address}}" database_name: "{{influxdb_database_name}}" data_points: - measurement: connections tags: host: server01 region: us-west time: "{{ ansible_date_time.iso8601 }}" fields: value: 2000 - measurement: connections tags: host: server02 region: us-east time: "{{ ansible_date_time.iso8601 }}" fields: value: 3000 ''' RETURN = r''' # only defaults ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_native from ansible.module_utils.influxdb import InfluxDb class AnsibleInfluxDBWrite(InfluxDb): def write_data_point(self, data_points): client = self.connect_to_influxdb() client.write_points(data_points) try: client.write_points(data_points) except Exception as e: self.module.fail_json(msg=to_native(e)) def main(): argument_spec = InfluxDb.influxdb_argument_spec() argument_spec.update( data_points=dict(required=True, type='list'), database_name=dict(required=True, type='str'), ) module = AnsibleModule( argument_spec=argument_spec, ) influx = AnsibleInfluxDBWrite(module) data_points = module.params.get('data_points') influx.write_data_point(data_points) module.exit_json(changed=True) if __name__ == '__main__': main()
gpl-3.0
elventear/ansible-modules-core
cloud/openstack/os_subnet.py
25
12768
#!/usr/bin/python #coding: utf-8 -*- # (c) 2013, Benno Joy <benno@ansible.com> # # This module is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This software is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this software. If not, see <http://www.gnu.org/licenses/>. try: import shade HAS_SHADE = True except ImportError: HAS_SHADE = False ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' --- module: os_subnet short_description: Add/Remove subnet to an OpenStack network extends_documentation_fragment: openstack version_added: "2.0" author: "Monty Taylor (@emonty)" description: - Add or Remove a subnet to an OpenStack network options: state: description: - Indicate desired state of the resource choices: ['present', 'absent'] required: false default: present network_name: description: - Name of the network to which the subnet should be attached - Required when I(state) is 'present' required: false name: description: - The name of the subnet that should be created. Although Neutron allows for non-unique subnet names, this module enforces subnet name uniqueness. required: true cidr: description: - The CIDR representation of the subnet that should be assigned to the subnet. Required when I(state) is 'present' required: false default: None ip_version: description: - The IP version of the subnet 4 or 6 required: false default: 4 enable_dhcp: description: - Whether DHCP should be enabled for this subnet. required: false default: true gateway_ip: description: - The ip that would be assigned to the gateway for this subnet required: false default: None no_gateway_ip: description: - The gateway IP would not be assigned for this subnet required: false default: false version_added: "2.2" dns_nameservers: description: - List of DNS nameservers for this subnet. required: false default: None allocation_pool_start: description: - From the subnet pool the starting address from which the IP should be allocated. required: false default: None allocation_pool_end: description: - From the subnet pool the last IP that should be assigned to the virtual machines. required: false default: None host_routes: description: - A list of host route dictionaries for the subnet. required: false default: None ipv6_ra_mode: description: - IPv6 router advertisement mode choices: ['dhcpv6-stateful', 'dhcpv6-stateless', 'slaac'] required: false default: None ipv6_address_mode: description: - IPv6 address mode choices: ['dhcpv6-stateful', 'dhcpv6-stateless', 'slaac'] required: false default: None project: description: - Project name or ID containing the subnet (name admin-only) required: false default: None version_added: "2.1" requirements: - "python >= 2.6" - "shade" ''' EXAMPLES = ''' # Create a new (or update an existing) subnet on the specified network - os_subnet: state: present network_name: network1 name: net1subnet cidr: 192.168.0.0/24 dns_nameservers: - 8.8.8.7 - 8.8.8.8 host_routes: - destination: 0.0.0.0/0 nexthop: 12.34.56.78 - destination: 192.168.0.0/24 nexthop: 192.168.0.1 # Delete a subnet - os_subnet: state: absent name: net1subnet # Create an ipv6 stateless subnet - os_subnet: state: present name: intv6 network_name: internal ip_version: 6 cidr: 2db8:1::/64 dns_nameservers: - 2001:4860:4860::8888 - 2001:4860:4860::8844 ipv6_ra_mode: dhcpv6-stateless ipv6_address_mode: dhcpv6-stateless ''' def _can_update(subnet, module, cloud): """Check for differences in non-updatable values""" network_name = module.params['network_name'] cidr = module.params['cidr'] ip_version = int(module.params['ip_version']) ipv6_ra_mode = module.params['ipv6_ra_mode'] ipv6_a_mode = module.params['ipv6_address_mode'] if network_name: network = cloud.get_network(network_name) if network: netid = network['id'] else: module.fail_json(msg='No network found for %s' % network_name) if netid != subnet['network_id']: module.fail_json(msg='Cannot update network_name in existing \ subnet') if ip_version and subnet['ip_version'] != ip_version: module.fail_json(msg='Cannot update ip_version in existing subnet') if ipv6_ra_mode and subnet.get('ipv6_ra_mode', None) != ipv6_ra_mode: module.fail_json(msg='Cannot update ipv6_ra_mode in existing subnet') if ipv6_a_mode and subnet.get('ipv6_address_mode', None) != ipv6_a_mode: module.fail_json(msg='Cannot update ipv6_address_mode in existing \ subnet') def _needs_update(subnet, module, cloud): """Check for differences in the updatable values.""" # First check if we are trying to update something we're not allowed to _can_update(subnet, module, cloud) # now check for the things we are allowed to update enable_dhcp = module.params['enable_dhcp'] subnet_name = module.params['name'] pool_start = module.params['allocation_pool_start'] pool_end = module.params['allocation_pool_end'] gateway_ip = module.params['gateway_ip'] no_gateway_ip = module.params['no_gateway_ip'] dns = module.params['dns_nameservers'] host_routes = module.params['host_routes'] curr_pool = subnet['allocation_pools'][0] if subnet['enable_dhcp'] != enable_dhcp: return True if subnet_name and subnet['name'] != subnet_name: return True if pool_start and curr_pool['start'] != pool_start: return True if pool_end and curr_pool['end'] != pool_end: return True if gateway_ip and subnet['gateway_ip'] != gateway_ip: return True if dns and sorted(subnet['dns_nameservers']) != sorted(dns): return True if host_routes: curr_hr = sorted(subnet['host_routes'], key=lambda t: t.keys()) new_hr = sorted(host_routes, key=lambda t: t.keys()) if sorted(curr_hr) != sorted(new_hr): return True if no_gateway_ip and subnet['gateway_ip']: return True return False def _system_state_change(module, subnet, cloud): state = module.params['state'] if state == 'present': if not subnet: return True return _needs_update(subnet, module, cloud) if state == 'absent' and subnet: return True return False def main(): ipv6_mode_choices = ['dhcpv6-stateful', 'dhcpv6-stateless', 'slaac'] argument_spec = openstack_full_argument_spec( name=dict(required=True), network_name=dict(default=None), cidr=dict(default=None), ip_version=dict(default='4', choices=['4', '6']), enable_dhcp=dict(default='true', type='bool'), gateway_ip=dict(default=None), no_gateway_ip=dict(default=False, type='bool'), dns_nameservers=dict(default=None, type='list'), allocation_pool_start=dict(default=None), allocation_pool_end=dict(default=None), host_routes=dict(default=None, type='list'), ipv6_ra_mode=dict(default=None, choice=ipv6_mode_choices), ipv6_address_mode=dict(default=None, choice=ipv6_mode_choices), state=dict(default='present', choices=['absent', 'present']), project=dict(default=None) ) module_kwargs = openstack_module_kwargs() module = AnsibleModule(argument_spec, supports_check_mode=True, **module_kwargs) if not HAS_SHADE: module.fail_json(msg='shade is required for this module') state = module.params['state'] network_name = module.params['network_name'] cidr = module.params['cidr'] ip_version = module.params['ip_version'] enable_dhcp = module.params['enable_dhcp'] subnet_name = module.params['name'] gateway_ip = module.params['gateway_ip'] no_gateway_ip = module.params['no_gateway_ip'] dns = module.params['dns_nameservers'] pool_start = module.params['allocation_pool_start'] pool_end = module.params['allocation_pool_end'] host_routes = module.params['host_routes'] ipv6_ra_mode = module.params['ipv6_ra_mode'] ipv6_a_mode = module.params['ipv6_address_mode'] project = module.params.pop('project') # Check for required parameters when state == 'present' if state == 'present': for p in ['network_name', 'cidr']: if not module.params[p]: module.fail_json(msg='%s required with present state' % p) if pool_start and pool_end: pool = [dict(start=pool_start, end=pool_end)] elif pool_start or pool_end: module.fail_json(msg='allocation pool requires start and end values') else: pool = None if no_gateway_ip and gateway_ip: module.fail_json(msg='no_gateway_ip is not allowed with gateway_ip') try: cloud = shade.openstack_cloud(**module.params) if project is not None: proj = cloud.get_project(project) if proj is None: module.fail_json(msg='Project %s could not be found' % project) project_id = proj['id'] filters = {'tenant_id': project_id} else: project_id = None filters = None subnet = cloud.get_subnet(subnet_name, filters=filters) if module.check_mode: module.exit_json(changed=_system_state_change(module, subnet, cloud)) if state == 'present': if not subnet: subnet = cloud.create_subnet(network_name, cidr, ip_version=ip_version, enable_dhcp=enable_dhcp, subnet_name=subnet_name, gateway_ip=gateway_ip, disable_gateway_ip=no_gateway_ip, dns_nameservers=dns, allocation_pools=pool, host_routes=host_routes, ipv6_ra_mode=ipv6_ra_mode, ipv6_address_mode=ipv6_a_mode, tenant_id=project_id) changed = True else: if _needs_update(subnet, module, cloud): cloud.update_subnet(subnet['id'], subnet_name=subnet_name, enable_dhcp=enable_dhcp, gateway_ip=gateway_ip, disable_gateway_ip=no_gateway_ip, dns_nameservers=dns, allocation_pools=pool, host_routes=host_routes) changed = True else: changed = False module.exit_json(changed=changed, subnet=subnet, id=subnet['id']) elif state == 'absent': if not subnet: changed = False else: changed = True cloud.delete_subnet(subnet_name) module.exit_json(changed=changed) except shade.OpenStackCloudException as e: module.fail_json(msg=str(e)) # this is magic, see lib/ansible/module_common.py from ansible.module_utils.basic import * from ansible.module_utils.openstack import * if __name__ == '__main__': main()
gpl-3.0
andrew-furtak/chipsec
chipsec/utilcmd/mmcfg_cmd.py
6
3307
#!/usr/bin/python #CHIPSEC: Platform Security Assessment Framework #Copyright (c) 2010-2015, Intel Corporation # #This program is free software; you can redistribute it and/or #modify it under the terms of the GNU General Public License #as published by the Free Software Foundation; Version 2. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. # #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # #Contact information: #chipsec@intel.com # """ The mmcfg command allows direct access to memory mapped config space. """ import time from chipsec.command import BaseCommand from chipsec.hal import mmio # Access to Memory Mapped PCIe Configuration Space (MMCFG) class MMCfgCommand(BaseCommand): """ >>> chipsec_util mmcfg <bus> <device> <function> <offset> <width> [value] Examples: >>> chipsec_util mmcfg 0 0 0 0x88 4 >>> chipsec_util mmcfg 0 0 0 0x88 byte 0x1A >>> chipsec_util mmcfg 0 0x1F 0 0xDC 1 0x1 >>> chipsec_util mmcfg 0 0 0 0x98 dword 0x004E0040 """ def requires_driver(self): return True def run(self): t = time.time() _mmio = mmio.MMIO(self.cs) if 2 == len(self.argv): #pciexbar = _mmio.get_PCIEXBAR_base_address() pciexbar = _mmio.get_MMCFG_base_address() self.logger.log( "[CHIPSEC] Memory Mapped Config Base: 0x%016X" % pciexbar ) return elif 6 > len(self.argv): print MMCfgCommand.__doc__ return try: bus = int(self.argv[2],16) device = int(self.argv[3],16) function = int(self.argv[4],16) offset = int(self.argv[5],16) if 6 == len(self.argv): width = 1 else: if 'byte' == self.argv[6]: width = 1 elif 'word' == self.argv[6]: width = 2 elif 'dword' == self.argv[6]: width = 4 else: width = int(self.argv[6]) except Exception as e : print MMCfgCommand.__doc__ return if 8 == len(self.argv): value = int(self.argv[7], 16) _mmio.write_mmcfg_reg(bus, device, function, offset, width, value ) #_cs.pci.write_mmcfg_reg( bus, device, function, offset, width, value ) self.logger.log( "[CHIPSEC] writing MMCFG register (%02d:%02d.%d + 0x%02X): 0x%X" % (bus, device, function, offset, value) ) else: value = _mmio.read_mmcfg_reg(bus, device, function, offset, width ) #value = _cs.pci.read_mmcfg_reg( bus, device, function, offset, width ) self.logger.log( "[CHIPSEC] reading MMCFG register (%02d:%02d.%d + 0x%02X): 0x%X" % (bus, device, function, offset, value) ) self.logger.log( "[CHIPSEC] (mmcfg) time elapsed %.3f" % (time.time()-t) ) commands = { 'mmcfg': MMCfgCommand }
gpl-2.0
gangadhar-kadam/helpdesk-frappe
frappe/config/docs.py
3
1141
source_link = "https://github.com/frappe/frappe" docs_base_url = "https://frappe.github.io/frappe" headline = "Superhero Web Framework" sub_heading = "Build extensions to ERPNext or make your own app" hide_install = True long_description = """Frappe is a full stack web application framework written in Python, Javascript, HTML/CSS with MySQL as the backend. It was built for ERPNext but is pretty generic and can be used to build database driven apps. The key differece in Frappe compared to other frameworks is that Frappe is that meta-data is also treated as data and is used to build front-ends very easily. Frappe comes with a full blown admin UI called the **Desk** that handles forms, navigation, lists, menus, permissions, file attachment and much more out of the box. Frappe also has a plug-in architecture that can be used to build plugins to ERPNext. Frappe Framework was designed to build [ERPNext](https://erpnext.com), open source ERP for managing small and medium sized businesses. [Get started with the Tutorial](https://frappe.github.io/frappe/user/tutorial) """ docs_version = "6.x.x" def get_context(context): pass
mit
midma101/AndIWasJustGoingToBed
.venv/lib/python2.7/site-packages/Crypto/Util/Counter.py
132
5157
# -*- coding: ascii -*- # # Util/Counter.py : Fast counter for use with CTR-mode ciphers # # Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net> # # =================================================================== # The contents of this file are dedicated to the public domain. To # the extent that dedication to the public domain is not available, # everyone is granted a worldwide, perpetual, royalty-free, # non-exclusive license to exercise all rights associated with the # contents of this file for any purpose whatsoever. # No rights are reserved. # # 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. # =================================================================== """Fast counter functions for CTR cipher modes. CTR is a chaining mode for symmetric block encryption or decryption. Messages are divideded into blocks, and the cipher operation takes place on each block using the secret key and a unique *counter block*. The most straightforward way to fulfil the uniqueness property is to start with an initial, random *counter block* value, and increment it as the next block is processed. The block ciphers from `Crypto.Cipher` (when configured in *MODE_CTR* mode) invoke a callable object (the *counter* parameter) to get the next *counter block*. Unfortunately, the Python calling protocol leads to major performance degradations. The counter functions instantiated by this module will be invoked directly by the ciphers in `Crypto.Cipher`. The fact that the Python layer is bypassed lead to more efficient (and faster) execution of CTR cipher modes. An example of usage is the following: >>> from Crypto.Cipher import AES >>> from Crypto.Util import Counter >>> >>> pt = b'\x00'*1000000 >>> ctr = Counter.new(128) >>> cipher = AES.new(b'\x00'*16, AES.MODE_CTR, counter=ctr) >>> ct = cipher.encrypt(pt) :undocumented: __package__ """ import sys if sys.version_info[0] == 2 and sys.version_info[1] == 1: from Crypto.Util.py21compat import * from Crypto.Util.py3compat import * from Crypto.Util import _counter import struct # Factory function def new(nbits, prefix=b(""), suffix=b(""), initial_value=1, overflow=0, little_endian=False, allow_wraparound=False, disable_shortcut=False): """Create a stateful counter block function suitable for CTR encryption modes. Each call to the function returns the next counter block. Each counter block is made up by three parts:: prefix || counter value || postfix The counter value is incremented by one at each call. :Parameters: nbits : integer Length of the desired counter, in bits. It must be a multiple of 8. prefix : byte string The constant prefix of the counter block. By default, no prefix is used. suffix : byte string The constant postfix of the counter block. By default, no suffix is used. initial_value : integer The initial value of the counter. Default value is 1. little_endian : boolean If True, the counter number will be encoded in little endian format. If False (default), in big endian format. allow_wraparound : boolean If True, the function will raise an *OverflowError* exception as soon as the counter wraps around. If False (default), the counter will simply restart from zero. disable_shortcut : boolean If True, do not make ciphers from `Crypto.Cipher` bypass the Python layer when invoking the counter block function. If False (default), bypass the Python layer. :Returns: The counter block function. """ # Sanity-check the message size (nbytes, remainder) = divmod(nbits, 8) if remainder != 0: # In the future, we might support arbitrary bit lengths, but for now we don't. raise ValueError("nbits must be a multiple of 8; got %d" % (nbits,)) if nbytes < 1: raise ValueError("nbits too small") elif nbytes > 0xffff: raise ValueError("nbits too large") initval = _encode(initial_value, nbytes, little_endian) if little_endian: return _counter._newLE(bstr(prefix), bstr(suffix), initval, allow_wraparound=allow_wraparound, disable_shortcut=disable_shortcut) else: return _counter._newBE(bstr(prefix), bstr(suffix), initval, allow_wraparound=allow_wraparound, disable_shortcut=disable_shortcut) def _encode(n, nbytes, little_endian=False): retval = [] n = long(n) for i in range(nbytes): if little_endian: retval.append(bchr(n & 0xff)) else: retval.insert(0, bchr(n & 0xff)) n >>= 8 return b("").join(retval) # vim:set ts=4 sw=4 sts=4 expandtab:
mit
Nicop06/ansible
lib/ansible/plugins/connection/buildah.py
84
6344
# Based on the docker connection plugin # Copyright (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # # Connection plugin for building container images using buildah tool # https://github.com/projectatomic/buildah # # Written by: Tomas Tomecek (https://github.com/TomasTomecek) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = """ connection: buildah short_description: Interact with an existing buildah container description: - Run commands or put/fetch files to an existing container using buildah tool. author: Tomas Tomecek (ttomecek@redhat.com) version_added: 2.4 options: remote_addr: description: - The ID of the container you want to access. default: inventory_hostname vars: - name: ansible_host # keyword: # - name: hosts remote_user: description: - User specified via name or ID which is used to execute commands inside the container. ini: - section: defaults key: remote_user env: - name: ANSIBLE_REMOTE_USER vars: - name: ansible_user # keyword: # - name: remote_user """ import shlex import shutil import subprocess import ansible.constants as C from ansible.module_utils._text import to_bytes, to_native from ansible.plugins.connection import ConnectionBase, ensure_connect try: from __main__ import display except ImportError: from ansible.utils.display import Display display = Display() # this _has to be_ named Connection class Connection(ConnectionBase): """ This is a connection plugin for buildah: it uses buildah binary to interact with the containers """ # String used to identify this Connection class from other classes transport = 'buildah' has_pipelining = True become_methods = frozenset(C.BECOME_METHODS) def __init__(self, play_context, new_stdin, *args, **kwargs): super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs) self._container_id = self._play_context.remote_addr self._connected = False # container filesystem will be mounted here on host self._mount_point = None # `buildah inspect` doesn't contain info about what the default user is -- if it's not # set, it's empty self.user = self._play_context.remote_user def _set_user(self): self._buildah(b"config", [b"--user=" + to_bytes(self.user, errors='surrogate_or_strict')]) def _buildah(self, cmd, cmd_args=None, in_data=None): """ run buildah executable :param cmd: buildah's command to execute (str) :param cmd_args: list of arguments to pass to the command (list of str/bytes) :param in_data: data passed to buildah's stdin :return: return code, stdout, stderr """ local_cmd = ['buildah', cmd, '--', self._container_id] if cmd_args: local_cmd += cmd_args local_cmd = [to_bytes(i, errors='surrogate_or_strict') for i in local_cmd] display.vvv("RUN %s" % (local_cmd,), host=self._container_id) p = subprocess.Popen(local_cmd, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate(input=in_data) stdout = to_bytes(stdout, errors='surrogate_or_strict') stderr = to_bytes(stderr, errors='surrogate_or_strict') return p.returncode, stdout, stderr def _connect(self): """ no persistent connection is being maintained, mount container's filesystem so we can easily access it """ super(Connection, self)._connect() rc, self._mount_point, stderr = self._buildah("mount") self._mount_point = self._mount_point.strip() display.vvvvv("MOUNTPOINT %s RC %s STDERR %r" % (self._mount_point, rc, stderr)) self._connected = True @ensure_connect def exec_command(self, cmd, in_data=None, sudoable=False): """ run specified command in a running OCI container using buildah """ super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable) # shlex.split has a bug with text strings on Python-2.6 and can only handle text strings on Python-3 cmd_args_list = shlex.split(to_native(cmd, errors='surrogate_or_strict')) rc, stdout, stderr = self._buildah("run", cmd_args_list) display.vvvvv("STDOUT %r STDERR %r" % (stderr, stderr)) return rc, stdout, stderr def put_file(self, in_path, out_path): """ Place a local file located in 'in_path' inside container at 'out_path' """ super(Connection, self).put_file(in_path, out_path) display.vvv("PUT %s TO %s" % (in_path, out_path), host=self._container_id) real_out_path = self._mount_point + to_bytes(out_path, errors='surrogate_or_strict') shutil.copyfile( to_bytes(in_path, errors='surrogate_or_strict'), to_bytes(real_out_path, errors='surrogate_or_strict') ) # alternatively, this can be implemented using `buildah copy`: # rc, stdout, stderr = self._buildah( # "copy", # [to_bytes(in_path, errors='surrogate_or_strict'), # to_bytes(out_path, errors='surrogate_or_strict')] # ) def fetch_file(self, in_path, out_path): """ obtain file specified via 'in_path' from the container and place it at 'out_path' """ super(Connection, self).fetch_file(in_path, out_path) display.vvv("FETCH %s TO %s" % (in_path, out_path), host=self._container_id) real_in_path = self._mount_point + to_bytes(in_path, errors='surrogate_or_strict') shutil.copyfile( to_bytes(real_in_path, errors='surrogate_or_strict'), to_bytes(out_path, errors='surrogate_or_strict') ) def close(self): """ unmount container's filesystem """ super(Connection, self).close() rc, stdout, stderr = self._buildah("umount") display.vvvvv("RC %s STDOUT %r STDERR %r" % (rc, stdout, stderr)) self._connected = False
gpl-3.0
WojtekReu/Politikon
events/views.py
1
10125
import json import logging from django.contrib.auth.decorators import login_required, user_passes_test from django.core.exceptions import PermissionDenied from django.db import transaction from django.http import Http404, HttpResponseBadRequest from django.shortcuts import get_object_or_404 from django.utils.decorators import method_decorator from django.utils.translation import ugettext as _ from django.views.decorators.clickjacking import xframe_options_exempt from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_http_methods from django.views.decorators.vary import vary_on_headers from django.views.generic import DetailView from .exceptions import ( NonexistantEvent, DraftEvent, PriceMismatch, EventNotInProgress, UnknownOutcome, InsufficientBets, InsufficientCash ) from .models import Event, Bet, SolutionVote, EventCategory from accounts.models import UserProfile from bladepolska.http import JSONResponse, JSONResponseBadRequest from haystack.generic_views import SearchView # from haystack.query import SearchQuerySet logger = logging.getLogger(__name__) class EventsListView(SearchView): template_name = 'events/events.html' paginate_by = 12 def get_queryset(self): queryset = super(EventsListView, self).get_queryset() if not self.request.user.is_authenticated() or not self.request.user.is_staff: queryset = queryset.filter(is_published=True) mode = self.kwargs.get('mode') if mode == 'popular': queryset = queryset.filter(outcome=Event.IN_PROGRESS).order_by('-turnover') elif mode == 'last-minute': queryset = queryset.filter(outcome=Event.IN_PROGRESS).order_by('estimated_end_date') elif mode == 'latest': queryset = queryset.filter(outcome=Event.IN_PROGRESS).order_by('-created_date') elif mode == 'changed': queryset = queryset.filter(outcome=Event.IN_PROGRESS).order_by('-absolute_price_change') elif mode == 'finished': queryset = queryset.exclude(outcome=Event.IN_PROGRESS).order_by('-end_date') elif mode == 'draft': queryset = queryset.exclude(is_published=True) category = self.kwargs.get('category') if category: event_category = get_object_or_404(EventCategory, slug=category) queryset = queryset.filter(categories__in=[event_category]) # events = Event.objects.get_events(self.kwargs['mode']) # tag = self.request.GET.get('tag') # if tag: # queryset = queryset.filter(tags__name__in=[tag]).distinct() for event in queryset: event.object.bet_line = event.object.get_user_bet(self.request.user) return queryset def get_context_data(self, *args, **kwargs): context = super(EventsListView, self).get_context_data(*args, **kwargs) if 'mode' in self.kwargs: context['active'] = self.kwargs['mode'] if 'category' in self.kwargs: context['active'] = self.kwargs['category'] context['popular_tags'] = Event.tags.most_common()[:10] context['categories'] = EventCategory.objects.all() return context class EventFacebookObjectDetailView(DetailView): template_name = 'events/facebook_event_detail.html' context_object_name = 'event' model = Event def get_object(self): return get_object_or_404(Event, id=self.kwargs['pk']) class EventDetailView(DetailView): template_name = 'events/event_detail.html' context_object_name = 'event' model = Event def get_event(self): return get_object_or_404(Event, id=self.kwargs['pk']) def dispatch(self, request, *args, **kwargs): event = self.get_event() if not request.user.is_staff and not event.is_published: raise PermissionDenied return super(EventDetailView, self).dispatch(request, *args, **kwargs) def get_context_data(self, *args, **kwargs): context = super(EventDetailView, self).get_context_data(*args, **kwargs) event = self.get_event() user = self.request.user bet_line = event.get_user_bet(user) # Voted voted = None if user.is_staff: try: sv = SolutionVote.objects.get(user=user, event=event) voted = 'TAK' if sv.outcome == SolutionVote.YES else 'NIE' except SolutionVote.DoesNotExist: pass # Similar events # similar_events = SearchQuerySet().more_like_this(event) similar_events = [x for x in event.tags.similar_objects() if x.outcome == Event.IN_PROGRESS] for similar_event in similar_events: similar_event.bet_line = similar_event.get_user_bet(self.request.user) # Share module if bet_line: share_url = u'{}?vote={}'.format( event.get_absolute_url(), 'true' if bet_line['outcome'] else 'false', ) else: share_url = event.get_absolute_url() context.update({ 'bet_line': bet_line, 'active': 1, 'voted': voted, 'event_dict': event.event_dict, 'bet_social': event.get_bet_social(), 'og_user': UserProfile.objects.filter(username=self.request.GET.get('user')).first(), 'og_vote': self.request.GET.get('vote'), 'similar_events': similar_events[:3], 'share_url': share_url }) return context class EventEmbedDetailView(DetailView): template_name = 'events/event_embed_detail.html' context_object_name = 'event' model = Event def get_event(self): return get_object_or_404(Event, id=self.kwargs['pk']) @method_decorator(xframe_options_exempt) def dispatch(self, request, *args, **kwargs): event = self.get_event() if not event.is_published: raise PermissionDenied return super(EventEmbedDetailView, self).dispatch(request, *args, **kwargs) @login_required @require_http_methods(["POST"]) @csrf_exempt @transaction.atomic def create_transaction(request, event_id): """ Buy or sell bet :param request: :param event_id: :return: """ data = json.loads(request.body) try: # simple params validation buy = bool(data['buy']) # True - buy, False - sell outcome = bool(data['outcome']) # True - YES, False - NO for_price = int(data['for_price']) # price except KeyError: return HttpResponseBadRequest(_("Something went wrong, try again in a few seconds.")) try: if buy: user, event, bet = Bet.objects.buy_a_bet(request.user, event_id, outcome, for_price) else: user, event, bet = Bet.objects.sell_a_bet(request.user, event_id, outcome, for_price) except NonexistantEvent: raise Http404 except DraftEvent as e: result = { 'error': unicode(e.message.decode('utf-8')), } return JSONResponseBadRequest(json.dumps(result)) except PriceMismatch as e: result = { 'error': unicode(e.message.decode('utf-8')), 'updates': { 'events': [ e.updated_event.event_dict ] } } return JSONResponseBadRequest(json.dumps(result)) except InsufficientCash as e: result = { 'error': unicode(e.message.decode('utf-8')), 'updates': { 'user': [ e.updated_user.statistics_dict ] } } return JSONResponseBadRequest(json.dumps(result)) except InsufficientBets as e: result = { 'error': unicode(e.message.decode('utf-8')), 'updates': { 'bets': [ e.updated_bet.bet_dict ] } } return JSONResponseBadRequest(json.dumps(result)) except EventNotInProgress as e: result = { 'error': unicode(e.message.decode('utf-8')), } return JSONResponseBadRequest(json.dumps(result)) except UnknownOutcome as e: result = { 'error': unicode(e.message.decode('utf-8')), } return JSONResponseBadRequest(json.dumps(result)) result = { 'updates': { 'bets': [ bet.bet_dict ], 'events': [ event.event_dict ], 'user': user.statistics_dict } } return JSONResponse(json.dumps(result)) @login_required @vary_on_headers('HTTP_X_REQUESTED_WITH') def bets_viewed(request): """ Uncheck new finished event as read :param request: :type request: WSGIRequest :return: json list with bet ids :rtype: JSONResponse """ bets_id_list = request.GET.getlist('bets[]') bets_resolved = [] for bet_id in bets_id_list: try: bet = Bet.objects.get(user=request.user, id=int(bet_id)) except ValueError: continue # TODO: log somewhere or do something bet.is_new_resolved = False bet.save() bets_resolved.append(bet_id) return JSONResponse(json.dumps(bets_resolved)) @user_passes_test(lambda u: u.is_staff) @require_http_methods(["POST"]) @csrf_exempt @transaction.atomic def resolve_event(request, event_id): """ Vote for yes or no :param request: :type request: WSGIRequest :param event_id: event id :type event_id: int :return: """ data = json.loads(request.body) try: vote_result = Event.objects.vote_for_solution(request.user, event_id, data['outcome']) except EventNotInProgress as e: result = { 'error': unicode(e.message.decode('utf-8')), } return JSONResponseBadRequest(json.dumps(result)) result = { 'updates': vote_result } return JSONResponse(json.dumps(result))
gpl-2.0
di0spyr0s/pants
tests/python/pants_test/testutils/compile_strategy_utils.py
6
1461
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import sys """Helpers to provide compile strategies to unit tests. These methods work around the fact that pytest.mark.parametrize does not support methods. """ _STRATEGIES = ['global', 'isolated'] _SCOPES = ['apt', 'java', 'scala'] def _wrap(testmethod, setupfun): def wrapped(self): for strategy in _STRATEGIES: try: setupfun(self, testmethod, strategy) except Exception: print("failed for strategy '{}'".format(strategy), file=sys.stderr) raise return wrapped def provide_compile_strategies(testmethod): """ A decorator for test methods that provides the compilation strategy as a parameter. Invokes the test multiple times, once for each built-in strategy in _STRATEGIES. """ return _wrap(testmethod, lambda self, testmethod, strategy: testmethod(self, strategy)) def set_compile_strategies(testmethod): """A decorator for BaseTests which sets strategy options differently for each invoke.""" def setup(self, testmethod, strategy): for scope in _SCOPES: self.set_options_for_scope('compile.{}'.format(scope), strategy=strategy) testmethod(self) return _wrap(testmethod, setup)
apache-2.0
ryancoleman/autodock-vina
boost_1_54_0/tools/build/v2/test/template.py
64
1081
#!/usr/bin/python # Copyright (C) FILL SOMETHING HERE 2006. # Distributed under the Boost Software License, Version 1.0. (See # accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) # This file is template for Boost.Build tests. It creates a simple project that # builds one exe from one source, and checks that the exe is really created. import BoostBuild # Create a temporary working directory. t = BoostBuild.Tester() # Create the needed files. t.write("jamroot.jam", """ exe hello : hello.cpp ; """) t.write("hello.cpp", """ int main() {} """ # Run the build. t.run_build_system() # First, create a list of three pathnames. file_list = BoostBuild.List("bin/$toolset/debug/") * \ BoostBuild.List("hello.exe hello.obj") # Second, assert that those files were added as result of the last build system # invocation. t.expect_addition(file_list) # Invoke the build system once again. t.run_build_system("clean") # Check if the files added previously were removed. t.expect_removal(file_list) # Remove temporary directories. t.cleanup()
apache-2.0
nikolas/lettuce
tests/integration/lib/Django-1.2.5/django/contrib/gis/db/backends/spatialite/introspection.py
401
2112
from django.contrib.gis.gdal import OGRGeomType from django.db.backends.sqlite3.introspection import DatabaseIntrospection, FlexibleFieldLookupDict class GeoFlexibleFieldLookupDict(FlexibleFieldLookupDict): """ Sublcass that includes updates the `base_data_types_reverse` dict for geometry field types. """ base_data_types_reverse = FlexibleFieldLookupDict.base_data_types_reverse.copy() base_data_types_reverse.update( {'point' : 'GeometryField', 'linestring' : 'GeometryField', 'polygon' : 'GeometryField', 'multipoint' : 'GeometryField', 'multilinestring' : 'GeometryField', 'multipolygon' : 'GeometryField', 'geometrycollection' : 'GeometryField', }) class SpatiaLiteIntrospection(DatabaseIntrospection): data_types_reverse = GeoFlexibleFieldLookupDict() def get_geometry_type(self, table_name, geo_col): cursor = self.connection.cursor() try: # Querying the `geometry_columns` table to get additional metadata. cursor.execute('SELECT "coord_dimension", "srid", "type" ' 'FROM "geometry_columns" ' 'WHERE "f_table_name"=%s AND "f_geometry_column"=%s', (table_name, geo_col)) row = cursor.fetchone() if not row: raise Exception('Could not find a geometry column for "%s"."%s"' % (table_name, geo_col)) # OGRGeomType does not require GDAL and makes it easy to convert # from OGC geom type name to Django field. field_type = OGRGeomType(row[2]).django # Getting any GeometryField keyword arguments that are not the default. dim = row[0] srid = row[1] field_params = {} if srid != 4326: field_params['srid'] = srid if isinstance(dim, basestring) and 'Z' in dim: field_params['dim'] = 3 finally: cursor.close() return field_type, field_params
gpl-3.0
rdipietro/tensorflow
tensorflow/contrib/distributions/python/ops/normal.py
15
8485
# 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. # ============================================================================== """The Normal (Gaussian) distribution class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math from tensorflow.contrib.bayesflow.python.ops import special_math from tensorflow.contrib.distributions.python.ops import distribution from tensorflow.contrib.distributions.python.ops import kullback_leibler from tensorflow.contrib.framework.python.framework import tensor_util as contrib_tensor_util from tensorflow.python.framework import common_shapes from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.ops import array_ops from tensorflow.python.ops import check_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn from tensorflow.python.ops import random_ops class Normal(distribution.Distribution): """The scalar Normal distribution with mean and stddev parameters mu, sigma. #### Mathematical details The PDF of this distribution is: ```f(x) = sqrt(1/(2*pi*sigma^2)) exp(-(x-mu)^2/(2*sigma^2))``` #### Examples Examples of initialization of one or a batch of distributions. ```python # Define a single scalar Normal distribution. dist = tf.contrib.distributions.Normal(mu=0., sigma=3.) # Evaluate the cdf at 1, returning a scalar. dist.cdf(1.) # Define a batch of two scalar valued Normals. # The first has mean 1 and standard deviation 11, the second 2 and 22. dist = tf.contrib.distributions.Normal(mu=[1, 2.], sigma=[11, 22.]) # Evaluate the pdf of the first distribution on 0, and the second on 1.5, # returning a length two tensor. dist.pdf([0, 1.5]) # Get 3 samples, returning a 3 x 2 tensor. dist.sample([3]) ``` Arguments are broadcast when possible. ```python # Define a batch of two scalar valued Normals. # Both have mean 1, but different standard deviations. dist = tf.contrib.distributions.Normal(mu=1., sigma=[11, 22.]) # Evaluate the pdf of both distributions on the same point, 3.0, # returning a length 2 tensor. dist.pdf(3.0) ``` """ def __init__(self, mu, sigma, validate_args=False, allow_nan_stats=True, name="Normal"): """Construct Normal distributions with mean and stddev `mu` and `sigma`. The parameters `mu` and `sigma` must be shaped in a way that supports broadcasting (e.g. `mu + sigma` is a valid operation). Args: mu: Floating point tensor, the means of the distribution(s). sigma: Floating point tensor, the stddevs of the distribution(s). sigma must contain only positive values. validate_args: `Boolean`, default `False`. Whether to assert that `sigma > 0`. If `validate_args` is `False`, correct output is not guaranteed when input is invalid. allow_nan_stats: `Boolean`, default `True`. If `False`, raise an exception if a statistic (e.g. mean/mode/etc...) is undefined for any batch member. If `True`, batch members with valid parameters leading to undefined statistics will return NaN for this statistic. name: The name to give Ops created by the initializer. Raises: TypeError: if mu and sigma are different dtypes. """ parameters = locals() parameters.pop("self") with ops.name_scope(name, values=[mu, sigma]) as ns: with ops.control_dependencies([check_ops.assert_positive(sigma)] if validate_args else []): self._mu = array_ops.identity(mu, name="mu") self._sigma = array_ops.identity(sigma, name="sigma") contrib_tensor_util.assert_same_float_dtype((self._mu, self._sigma)) super(Normal, self).__init__( dtype=self._sigma.dtype, is_continuous=True, is_reparameterized=True, validate_args=validate_args, allow_nan_stats=allow_nan_stats, parameters=parameters, graph_parents=[self._mu, self._sigma], name=ns) @staticmethod def _param_shapes(sample_shape): return dict( zip(("mu", "sigma"), ([ops.convert_to_tensor( sample_shape, dtype=dtypes.int32)] * 2))) @property def mu(self): """Distribution parameter for the mean.""" return self._mu @property def sigma(self): """Distribution parameter for standard deviation.""" return self._sigma def _batch_shape(self): return array_ops.shape(self.mu + self.sigma) def _get_batch_shape(self): return common_shapes.broadcast_shape( self._mu.get_shape(), self.sigma.get_shape()) def _event_shape(self): return constant_op.constant([], dtype=dtypes.int32) def _get_event_shape(self): return tensor_shape.scalar() def _sample_n(self, n, seed=None): shape = array_ops.concat(0, ([n], array_ops.shape(self.mean()))) sampled = random_ops.random_normal( shape=shape, mean=0, stddev=1, dtype=self.mu.dtype, seed=seed) return sampled * self.sigma + self.mu def _log_prob(self, x): return (-0.5 * math.log(2. * math.pi) - math_ops.log(self.sigma) -0.5 * math_ops.square(self._z(x))) def _prob(self, x): return math_ops.exp(self._log_prob(x)) def _log_cdf(self, x): return special_math.log_ndtr(self._z(x)) def _cdf(self, x): return special_math.ndtr(self._z(x)) def _log_survival_function(self, x): return special_math.log_ndtr(-self._z(x)) def _survival_function(self, x): return special_math.ndtr(-self._z(x)) def _entropy(self): # Use broadcasting rules to calculate the full broadcast sigma. sigma = self.sigma * array_ops.ones_like(self.mu) return 0.5 * math.log(2. * math.pi * math.e) + math_ops.log(sigma) def _mean(self): return self.mu * array_ops.ones_like(self.sigma) def _variance(self): return math_ops.square(self.std()) def _std(self): return self.sigma * array_ops.ones_like(self.mu) def _mode(self): return self._mean() def _z(self, x): """Standardize input `x` to a unit normal.""" with ops.name_scope("standardize", values=[x]): return (x - self.mu) / self.sigma class NormalWithSoftplusSigma(Normal): """Normal with softplus applied to `sigma`.""" def __init__(self, mu, sigma, validate_args=False, allow_nan_stats=True, name="NormalWithSoftplusSigma"): parameters = locals() parameters.pop("self") with ops.name_scope(name, values=[sigma]) as ns: super(NormalWithSoftplusSigma, self).__init__( mu=mu, sigma=nn.softplus(sigma), validate_args=validate_args, allow_nan_stats=allow_nan_stats, name=ns) self._parameters = parameters @kullback_leibler.RegisterKL(Normal, Normal) def _kl_normal_normal(n_a, n_b, name=None): """Calculate the batched KL divergence KL(n_a || n_b) with n_a and n_b Normal. Args: n_a: instance of a Normal distribution object. n_b: instance of a Normal distribution object. name: (optional) Name to use for created operations. default is "kl_normal_normal". Returns: Batchwise KL(n_a || n_b) """ with ops.name_scope(name, "kl_normal_normal", [n_a.mu, n_b.mu]): one = constant_op.constant(1, dtype=n_a.dtype) two = constant_op.constant(2, dtype=n_a.dtype) half = constant_op.constant(0.5, dtype=n_a.dtype) s_a_squared = math_ops.square(n_a.sigma) s_b_squared = math_ops.square(n_b.sigma) ratio = s_a_squared / s_b_squared return (math_ops.square(n_a.mu - n_b.mu) / (two * s_b_squared) + half * (ratio - one - math_ops.log(ratio)))
apache-2.0
lavjain/incubator-hawq
tools/bin/gppylib/gpMgmttest/__init__.py
12
3044
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import unittest2 as unittest import time class GpMgmtTestRunner(unittest.TextTestRunner): def _makeResult(self): return GpMgmtTextTestResult(self.stream, self.descriptions, self.verbosity) class GpMgmtTextTestResult(unittest.TextTestResult): def __init__(self, stream, descriptions, verbosity): super(GpMgmtTextTestResult, self).__init__(stream, descriptions, verbosity) self.verbosity = verbosity self.startTime = 0 def getDescription(self, test): case_name, full_name = test.__str__().split() suite_name, class_name = full_name.strip('()').rsplit('.',1) if self.verbosity > 1: if test.shortDescription(): return 'Test Suite Name|%s|Test Case Name|%s|Test Details|%s' % (suite_name, case_name, test.shortDescription()) else: return 'Test Suite Name|%s|Test Case Name|%s|Test Details|' % (suite_name, case_name) def startTest(self, test): super(GpMgmtTextTestResult, self).startTest(test) self.startTime = test.start_time = time.time() def addSuccess(self, test): test.end_time = time.time() self._show_run_time() self.stream.write('|Test Status|') super(GpMgmtTextTestResult, self).addSuccess(test) def addError(self, test, err): test.end_time = time.time() self._show_run_time() self.stream.write('|Test Status|') super(GpMgmtTextTestResult, self).addError(test, err) def addFailure(self, test, err): test.end_time = time.time() self._show_run_time() self.stream.write('|Test Status|') super(GpMgmtTextTestResult, self).addFailure(test, err) def addSkip(self, test, err): self._show_run_time() self.stream.write('|Test Status|') super(GpMgmtTextTestResult, self).addSkip(test, err) def addExpectedFailure(self, test, err): self.end_time = time.time() self._show_run_time() self.stream.write('|Test Status|') super(GpMgmtTextTestResult, self).addExpectedFailure(test, err) def _show_run_time(self): etime = time.time() elapsed = etime - self.startTime self.stream.write('(%4.2f ms)' % (elapsed*1000))
apache-2.0
hornn/interviews
tools/bin/gppylib/gp_dbid.py
9
4596
#!/usr/bin/env python # Line too long - pylint: disable=C0301 # Invalid name - pylint: disable=C0103 """ gp_dbid.py Copyright (c) EMC/Greenplum Inc 2011. All Rights Reserved. """ import re import os, stat class DummyLogger: def info(self, msg): pass def debug(self, msg): pass DBID_RE = re.compile(r"dbid\s*=\s*(\d+)") STANDBY_DBID_RE = re.compile(r"standby_dbid\s*=\s*(\d+)") class GpDbidFile: """ Used by gpstart, gpinitstandby, gpactivatestandby and indirectly by gpmigrator via gpsetdbid.py to manage the gp_dbid file. """ def __init__(self, datadir, do_read=False, logger=None): """ Initialize path to gp_dbid file and reset values. Log subsequent activity using specified logger and if do_read is True, immediately attempt to read values. """ self.datadir = datadir self.logger = logger or DummyLogger() self.filepath = os.path.join(self.datadir, 'gp_dbid') self.dbid = None self.standby_dbid = None if do_read: self.read_gp_dbid() def read_gp_dbid(self): """ Open the gp_dbid file and parse its contents. """ INFO = self.logger.info INFO('%s - read_gp_dbid' % self.filepath) with open(self.filepath) as f: self.parse(f) def parse(self, f): """ Parse f, looking for matching dbid and standby_dbid expressions and ignoring all other lines. Assigns dbid and/or standby_dbid to observed values, converting matched values from strings to integers. """ INFO = self.logger.info DEBUG = self.logger.debug self.dbid = None self.standby_dbid = None for line in f: line = line.strip() DEBUG('parse: %s' % line) m = re.match(DBID_RE, line) if m: self.dbid = int(m.group(1)) INFO('match dbid: %d' % self.dbid) m = re.match(STANDBY_DBID_RE, line) if m: self.standby_dbid = int(m.group(1)) INFO('match standby_dbid: %d' % self.standby_dbid) assert self.dbid is not None def format(self, f): """ Generate gp_dbid contents based on dbid and standby_dbid values """ INFO = self.logger.info f.write("# Greenplum Database identifier for this master/segment.\n") f.write("# Do not change the contents of this file.\n") f.write('dbid = %d\n' % self.dbid) INFO('wrote dbid: %d' % self.dbid) if self.standby_dbid: f.write('standby_dbid = %d\n' % self.standby_dbid) INFO('wrote standby_dbid: %d' % self.standby_dbid) def write_gp_dbid(self): """ Create or replace gp_dbid file with current values, changing permissions of the new file when done and verifying by re-reading the file contents and checking the values read match desired values """ INFO = self.logger.info INFO('%s - write_gp_dbid' % self.filepath) if os.path.exists(self.filepath): INFO('found existing file') os.remove(self.filepath) INFO('removed existing file') self.logger.info('opening new file') with open(self.filepath, 'w') as f: self.format(f) INFO('setting read only') os.chmod(self.filepath, stat.S_IRUSR) # user read permissions (0400) INFO('verifying file') v = GpDbidFile(self.datadir, do_read=True) assert self.dbid == v.dbid assert self.standby_dbid == v.standby_dbid def writeGpDbidFile(directory, dbid, logger=None): """ Writes the gp_dbid file to the given directory, marking it as for the given dbid. This method may be deprecating. See comments in CR-2806. """ d = GpDbidFile(directory, logger=logger) d.dbid = dbid d.write_gp_dbid() # # trivial unit test # if __name__ == '__main__': import copy, shutil import unittest2 as unittest TESTDIR = 'test_gp_dbid1' class MyTestCase(unittest.TestCase): def test1(self): d = GpDbidFile(TESTDIR) d2 = copy.copy(d) d.dbid = 10 d.write_gp_dbid() d2.read_gp_dbid() assert d.dbid == d2.dbid assert d.standby_dbid == d2.standby_dbid if os.path.exists(TESTDIR): shutil.rmtree(TESTDIR) os.mkdir(TESTDIR) unittest.main() shutil.rmtree(TESTDIR)
apache-2.0
Jionglun/2015cd_midterm
static/Brython3.1.1-20150328-091302/Lib/logging/__init__.py
733
66279
# Copyright 2001-2013 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. """ Logging package for Python. Based on PEP 282 and comments thereto in comp.lang.python. Copyright (C) 2001-2013 Vinay Sajip. All Rights Reserved. To use, simply 'import logging' and log away! """ import sys, os, time, io, traceback, warnings, weakref from string import Template __all__ = ['BASIC_FORMAT', 'BufferingFormatter', 'CRITICAL', 'DEBUG', 'ERROR', 'FATAL', 'FileHandler', 'Filter', 'Formatter', 'Handler', 'INFO', 'LogRecord', 'Logger', 'LoggerAdapter', 'NOTSET', 'NullHandler', 'StreamHandler', 'WARN', 'WARNING', 'addLevelName', 'basicConfig', 'captureWarnings', 'critical', 'debug', 'disable', 'error', 'exception', 'fatal', 'getLevelName', 'getLogger', 'getLoggerClass', 'info', 'log', 'makeLogRecord', 'setLoggerClass', 'warn', 'warning', 'getLogRecordFactory', 'setLogRecordFactory', 'lastResort'] try: import threading except ImportError: #pragma: no cover threading = None __author__ = "Vinay Sajip <vinay_sajip@red-dove.com>" __status__ = "production" __version__ = "0.5.1.2" __date__ = "07 February 2010" #--------------------------------------------------------------------------- # Miscellaneous module data #--------------------------------------------------------------------------- # # _srcfile is used when walking the stack to check when we've got the first # caller stack frame. # if hasattr(sys, 'frozen'): #support for py2exe _srcfile = "logging%s__init__%s" % (os.sep, __file__[-4:]) else: _srcfile = __file__ _srcfile = os.path.normcase(_srcfile) if hasattr(sys, '_getframe'): currentframe = lambda: sys._getframe(3) else: #pragma: no cover def currentframe(): """Return the frame object for the caller's stack frame.""" try: raise Exception except: return sys.exc_info()[2].tb_frame.f_back # _srcfile is only used in conjunction with sys._getframe(). # To provide compatibility with older versions of Python, set _srcfile # to None if _getframe() is not available; this value will prevent # findCaller() from being called. #if not hasattr(sys, "_getframe"): # _srcfile = None # #_startTime is used as the base when calculating the relative time of events # _startTime = time.time() # #raiseExceptions is used to see if exceptions during handling should be #propagated # raiseExceptions = True # # If you don't want threading information in the log, set this to zero # logThreads = True # # If you don't want multiprocessing information in the log, set this to zero # logMultiprocessing = True # # If you don't want process information in the log, set this to zero # logProcesses = True #--------------------------------------------------------------------------- # Level related stuff #--------------------------------------------------------------------------- # # Default levels and level names, these can be replaced with any positive set # of values having corresponding names. There is a pseudo-level, NOTSET, which # is only really there as a lower limit for user-defined levels. Handlers and # loggers are initialized with NOTSET so that they will log all messages, even # at user-defined levels. # CRITICAL = 50 FATAL = CRITICAL ERROR = 40 WARNING = 30 WARN = WARNING INFO = 20 DEBUG = 10 NOTSET = 0 _levelNames = { CRITICAL : 'CRITICAL', ERROR : 'ERROR', WARNING : 'WARNING', INFO : 'INFO', DEBUG : 'DEBUG', NOTSET : 'NOTSET', 'CRITICAL' : CRITICAL, 'ERROR' : ERROR, 'WARN' : WARNING, 'WARNING' : WARNING, 'INFO' : INFO, 'DEBUG' : DEBUG, 'NOTSET' : NOTSET, } def getLevelName(level): """ Return the textual representation of logging level 'level'. If the level is one of the predefined levels (CRITICAL, ERROR, WARNING, INFO, DEBUG) then you get the corresponding string. If you have associated levels with names using addLevelName then the name you have associated with 'level' is returned. If a numeric value corresponding to one of the defined levels is passed in, the corresponding string representation is returned. Otherwise, the string "Level %s" % level is returned. """ return _levelNames.get(level, ("Level %s" % level)) def addLevelName(level, levelName): """ Associate 'levelName' with 'level'. This is used when converting levels to text during message formatting. """ _acquireLock() try: #unlikely to cause an exception, but you never know... _levelNames[level] = levelName _levelNames[levelName] = level finally: _releaseLock() def _checkLevel(level): if isinstance(level, int): rv = level elif str(level) == level: if level not in _levelNames: raise ValueError("Unknown level: %r" % level) rv = _levelNames[level] else: raise TypeError("Level not an integer or a valid string: %r" % level) return rv #--------------------------------------------------------------------------- # Thread-related stuff #--------------------------------------------------------------------------- # #_lock is used to serialize access to shared data structures in this module. #This needs to be an RLock because fileConfig() creates and configures #Handlers, and so might arbitrary user threads. Since Handler code updates the #shared dictionary _handlers, it needs to acquire the lock. But if configuring, #the lock would already have been acquired - so we need an RLock. #The same argument applies to Loggers and Manager.loggerDict. # if threading: _lock = threading.RLock() else: #pragma: no cover _lock = None def _acquireLock(): """ Acquire the module-level lock for serializing access to shared data. This should be released with _releaseLock(). """ if _lock: _lock.acquire() def _releaseLock(): """ Release the module-level lock acquired by calling _acquireLock(). """ if _lock: _lock.release() #--------------------------------------------------------------------------- # The logging record #--------------------------------------------------------------------------- class LogRecord(object): """ A LogRecord instance represents an event being logged. LogRecord instances are created every time something is logged. They contain all the information pertinent to the event being logged. The main information passed in is in msg and args, which are combined using str(msg) % args to create the message field of the record. The record also includes information such as when the record was created, the source line where the logging call was made, and any exception information to be logged. """ def __init__(self, name, level, pathname, lineno, msg, args, exc_info, func=None, sinfo=None, **kwargs): """ Initialize a logging record with interesting information. """ ct = time.time() self.name = name self.msg = msg # # The following statement allows passing of a dictionary as a sole # argument, so that you can do something like # logging.debug("a %(a)d b %(b)s", {'a':1, 'b':2}) # Suggested by Stefan Behnel. # Note that without the test for args[0], we get a problem because # during formatting, we test to see if the arg is present using # 'if self.args:'. If the event being logged is e.g. 'Value is %d' # and if the passed arg fails 'if self.args:' then no formatting # is done. For example, logger.warning('Value is %d', 0) would log # 'Value is %d' instead of 'Value is 0'. # For the use case of passing a dictionary, this should not be a # problem. if args and len(args) == 1 and isinstance(args[0], dict) and args[0]: args = args[0] self.args = args self.levelname = getLevelName(level) self.levelno = level self.pathname = pathname try: self.filename = os.path.basename(pathname) self.module = os.path.splitext(self.filename)[0] except (TypeError, ValueError, AttributeError): self.filename = pathname self.module = "Unknown module" self.exc_info = exc_info self.exc_text = None # used to cache the traceback text self.stack_info = sinfo self.lineno = lineno self.funcName = func self.created = ct self.msecs = (ct - int(ct)) * 1000 self.relativeCreated = (self.created - _startTime) * 1000 if logThreads and threading: self.thread = threading.get_ident() self.threadName = threading.current_thread().name else: # pragma: no cover self.thread = None self.threadName = None if not logMultiprocessing: # pragma: no cover self.processName = None else: self.processName = 'MainProcess' mp = sys.modules.get('multiprocessing') if mp is not None: # Errors may occur if multiprocessing has not finished loading # yet - e.g. if a custom import hook causes third-party code # to run when multiprocessing calls import. See issue 8200 # for an example try: self.processName = mp.current_process().name except Exception: #pragma: no cover pass if logProcesses and hasattr(os, 'getpid'): self.process = os.getpid() else: self.process = None def __str__(self): return '<LogRecord: %s, %s, %s, %s, "%s">'%(self.name, self.levelno, self.pathname, self.lineno, self.msg) def getMessage(self): """ Return the message for this LogRecord. Return the message for this LogRecord after merging any user-supplied arguments with the message. """ msg = str(self.msg) if self.args: msg = msg % self.args return msg # # Determine which class to use when instantiating log records. # _logRecordFactory = LogRecord def setLogRecordFactory(factory): """ Set the factory to be used when instantiating a log record. :param factory: A callable which will be called to instantiate a log record. """ global _logRecordFactory _logRecordFactory = factory def getLogRecordFactory(): """ Return the factory to be used when instantiating a log record. """ return _logRecordFactory def makeLogRecord(dict): """ Make a LogRecord whose attributes are defined by the specified dictionary, This function is useful for converting a logging event received over a socket connection (which is sent as a dictionary) into a LogRecord instance. """ rv = _logRecordFactory(None, None, "", 0, "", (), None, None) rv.__dict__.update(dict) return rv #--------------------------------------------------------------------------- # Formatter classes and functions #--------------------------------------------------------------------------- class PercentStyle(object): default_format = '%(message)s' asctime_format = '%(asctime)s' asctime_search = '%(asctime)' def __init__(self, fmt): self._fmt = fmt or self.default_format def usesTime(self): return self._fmt.find(self.asctime_search) >= 0 def format(self, record): return self._fmt % record.__dict__ class StrFormatStyle(PercentStyle): default_format = '{message}' asctime_format = '{asctime}' asctime_search = '{asctime' def format(self, record): return self._fmt.format(**record.__dict__) class StringTemplateStyle(PercentStyle): default_format = '${message}' asctime_format = '${asctime}' asctime_search = '${asctime}' def __init__(self, fmt): self._fmt = fmt or self.default_format self._tpl = Template(self._fmt) def usesTime(self): fmt = self._fmt return fmt.find('$asctime') >= 0 or fmt.find(self.asctime_format) >= 0 def format(self, record): return self._tpl.substitute(**record.__dict__) _STYLES = { '%': PercentStyle, '{': StrFormatStyle, '$': StringTemplateStyle } class Formatter(object): """ Formatter instances are used to convert a LogRecord to text. Formatters need to know how a LogRecord is constructed. They are responsible for converting a LogRecord to (usually) a string which can be interpreted by either a human or an external system. The base Formatter allows a formatting string to be specified. If none is supplied, the default value of "%s(message)" is used. The Formatter can be initialized with a format string which makes use of knowledge of the LogRecord attributes - e.g. the default value mentioned above makes use of the fact that the user's message and arguments are pre- formatted into a LogRecord's message attribute. Currently, the useful attributes in a LogRecord are described by: %(name)s Name of the logger (logging channel) %(levelno)s Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL) %(levelname)s Text logging level for the message ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL") %(pathname)s Full pathname of the source file where the logging call was issued (if available) %(filename)s Filename portion of pathname %(module)s Module (name portion of filename) %(lineno)d Source line number where the logging call was issued (if available) %(funcName)s Function name %(created)f Time when the LogRecord was created (time.time() return value) %(asctime)s Textual time when the LogRecord was created %(msecs)d Millisecond portion of the creation time %(relativeCreated)d Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded (typically at application startup time) %(thread)d Thread ID (if available) %(threadName)s Thread name (if available) %(process)d Process ID (if available) %(message)s The result of record.getMessage(), computed just as the record is emitted """ converter = time.localtime def __init__(self, fmt=None, datefmt=None, style='%'): """ Initialize the formatter with specified format strings. Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with the optional datefmt argument (if omitted, you get the ISO8601 format). Use a style parameter of '%', '{' or '$' to specify that you want to use one of %-formatting, :meth:`str.format` (``{}``) formatting or :class:`string.Template` formatting in your format string. .. versionchanged: 3.2 Added the ``style`` parameter. """ if style not in _STYLES: raise ValueError('Style must be one of: %s' % ','.join( _STYLES.keys())) self._style = _STYLES[style](fmt) self._fmt = self._style._fmt self.datefmt = datefmt default_time_format = '%Y-%m-%d %H:%M:%S' default_msec_format = '%s,%03d' def formatTime(self, record, datefmt=None): """ Return the creation time of the specified LogRecord as formatted text. This method should be called from format() by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behaviour is as follows: if datefmt (a string) is specified, it is used with time.strftime() to format the creation time of the record. Otherwise, the ISO8601 format is used. The resulting string is returned. This function uses a user-configurable function to convert the creation time to a tuple. By default, time.localtime() is used; to change this for a particular formatter instance, set the 'converter' attribute to a function with the same signature as time.localtime() or time.gmtime(). To change it for all formatters, for example if you want all logging times to be shown in GMT, set the 'converter' attribute in the Formatter class. """ ct = self.converter(record.created) if datefmt: s = time.strftime(datefmt, ct) else: t = time.strftime(self.default_time_format, ct) s = self.default_msec_format % (t, record.msecs) return s def formatException(self, ei): """ Format and return the specified exception information as a string. This default implementation just uses traceback.print_exception() """ sio = io.StringIO() tb = ei[2] # See issues #9427, #1553375. Commented out for now. #if getattr(self, 'fullstack', False): # traceback.print_stack(tb.tb_frame.f_back, file=sio) traceback.print_exception(ei[0], ei[1], tb, None, sio) s = sio.getvalue() sio.close() if s[-1:] == "\n": s = s[:-1] return s def usesTime(self): """ Check if the format uses the creation time of the record. """ return self._style.usesTime() def formatMessage(self, record): return self._style.format(record) def formatStack(self, stack_info): """ This method is provided as an extension point for specialized formatting of stack information. The input data is a string as returned from a call to :func:`traceback.print_stack`, but with the last trailing newline removed. The base implementation just returns the value passed in. """ return stack_info def format(self, record): """ Format the specified record as text. The record's attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message. """ record.message = record.getMessage() if self.usesTime(): record.asctime = self.formatTime(record, self.datefmt) s = self.formatMessage(record) if record.exc_info: # Cache the traceback text to avoid converting it multiple times # (it's constant anyway) if not record.exc_text: record.exc_text = self.formatException(record.exc_info) if record.exc_text: if s[-1:] != "\n": s = s + "\n" s = s + record.exc_text if record.stack_info: if s[-1:] != "\n": s = s + "\n" s = s + self.formatStack(record.stack_info) return s # # The default formatter to use when no other is specified # _defaultFormatter = Formatter() class BufferingFormatter(object): """ A formatter suitable for formatting a number of records. """ def __init__(self, linefmt=None): """ Optionally specify a formatter which will be used to format each individual record. """ if linefmt: self.linefmt = linefmt else: self.linefmt = _defaultFormatter def formatHeader(self, records): """ Return the header string for the specified records. """ return "" def formatFooter(self, records): """ Return the footer string for the specified records. """ return "" def format(self, records): """ Format the specified records and return the result as a string. """ rv = "" if len(records) > 0: rv = rv + self.formatHeader(records) for record in records: rv = rv + self.linefmt.format(record) rv = rv + self.formatFooter(records) return rv #--------------------------------------------------------------------------- # Filter classes and functions #--------------------------------------------------------------------------- class Filter(object): """ Filter instances are used to perform arbitrary filtering of LogRecords. Loggers and Handlers can optionally use Filter instances to filter records as desired. The base filter class only allows events which are below a certain point in the logger hierarchy. For example, a filter initialized with "A.B" will allow events logged by loggers "A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If initialized with the empty string, all events are passed. """ def __init__(self, name=''): """ Initialize a filter. Initialize with the name of the logger which, together with its children, will have its events allowed through the filter. If no name is specified, allow every event. """ self.name = name self.nlen = len(name) def filter(self, record): """ Determine if the specified record is to be logged. Is the specified record to be logged? Returns 0 for no, nonzero for yes. If deemed appropriate, the record may be modified in-place. """ if self.nlen == 0: return True elif self.name == record.name: return True elif record.name.find(self.name, 0, self.nlen) != 0: return False return (record.name[self.nlen] == ".") class Filterer(object): """ A base class for loggers and handlers which allows them to share common code. """ def __init__(self): """ Initialize the list of filters to be an empty list. """ self.filters = [] def addFilter(self, filter): """ Add the specified filter to this handler. """ if not (filter in self.filters): self.filters.append(filter) def removeFilter(self, filter): """ Remove the specified filter from this handler. """ if filter in self.filters: self.filters.remove(filter) def filter(self, record): """ Determine if a record is loggable by consulting all the filters. The default is to allow the record to be logged; any filter can veto this and the record is then dropped. Returns a zero value if a record is to be dropped, else non-zero. .. versionchanged: 3.2 Allow filters to be just callables. """ rv = True for f in self.filters: if hasattr(f, 'filter'): result = f.filter(record) else: result = f(record) # assume callable - will raise if not if not result: rv = False break return rv #--------------------------------------------------------------------------- # Handler classes and functions #--------------------------------------------------------------------------- _handlers = weakref.WeakValueDictionary() #map of handler names to handlers _handlerList = [] # added to allow handlers to be removed in reverse of order initialized def _removeHandlerRef(wr): """ Remove a handler reference from the internal cleanup list. """ # This function can be called during module teardown, when globals are # set to None. If _acquireLock is None, assume this is the case and do # nothing. if (_acquireLock is not None and _handlerList is not None and _releaseLock is not None): _acquireLock() try: if wr in _handlerList: _handlerList.remove(wr) finally: _releaseLock() def _addHandlerRef(handler): """ Add a handler to the internal cleanup list using a weak reference. """ _acquireLock() try: _handlerList.append(weakref.ref(handler, _removeHandlerRef)) finally: _releaseLock() class Handler(Filterer): """ Handler instances dispatch logging events to specific destinations. The base handler class. Acts as a placeholder which defines the Handler interface. Handlers can optionally use Formatter instances to format records as desired. By default, no formatter is specified; in this case, the 'raw' message as determined by record.message is logged. """ def __init__(self, level=NOTSET): """ Initializes the instance - basically setting the formatter to None and the filter list to empty. """ Filterer.__init__(self) self._name = None self.level = _checkLevel(level) self.formatter = None # Add the handler to the global _handlerList (for cleanup on shutdown) _addHandlerRef(self) self.createLock() def get_name(self): return self._name def set_name(self, name): _acquireLock() try: if self._name in _handlers: del _handlers[self._name] self._name = name if name: _handlers[name] = self finally: _releaseLock() name = property(get_name, set_name) def createLock(self): """ Acquire a thread lock for serializing access to the underlying I/O. """ if threading: self.lock = threading.RLock() else: #pragma: no cover self.lock = None def acquire(self): """ Acquire the I/O thread lock. """ if self.lock: self.lock.acquire() def release(self): """ Release the I/O thread lock. """ if self.lock: self.lock.release() def setLevel(self, level): """ Set the logging level of this handler. level must be an int or a str. """ self.level = _checkLevel(level) def format(self, record): """ Format the specified record. If a formatter is set, use it. Otherwise, use the default formatter for the module. """ if self.formatter: fmt = self.formatter else: fmt = _defaultFormatter return fmt.format(record) def emit(self, record): """ Do whatever it takes to actually log the specified logging record. This version is intended to be implemented by subclasses and so raises a NotImplementedError. """ raise NotImplementedError('emit must be implemented ' 'by Handler subclasses') def handle(self, record): """ Conditionally emit the specified logging record. Emission depends on filters which may have been added to the handler. Wrap the actual emission of the record with acquisition/release of the I/O thread lock. Returns whether the filter passed the record for emission. """ rv = self.filter(record) if rv: self.acquire() try: self.emit(record) finally: self.release() return rv def setFormatter(self, fmt): """ Set the formatter for this handler. """ self.formatter = fmt def flush(self): """ Ensure all logging output has been flushed. This version does nothing and is intended to be implemented by subclasses. """ pass def close(self): """ Tidy up any resources used by the handler. This version removes the handler from an internal map of handlers, _handlers, which is used for handler lookup by name. Subclasses should ensure that this gets called from overridden close() methods. """ #get the module data lock, as we're updating a shared structure. _acquireLock() try: #unlikely to raise an exception, but you never know... if self._name and self._name in _handlers: del _handlers[self._name] finally: _releaseLock() def handleError(self, record): """ Handle errors which occur during an emit() call. This method should be called from handlers when an exception is encountered during an emit() call. If raiseExceptions is false, exceptions get silently ignored. This is what is mostly wanted for a logging system - most users will not care about errors in the logging system, they are more interested in application errors. You could, however, replace this with a custom handler if you wish. The record which was being processed is passed in to this method. """ if raiseExceptions and sys.stderr: # see issue 13807 ei = sys.exc_info() try: traceback.print_exception(ei[0], ei[1], ei[2], None, sys.stderr) sys.stderr.write('Logged from file %s, line %s\n' % ( record.filename, record.lineno)) except IOError: #pragma: no cover pass # see issue 5971 finally: del ei class StreamHandler(Handler): """ A handler class which writes logging records, appropriately formatted, to a stream. Note that this class does not close the stream, as sys.stdout or sys.stderr may be used. """ terminator = '\n' def __init__(self, stream=None): """ Initialize the handler. If stream is not specified, sys.stderr is used. """ Handler.__init__(self) if stream is None: stream = sys.stderr self.stream = stream def flush(self): """ Flushes the stream. """ self.acquire() try: if self.stream and hasattr(self.stream, "flush"): self.stream.flush() finally: self.release() def emit(self, record): """ Emit a record. If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline. If exception information is present, it is formatted using traceback.print_exception and appended to the stream. If the stream has an 'encoding' attribute, it is used to determine how to do the output to the stream. """ try: msg = self.format(record) stream = self.stream stream.write(msg) stream.write(self.terminator) self.flush() except (KeyboardInterrupt, SystemExit): #pragma: no cover raise except: self.handleError(record) class FileHandler(StreamHandler): """ A handler class which writes formatted logging records to disk files. """ def __init__(self, filename, mode='a', encoding=None, delay=False): """ Open the specified file and use it as the stream for logging. """ #keep the absolute path, otherwise derived classes which use this #may come a cropper when the current directory changes self.baseFilename = os.path.abspath(filename) self.mode = mode self.encoding = encoding self.delay = delay if delay: #We don't open the stream, but we still need to call the #Handler constructor to set level, formatter, lock etc. Handler.__init__(self) self.stream = None else: StreamHandler.__init__(self, self._open()) def close(self): """ Closes the stream. """ self.acquire() try: if self.stream: self.flush() if hasattr(self.stream, "close"): self.stream.close() StreamHandler.close(self) self.stream = None finally: self.release() def _open(self): """ Open the current base file with the (original) mode and encoding. Return the resulting stream. """ return open(self.baseFilename, self.mode, encoding=self.encoding) def emit(self, record): """ Emit a record. If the stream was not opened because 'delay' was specified in the constructor, open it before calling the superclass's emit. """ if self.stream is None: self.stream = self._open() StreamHandler.emit(self, record) class _StderrHandler(StreamHandler): """ This class is like a StreamHandler using sys.stderr, but always uses whatever sys.stderr is currently set to rather than the value of sys.stderr at handler construction time. """ def __init__(self, level=NOTSET): """ Initialize the handler. """ Handler.__init__(self, level) @property def stream(self): return sys.stderr _defaultLastResort = _StderrHandler(WARNING) lastResort = _defaultLastResort #--------------------------------------------------------------------------- # Manager classes and functions #--------------------------------------------------------------------------- class PlaceHolder(object): """ PlaceHolder instances are used in the Manager logger hierarchy to take the place of nodes for which no loggers have been defined. This class is intended for internal use only and not as part of the public API. """ def __init__(self, alogger): """ Initialize with the specified logger being a child of this placeholder. """ self.loggerMap = { alogger : None } def append(self, alogger): """ Add the specified logger as a child of this placeholder. """ if alogger not in self.loggerMap: self.loggerMap[alogger] = None # # Determine which class to use when instantiating loggers. # _loggerClass = None def setLoggerClass(klass): """ Set the class to be used when instantiating a logger. The class should define __init__() such that only a name argument is required, and the __init__() should call Logger.__init__() """ if klass != Logger: if not issubclass(klass, Logger): raise TypeError("logger not derived from logging.Logger: " + klass.__name__) global _loggerClass _loggerClass = klass def getLoggerClass(): """ Return the class to be used when instantiating a logger. """ return _loggerClass class Manager(object): """ There is [under normal circumstances] just one Manager instance, which holds the hierarchy of loggers. """ def __init__(self, rootnode): """ Initialize the manager with the root node of the logger hierarchy. """ self.root = rootnode self.disable = 0 self.emittedNoHandlerWarning = False self.loggerDict = {} self.loggerClass = None self.logRecordFactory = None def getLogger(self, name): """ Get a logger with the specified name (channel name), creating it if it doesn't yet exist. This name is a dot-separated hierarchical name, such as "a", "a.b", "a.b.c" or similar. If a PlaceHolder existed for the specified name [i.e. the logger didn't exist but a child of it did], replace it with the created logger and fix up the parent/child references which pointed to the placeholder to now point to the logger. """ rv = None if not isinstance(name, str): raise TypeError('A logger name must be a string') _acquireLock() try: if name in self.loggerDict: rv = self.loggerDict[name] if isinstance(rv, PlaceHolder): ph = rv rv = (self.loggerClass or _loggerClass)(name) rv.manager = self self.loggerDict[name] = rv self._fixupChildren(ph, rv) self._fixupParents(rv) else: rv = (self.loggerClass or _loggerClass)(name) rv.manager = self self.loggerDict[name] = rv self._fixupParents(rv) finally: _releaseLock() return rv def setLoggerClass(self, klass): """ Set the class to be used when instantiating a logger with this Manager. """ if klass != Logger: if not issubclass(klass, Logger): raise TypeError("logger not derived from logging.Logger: " + klass.__name__) self.loggerClass = klass def setLogRecordFactory(self, factory): """ Set the factory to be used when instantiating a log record with this Manager. """ self.logRecordFactory = factory def _fixupParents(self, alogger): """ Ensure that there are either loggers or placeholders all the way from the specified logger to the root of the logger hierarchy. """ name = alogger.name i = name.rfind(".") rv = None while (i > 0) and not rv: substr = name[:i] if substr not in self.loggerDict: self.loggerDict[substr] = PlaceHolder(alogger) else: obj = self.loggerDict[substr] if isinstance(obj, Logger): rv = obj else: assert isinstance(obj, PlaceHolder) obj.append(alogger) i = name.rfind(".", 0, i - 1) if not rv: rv = self.root alogger.parent = rv def _fixupChildren(self, ph, alogger): """ Ensure that children of the placeholder ph are connected to the specified logger. """ name = alogger.name namelen = len(name) for c in ph.loggerMap.keys(): #The if means ... if not c.parent.name.startswith(nm) if c.parent.name[:namelen] != name: alogger.parent = c.parent c.parent = alogger #--------------------------------------------------------------------------- # Logger classes and functions #--------------------------------------------------------------------------- class Logger(Filterer): """ Instances of the Logger class represent a single logging channel. A "logging channel" indicates an area of an application. Exactly how an "area" is defined is up to the application developer. Since an application can have any number of areas, logging channels are identified by a unique string. Application areas can be nested (e.g. an area of "input processing" might include sub-areas "read CSV files", "read XLS files" and "read Gnumeric files"). To cater for this natural nesting, channel names are organized into a namespace hierarchy where levels are separated by periods, much like the Java or Python package namespace. So in the instance given above, channel names might be "input" for the upper level, and "input.csv", "input.xls" and "input.gnu" for the sub-levels. There is no arbitrary limit to the depth of nesting. """ def __init__(self, name, level=NOTSET): """ Initialize the logger with a name and an optional level. """ Filterer.__init__(self) self.name = name self.level = _checkLevel(level) self.parent = None self.propagate = True self.handlers = [] self.disabled = False def setLevel(self, level): """ Set the logging level of this logger. level must be an int or a str. """ self.level = _checkLevel(level) def debug(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'DEBUG'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.debug("Houston, we have a %s", "thorny problem", exc_info=1) """ if self.isEnabledFor(DEBUG): self._log(DEBUG, msg, args, **kwargs) def info(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'INFO'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.info("Houston, we have a %s", "interesting problem", exc_info=1) """ if self.isEnabledFor(INFO): self._log(INFO, msg, args, **kwargs) def warning(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'WARNING'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.warning("Houston, we have a %s", "bit of a problem", exc_info=1) """ if self.isEnabledFor(WARNING): self._log(WARNING, msg, args, **kwargs) def warn(self, msg, *args, **kwargs): warnings.warn("The 'warn' method is deprecated, " "use 'warning' instead", DeprecationWarning, 2) self.warning(msg, *args, **kwargs) def error(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'ERROR'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.error("Houston, we have a %s", "major problem", exc_info=1) """ if self.isEnabledFor(ERROR): self._log(ERROR, msg, args, **kwargs) def exception(self, msg, *args, **kwargs): """ Convenience method for logging an ERROR with exception information. """ kwargs['exc_info'] = True self.error(msg, *args, **kwargs) def critical(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'CRITICAL'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.critical("Houston, we have a %s", "major disaster", exc_info=1) """ if self.isEnabledFor(CRITICAL): self._log(CRITICAL, msg, args, **kwargs) fatal = critical def log(self, level, msg, *args, **kwargs): """ Log 'msg % args' with the integer severity 'level'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.log(level, "We have a %s", "mysterious problem", exc_info=1) """ if not isinstance(level, int): if raiseExceptions: raise TypeError("level must be an integer") else: return if self.isEnabledFor(level): self._log(level, msg, args, **kwargs) def findCaller(self, stack_info=False): """ Find the stack frame of the caller so that we can note the source file name, line number and function name. """ f = currentframe() #On some versions of IronPython, currentframe() returns None if #IronPython isn't run with -X:Frames. if f is not None: f = f.f_back rv = "(unknown file)", 0, "(unknown function)", None while hasattr(f, "f_code"): co = f.f_code filename = os.path.normcase(co.co_filename) if filename == _srcfile: f = f.f_back continue sinfo = None if stack_info: sio = io.StringIO() sio.write('Stack (most recent call last):\n') traceback.print_stack(f, file=sio) sinfo = sio.getvalue() if sinfo[-1] == '\n': sinfo = sinfo[:-1] sio.close() rv = (co.co_filename, f.f_lineno, co.co_name, sinfo) break return rv def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None): """ A factory method which can be overridden in subclasses to create specialized LogRecords. """ rv = _logRecordFactory(name, level, fn, lno, msg, args, exc_info, func, sinfo) if extra is not None: for key in extra: if (key in ["message", "asctime"]) or (key in rv.__dict__): raise KeyError("Attempt to overwrite %r in LogRecord" % key) rv.__dict__[key] = extra[key] return rv def _log(self, level, msg, args, exc_info=None, extra=None, stack_info=False): """ Low-level logging routine which creates a LogRecord and then calls all the handlers of this logger to handle the record. """ sinfo = None if _srcfile: #IronPython doesn't track Python frames, so findCaller raises an #exception on some versions of IronPython. We trap it here so that #IronPython can use logging. try: fn, lno, func, sinfo = self.findCaller(stack_info) except ValueError: # pragma: no cover fn, lno, func = "(unknown file)", 0, "(unknown function)" else: # pragma: no cover fn, lno, func = "(unknown file)", 0, "(unknown function)" if exc_info: if not isinstance(exc_info, tuple): exc_info = sys.exc_info() record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info, func, extra, sinfo) self.handle(record) def handle(self, record): """ Call the handlers for the specified record. This method is used for unpickled records received from a socket, as well as those created locally. Logger-level filtering is applied. """ if (not self.disabled) and self.filter(record): self.callHandlers(record) def addHandler(self, hdlr): """ Add the specified handler to this logger. """ _acquireLock() try: if not (hdlr in self.handlers): self.handlers.append(hdlr) finally: _releaseLock() def removeHandler(self, hdlr): """ Remove the specified handler from this logger. """ _acquireLock() try: if hdlr in self.handlers: self.handlers.remove(hdlr) finally: _releaseLock() def hasHandlers(self): """ See if this logger has any handlers configured. Loop through all handlers for this logger and its parents in the logger hierarchy. Return True if a handler was found, else False. Stop searching up the hierarchy whenever a logger with the "propagate" attribute set to zero is found - that will be the last logger which is checked for the existence of handlers. """ c = self rv = False while c: if c.handlers: rv = True break if not c.propagate: break else: c = c.parent return rv def callHandlers(self, record): """ Pass a record to all relevant handlers. Loop through all handlers for this logger and its parents in the logger hierarchy. If no handler was found, output a one-off error message to sys.stderr. Stop searching up the hierarchy whenever a logger with the "propagate" attribute set to zero is found - that will be the last logger whose handlers are called. """ c = self found = 0 while c: for hdlr in c.handlers: found = found + 1 if record.levelno >= hdlr.level: hdlr.handle(record) if not c.propagate: c = None #break out else: c = c.parent if (found == 0): if lastResort: if record.levelno >= lastResort.level: lastResort.handle(record) elif raiseExceptions and not self.manager.emittedNoHandlerWarning: sys.stderr.write("No handlers could be found for logger" " \"%s\"\n" % self.name) self.manager.emittedNoHandlerWarning = True def getEffectiveLevel(self): """ Get the effective level for this logger. Loop through this logger and its parents in the logger hierarchy, looking for a non-zero logging level. Return the first one found. """ logger = self while logger: if logger.level: return logger.level logger = logger.parent return NOTSET def isEnabledFor(self, level): """ Is this logger enabled for level 'level'? """ if self.manager.disable >= level: return False return level >= self.getEffectiveLevel() def getChild(self, suffix): """ Get a logger which is a descendant to this one. This is a convenience method, such that logging.getLogger('abc').getChild('def.ghi') is the same as logging.getLogger('abc.def.ghi') It's useful, for example, when the parent logger is named using __name__ rather than a literal string. """ if self.root is not self: suffix = '.'.join((self.name, suffix)) return self.manager.getLogger(suffix) class RootLogger(Logger): """ A root logger is not that different to any other logger, except that it must have a logging level and there is only one instance of it in the hierarchy. """ def __init__(self, level): """ Initialize the logger with the name "root". """ Logger.__init__(self, "root", level) _loggerClass = Logger class LoggerAdapter(object): """ An adapter for loggers which makes it easier to specify contextual information in logging output. """ def __init__(self, logger, extra): """ Initialize the adapter with a logger and a dict-like object which provides contextual information. This constructor signature allows easy stacking of LoggerAdapters, if so desired. You can effectively pass keyword arguments as shown in the following example: adapter = LoggerAdapter(someLogger, dict(p1=v1, p2="v2")) """ self.logger = logger self.extra = extra def process(self, msg, kwargs): """ Process the logging message and keyword arguments passed in to a logging call to insert contextual information. You can either manipulate the message itself, the keyword args or both. Return the message and kwargs modified (or not) to suit your needs. Normally, you'll only need to override this one method in a LoggerAdapter subclass for your specific needs. """ kwargs["extra"] = self.extra return msg, kwargs # # Boilerplate convenience methods # def debug(self, msg, *args, **kwargs): """ Delegate a debug call to the underlying logger. """ self.log(DEBUG, msg, *args, **kwargs) def info(self, msg, *args, **kwargs): """ Delegate an info call to the underlying logger. """ self.log(INFO, msg, *args, **kwargs) def warning(self, msg, *args, **kwargs): """ Delegate a warning call to the underlying logger. """ self.log(WARNING, msg, *args, **kwargs) def warn(self, msg, *args, **kwargs): warnings.warn("The 'warn' method is deprecated, " "use 'warning' instead", DeprecationWarning, 2) self.warning(msg, *args, **kwargs) def error(self, msg, *args, **kwargs): """ Delegate an error call to the underlying logger. """ self.log(ERROR, msg, *args, **kwargs) def exception(self, msg, *args, **kwargs): """ Delegate an exception call to the underlying logger. """ kwargs["exc_info"] = True self.log(ERROR, msg, *args, **kwargs) def critical(self, msg, *args, **kwargs): """ Delegate a critical call to the underlying logger. """ self.log(CRITICAL, msg, *args, **kwargs) def log(self, level, msg, *args, **kwargs): """ Delegate a log call to the underlying logger, after adding contextual information from this adapter instance. """ if self.isEnabledFor(level): msg, kwargs = self.process(msg, kwargs) self.logger._log(level, msg, args, **kwargs) def isEnabledFor(self, level): """ Is this logger enabled for level 'level'? """ if self.logger.manager.disable >= level: return False return level >= self.getEffectiveLevel() def setLevel(self, level): """ Set the specified level on the underlying logger. """ self.logger.setLevel(level) def getEffectiveLevel(self): """ Get the effective level for the underlying logger. """ return self.logger.getEffectiveLevel() def hasHandlers(self): """ See if the underlying logger has any handlers. """ return self.logger.hasHandlers() root = RootLogger(WARNING) Logger.root = root Logger.manager = Manager(Logger.root) #--------------------------------------------------------------------------- # Configuration classes and functions #--------------------------------------------------------------------------- BASIC_FORMAT = "%(levelname)s:%(name)s:%(message)s" def basicConfig(**kwargs): """ Do basic configuration for the logging system. This function does nothing if the root logger already has handlers configured. It is a convenience method intended for use by simple scripts to do one-shot configuration of the logging package. The default behaviour is to create a StreamHandler which writes to sys.stderr, set a formatter using the BASIC_FORMAT format string, and add the handler to the root logger. A number of optional keyword arguments may be specified, which can alter the default behaviour. filename Specifies that a FileHandler be created, using the specified filename, rather than a StreamHandler. filemode Specifies the mode to open the file, if filename is specified (if filemode is unspecified, it defaults to 'a'). format Use the specified format string for the handler. datefmt Use the specified date/time format. style If a format string is specified, use this to specify the type of format string (possible values '%', '{', '$', for %-formatting, :meth:`str.format` and :class:`string.Template` - defaults to '%'). level Set the root logger level to the specified level. stream Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with 'filename' - if both are present, 'stream' is ignored. handlers If specified, this should be an iterable of already created handlers, which will be added to the root handler. Any handler in the list which does not have a formatter assigned will be assigned the formatter created in this function. Note that you could specify a stream created using open(filename, mode) rather than passing the filename and mode in. However, it should be remembered that StreamHandler does not close its stream (since it may be using sys.stdout or sys.stderr), whereas FileHandler closes its stream when the handler is closed. .. versionchanged:: 3.2 Added the ``style`` parameter. .. versionchanged:: 3.3 Added the ``handlers`` parameter. A ``ValueError`` is now thrown for incompatible arguments (e.g. ``handlers`` specified together with ``filename``/``filemode``, or ``filename``/``filemode`` specified together with ``stream``, or ``handlers`` specified together with ``stream``. """ # Add thread safety in case someone mistakenly calls # basicConfig() from multiple threads _acquireLock() try: if len(root.handlers) == 0: handlers = kwargs.get("handlers") if handlers is None: if "stream" in kwargs and "filename" in kwargs: raise ValueError("'stream' and 'filename' should not be " "specified together") else: if "stream" in kwargs or "filename" in kwargs: raise ValueError("'stream' or 'filename' should not be " "specified together with 'handlers'") if handlers is None: filename = kwargs.get("filename") if filename: mode = kwargs.get("filemode", 'a') h = FileHandler(filename, mode) else: stream = kwargs.get("stream") h = StreamHandler(stream) handlers = [h] fs = kwargs.get("format", BASIC_FORMAT) dfs = kwargs.get("datefmt", None) style = kwargs.get("style", '%') fmt = Formatter(fs, dfs, style) for h in handlers: if h.formatter is None: h.setFormatter(fmt) root.addHandler(h) level = kwargs.get("level") if level is not None: root.setLevel(level) finally: _releaseLock() #--------------------------------------------------------------------------- # Utility functions at module level. # Basically delegate everything to the root logger. #--------------------------------------------------------------------------- def getLogger(name=None): """ Return a logger with the specified name, creating it if necessary. If no name is specified, return the root logger. """ if name: return Logger.manager.getLogger(name) else: return root def critical(msg, *args, **kwargs): """ Log a message with severity 'CRITICAL' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ if len(root.handlers) == 0: basicConfig() root.critical(msg, *args, **kwargs) fatal = critical def error(msg, *args, **kwargs): """ Log a message with severity 'ERROR' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ if len(root.handlers) == 0: basicConfig() root.error(msg, *args, **kwargs) def exception(msg, *args, **kwargs): """ Log a message with severity 'ERROR' on the root logger, with exception information. If the logger has no handlers, basicConfig() is called to add a console handler with a pre-defined format. """ kwargs['exc_info'] = True error(msg, *args, **kwargs) def warning(msg, *args, **kwargs): """ Log a message with severity 'WARNING' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ if len(root.handlers) == 0: basicConfig() root.warning(msg, *args, **kwargs) def warn(msg, *args, **kwargs): warnings.warn("The 'warn' function is deprecated, " "use 'warning' instead", DeprecationWarning, 2) warning(msg, *args, **kwargs) def info(msg, *args, **kwargs): """ Log a message with severity 'INFO' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ if len(root.handlers) == 0: basicConfig() root.info(msg, *args, **kwargs) def debug(msg, *args, **kwargs): """ Log a message with severity 'DEBUG' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ if len(root.handlers) == 0: basicConfig() root.debug(msg, *args, **kwargs) def log(level, msg, *args, **kwargs): """ Log 'msg % args' with the integer severity 'level' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ if len(root.handlers) == 0: basicConfig() root.log(level, msg, *args, **kwargs) def disable(level): """ Disable all logging calls of severity 'level' and below. """ root.manager.disable = level def shutdown(handlerList=_handlerList): """ Perform any cleanup actions in the logging system (e.g. flushing buffers). Should be called at application exit. """ for wr in reversed(handlerList[:]): #errors might occur, for example, if files are locked #we just ignore them if raiseExceptions is not set try: h = wr() if h: try: h.acquire() h.flush() h.close() except (IOError, ValueError): # Ignore errors which might be caused # because handlers have been closed but # references to them are still around at # application exit. pass finally: h.release() except: if raiseExceptions: raise #else, swallow #Let's try and shutdown automatically on application exit... import atexit atexit.register(shutdown) # Null handler class NullHandler(Handler): """ This handler does nothing. It's intended to be used to avoid the "No handlers could be found for logger XXX" one-off warning. This is important for library code, which may contain code to log events. If a user of the library does not configure logging, the one-off warning might be produced; to avoid this, the library developer simply needs to instantiate a NullHandler and add it to the top-level logger of the library module or package. """ def handle(self, record): """Stub.""" def emit(self, record): """Stub.""" def createLock(self): self.lock = None # Warnings integration _warnings_showwarning = None def _showwarning(message, category, filename, lineno, file=None, line=None): """ Implementation of showwarnings which redirects to logging, which will first check to see if the file parameter is None. If a file is specified, it will delegate to the original warnings implementation of showwarning. Otherwise, it will call warnings.formatwarning and will log the resulting string to a warnings logger named "py.warnings" with level logging.WARNING. """ if file is not None: if _warnings_showwarning is not None: _warnings_showwarning(message, category, filename, lineno, file, line) else: s = warnings.formatwarning(message, category, filename, lineno, line) logger = getLogger("py.warnings") if not logger.handlers: logger.addHandler(NullHandler()) logger.warning("%s", s) def captureWarnings(capture): """ If capture is true, redirect all warnings to the logging package. If capture is False, ensure that warnings are not redirected to logging but to their original destinations. """ global _warnings_showwarning if capture: if _warnings_showwarning is None: _warnings_showwarning = warnings.showwarning warnings.showwarning = _showwarning else: if _warnings_showwarning is not None: warnings.showwarning = _warnings_showwarning _warnings_showwarning = None
gpl-3.0
acshan/odoo
addons/resource/faces/pcalendar.py
433
28436
#@+leo-ver=4 #@+node:@file pcalendar.py #@@language python #@<< Copyright >> #@+node:<< Copyright >> ############################################################################ # Copyright (C) 2005, 2006, 2007, 2008 by Reithinger GmbH # mreithinger@web.de # # This file is part of faces. # # faces 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. # # faces is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the # Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ############################################################################ #@-node:<< Copyright >> #@nl """ This module contains all classes and functions for the project plan calendar """ #@<< Imports >> #@+node:<< Imports >> from string import * import datetime import time import re import locale import bisect import sys TIME_RANGE_PATTERN = re.compile("(\\d+):(\\d+)\\s*-\\s*(\\d+):(\\d+)") TIME_DELTA_PATTERN = re.compile("([-+]?\\d+(\\.\\d+)?)([dwmyMH])") DEFAULT_MINIMUM_TIME_UNIT = 15 DEFAULT_WORKING_DAYS_PER_WEEK = 5 DEFAULT_WORKING_DAYS_PER_MONTH = 20 DEFAULT_WORKING_DAYS_PER_YEAR = 200 DEFAULT_WORKING_HOURS_PER_DAY = 8 DEFAULT_WORKING_TIMES = ( (8 * 60, 12 * 60 ), (13 * 60, 17 * 60 ) ) DEFAULT_WORKING_DAYS = { 0 : DEFAULT_WORKING_TIMES, 1 : DEFAULT_WORKING_TIMES, 2 : DEFAULT_WORKING_TIMES, 3 : DEFAULT_WORKING_TIMES, 4 : DEFAULT_WORKING_TIMES, 5 : (), 6 : () } #@-node:<< Imports >> #@nl #@+others #@+node:to_time_range def to_time_range(src): """ converts a string to a timerange, i.e (from, to) from, to are ints, specifing the minutes since midnight """ if not src: return () mo = TIME_RANGE_PATTERN.match(src) if not mo: raise ValueError("%s is no time range" % src) from_time = int(mo.group(1)) * 60 + int(mo.group(2)) to_time = int(mo.group(3)) * 60 + int(mo.group(4)) return from_time, to_time #@-node:to_time_range #@+node:to_datetime def to_datetime(src): """ a tolerant conversion function to convert different strings to a datetime.dateime """ #to get the original value for wrappers new = getattr(src, "_value", src) while new is not src: src = new new = getattr(src, "_value", src) if isinstance(src, _WorkingDateBase): src = src.to_datetime() if isinstance(src, datetime.datetime): return src src = str(src) formats = [ "%x %H:%M", "%x", "%Y-%m-%d %H:%M", "%y-%m-%d %H:%M", "%d.%m.%Y %H:%M", "%d.%m.%y %H:%M", "%Y%m%d %H:%M", "%d/%m/%y %H:%M", "%d/%m/%Y %H:%M", "%d/%m/%Y", "%d/%m/%y", "%Y-%m-%d", "%y-%m-%d", "%d.%m.%Y", "%d.%m.%y", "%Y%m%d" ] for f in formats: try: conv = time.strptime(src, f) return datetime.datetime(*conv[0:-3]) except Exception, e: pass raise TypeError("'%s' (%s) is not a datetime" % (src, str(type(src)))) #@-node: #@+node:_to_days def _to_days(src): """ converts a string of the day abreviations mon, tue, wed, thu, fri, sat, sun to a dir with correct weekday indices. For Example convert_to_days('mon, tue, thu') results in { 0:1, 1:1, 3:1 } """ tokens = src.split(",") result = { } for t in tokens: try: index = { "mon" : 0, "tue" : 1, "wed" : 2, "thu" : 3, "fri" : 4, "sat" : 5, "sun" : 6 } [ lower(t.strip()) ] result[index] = 1 except: raise ValueError("%s is not a day" % (t)) return result #@-node:_to_days #@+node:_add_to_time_spans def _add_to_time_spans(src, to_add, is_free): if not isinstance(to_add, (tuple, list)): to_add = (to_add,) tmp = [] for start, end, f in src: tmp.append((start, True, f)) tmp.append((end, False, f)) for v in to_add: if isinstance(v, (tuple, list)): start = to_datetime(v[0]) end = to_datetime(v[1]) else: start = to_datetime(v) end = start.replace(hour=0, minute=0) + datetime.timedelta(1) tmp.append((start, start <= end, is_free)) tmp.append((end, start > end, is_free)) tmp.sort() # 0: date # 1: is_start # 2: is_free sequence = [] free_count = 0 work_count = 0 last = None for date, is_start, is_free in tmp: if is_start: if is_free: if not free_count and not work_count: last = date free_count += 1 else: if not work_count: if free_count: sequence.append((last, date, True)) last = date work_count += 1 else: if is_free: assert(free_count > 0) free_count -= 1 if not free_count and not work_count: sequence.append((last, date, True)) else: assert(work_count > 0) work_count -= 1 if not work_count: sequence.append((last, date, False)) if free_count: last = date return tuple(sequence) #@-node:_add_to_time_spans #@+node:to_timedelta def to_timedelta(src, cal=None, is_duration=False): """ converts a string to a datetime.timedelta. If cal is specified it will be used for getting the working times. if is_duration=True working times will not be considered. Valid units are d for Days w for Weeks m for Months y for Years H for Hours M for Minutes """ cal = cal or _default_calendar if isinstance(src, datetime.timedelta): return datetime.timedelta(src.days, seconds=src.seconds, calendar=cal) if isinstance(src, (long, int, float)): src = "%sM" % str(src) if not isinstance(src, basestring): raise ValueError("%s is not a duration" % (repr(src))) src = src.strip() if is_duration: d_p_w = 7 d_p_m = 30 d_p_y = 360 d_w_h = 24 else: d_p_w = cal.working_days_per_week d_p_m = cal.working_days_per_month d_p_y = cal.working_days_per_year d_w_h = cal.working_hours_per_day def convert_minutes(minutes): minutes = int(minutes) hours = minutes / 60 minutes = minutes % 60 days = hours / d_w_h hours = hours % d_w_h return [ days, 0, 0, 0, minutes, hours ] def convert_days(value): days = int(value) value -= days value *= d_w_h hours = int(value) value -= hours value *= 60 minutes = round(value) return [ days, 0, 0, 0, minutes, hours ] sum_args = [ 0, 0, 0, 0, 0, 0 ] split = src.split(" ") for s in split: mo = TIME_DELTA_PATTERN.match(s) if not mo: raise ValueError(src + " is not a valid duration: valid" " units are: d w m y M H") unit = mo.group(3) val = float(mo.group(1)) if unit == 'd': args = convert_days(val) elif unit == 'w': args = convert_days(val * d_p_w) elif unit == 'm': args = convert_days(val * d_p_m) elif unit == 'y': args = convert_days(val * d_p_y) elif unit == 'M': args = convert_minutes(val) elif unit == 'H': args = convert_minutes(val * 60) sum_args = [ a + b for a, b in zip(sum_args, args) ] sum_args = tuple(sum_args) return datetime.timedelta(*sum_args) #@-node:to_timedelta #@+node:timedelta_to_str def timedelta_to_str(delta, format, cal=None, is_duration=False): cal = cal or _default_calendar if is_duration: d_p_w = 7 d_p_m = 30 d_p_y = 365 d_w_h = 24 else: d_p_w = cal.working_days_per_week d_p_m = cal.working_days_per_month d_p_y = cal.working_days_per_year d_w_h = cal.working_hours_per_day has_years = format.find("%y") > -1 has_minutes = format.find("%M") > -1 has_hours = format.find("%H") > -1 or has_minutes has_days = format.find("%d") > -1 has_weeks = format.find("%w") > -1 has_months = format.find("%m") > -1 result = format days = delta.days d_r = (days, format) minutes = delta.seconds / 60 def rebase(d_r, cond1, cond2, letter, divisor): #rebase the days if not cond1: return d_r days, result = d_r if cond2: val = days / divisor if not val: result = re.sub("{[^{]*?%" + letter + "[^}]*?}", "", result) result = result.replace("%" + letter, str(val)) days %= divisor else: result = result.replace("%" + letter, locale.format("%.2f", (float(days) / divisor))) return (days, result) d_r = rebase(d_r, has_years, has_months or has_weeks or has_days, "y", d_p_y) d_r = rebase(d_r, has_months, has_weeks or has_days, "m", d_p_m) d_r = rebase(d_r, has_weeks, has_days, "w", d_p_w) days, result = d_r if not has_days: minutes += days * d_w_h * 60 days = 0 if has_hours: if not days: result = re.sub("{[^{]*?%d[^}]*?}", "", result) result = result.replace("%d", str(days)) else: result = result.replace("%d", "%.2f" % (days + float(minutes) / (d_w_h * 60))) if has_hours: if has_minutes: val = minutes / 60 if not val: result = re.sub("{[^{]*?%H[^}]*?}", "", result) result = result.replace("%H", str(val)) minutes %= 60 else: result = result.replace("%H", "%.2f" % (float(minutes) / 60)) if not minutes: result = re.sub("{[^{]*?%M[^}]*?}", "", result) result = result.replace("%M", str(minutes)) result = result.replace("{", "") result = result.replace("}", "") return result.strip() #@-node:timedelta_to_str #@+node:strftime def strftime(dt, format): """ an extended version of strftime, that introduces some new directives: %IW iso week number %IY iso year %IB full month name appropriate to iso week %ib abbreviated month name appropriate to iso week %im month as decimal number appropriate to iso week """ iso = dt.isocalendar() if iso[0] != dt.year: iso_date = dt.replace(day=1, month=1) format = format \ .replace("%IB", iso_date.strftime("%B"))\ .replace("%ib", iso_date.strftime("%b"))\ .replace("%im", iso_date.strftime("%m")) else: format = format \ .replace("%IB", "%B")\ .replace("%ib", "%b")\ .replace("%im", "%m") format = format \ .replace("%IW", str(iso[1]))\ .replace("%IY", str(iso[0]))\ return dt.strftime(format) #@-node:strftime #@+node:union def union(*calendars): """ returns a calendar that unifies all working times """ #@ << check arguments >> #@+node:<< check arguments >> if len(calendars) == 1: calendars = calendars[0] #@nonl #@-node:<< check arguments >> #@nl #@ << intersect vacations >> #@+node:<< intersect vacations >> free_time = [] for c in calendars: for start, end, is_free in c.time_spans: if is_free: free_time.append((start, False)) free_time.append((end, True)) count = len(calendars) open = 0 time_spans = [] free_time.sort() for date, is_end in free_time: if is_end: if open == count: time_spans.append((start, date, True)) open -= 1 else: open += 1 start = date #@-node:<< intersect vacations >> #@nl #@ << unify extra worktime >> #@+node:<< unify extra worktime >> for c in calendars: for start, end, is_free in c.time_spans: if not is_free: time_spans = _add_to_time_spans(time_spans, start, end) #@nonl #@-node:<< unify extra worktime >> #@nl #@ << unify working times >> #@+node:<< unify working times >> working_times = {} for d in range(0, 7): times = [] for c in calendars: for start, end in c.working_times.get(d, []): times.append((start, False)) times.append((end, True)) times.sort() open = 0 ti = [] start = None for time, is_end in times: if not is_end: if not start: start = time open += 1 else: open -= 1 if not open: ti.append((start, time)) start = None if ti: working_times[d] = ti #@-node:<< unify working times >> #@nl #@ << create result calendar >> #@+node:<< create result calendar >> result = Calendar() result.working_times = working_times result.time_spans = time_spans result._recalc_working_time() result._build_mapping() #@nonl #@-node:<< create result calendar >> #@nl return result #@nonl #@-node:union #@+node:class _CalendarItem class _CalendarItem(int): #@ << class _CalendarItem declarations >> #@+node:<< class _CalendarItem declarations >> __slots__ = () calender = None #@-node:<< class _CalendarItem declarations >> #@nl #@ @+others #@+node:__new__ def __new__(cls, val): try: return int.__new__(cls, val) except OverflowError: return int.__new__(cls, sys.maxint) #@-node:__new__ #@+node:round def round(self, round_up=True): m_t_u = self.calendar.minimum_time_unit minutes = int(self) base = (minutes / m_t_u) * m_t_u minutes %= m_t_u round_up = round_up and minutes > 0 or minutes > m_t_u / 2 if round_up: base += m_t_u return self.__class__(base) #@-node:round #@-others #@-node:class _CalendarItem #@+node:class _Minutes class _Minutes(_CalendarItem): #@ << class _Minutes declarations >> #@+node:<< class _Minutes declarations >> __slots__ = () STR_FORMAT = "{%dd}{ %HH}{ %MM}" #@-node:<< class _Minutes declarations >> #@nl #@ @+others #@+node:__new__ def __new__(cls, src=0, is_duration=False): """ converts a timedelta in working minutes. """ if isinstance(src, cls) or type(src) is int: return _CalendarItem.__new__(cls, src) cal = cls.calendar if not isinstance(src, datetime.timedelta): src = to_timedelta(src, cal, is_duration) d_w_h = is_duration and 24 or cal.working_hours_per_day src = src.days * d_w_h * 60 + src.seconds / 60 return _CalendarItem.__new__(cls, src) #@-node:__new__ #@+node:__cmp__ def __cmp__(self, other): return cmp(int(self), int(self.__class__(other))) #@-node:__cmp__ #@+node:__add__ def __add__(self, other): try: return self.__class__(int(self) + int(self.__class__(other))) except: return NotImplemented #@-node:__add__ #@+node:__sub__ def __sub__(self, other): try: return self.__class__(int(self) - int(self.__class__(other))) except: return NotImplemented #@-node:__sub__ #@+node:to_timedelta def to_timedelta(self, is_duration=False): d_w_h = is_duration and 24 or self.calendar.working_hours_per_day minutes = int(self) hours = minutes / 60 minutes = minutes % 60 days = hours / d_w_h hours = hours % d_w_h return datetime.timedelta(days, hours=hours, minutes=minutes) #@nonl #@-node:to_timedelta #@+node:strftime def strftime(self, format=None, is_duration=False): td = self.to_timedelta(is_duration) return timedelta_to_str(td, format or self.STR_FORMAT, self.calendar, is_duration) #@nonl #@-node:strftime #@-others #@-node:class _Minutes #@+node:class _WorkingDateBase class _WorkingDateBase(_CalendarItem): """ A daytetime which has only valid values within the workingtimes of a specific calendar """ #@ << class _WorkingDateBase declarations >> #@+node:<< class _WorkingDateBase declarations >> timetuple = True STR_FORMAT = "%x %H:%M" _minutes = _Minutes __slots__ = () #@-node:<< class _WorkingDateBase declarations >> #@nl #@ @+others #@+node:__new__ def __new__(cls, src): #cls.__bases__[0] is the base of #the calendar specific StartDate and EndDate if isinstance(src, cls.__bases__[0]) or type(src) in (int, float): return _CalendarItem.__new__(cls, src) src = cls.calendar.from_datetime(to_datetime(src)) return _CalendarItem.__new__(cls, src) #@-node:__new__ #@+node:__repr__ def __repr__(self): return self.strftime() #@-node:__repr__ #@+node:to_datetime def to_datetime(self): return self.to_starttime() #@-node:to_datetime #@+node:to_starttime def to_starttime(self): return self.calendar.to_starttime(self) #@-node:to_starttime #@+node:to_endtime def to_endtime(self): return self.calendar.to_endtime(self) #@-node:to_endtime #@+node:__cmp__ def __cmp__(self, other): return cmp(int(self), int(self.__class__(other))) #@-node:__cmp__ #@+node:__add__ def __add__(self, other): try: return self.__class__(int(self) + int(self._minutes(other))) except ValueError, e: raise e except: return NotImplemented #@-node:__add__ #@+node:__sub__ def __sub__(self, other): if isinstance(other, (datetime.timedelta, str, _Minutes)): try: other = self._minutes(other) except: pass if isinstance(other, self._minutes): return self.__class__(int(self) - int(other)) try: return self._minutes(int(self) - int(self.__class__(other))) except: return NotImplemented #@-node:__sub__ #@+node:strftime def strftime(self, format=None): return strftime(self.to_datetime(), format or self.STR_FORMAT) #@-node:strftime #@-others #@-node:class _WorkingDateBase #@+node:class Calendar class Calendar(object): """ A calendar to specify working times and vacations. The calendars epoch start at 1.1.1979 """ #@ << declarations >> #@+node:<< declarations >> # january the first must be a monday EPOCH = datetime.datetime(1979, 1, 1) minimum_time_unit = DEFAULT_MINIMUM_TIME_UNIT working_days_per_week = DEFAULT_WORKING_DAYS_PER_WEEK working_days_per_month = DEFAULT_WORKING_DAYS_PER_MONTH working_days_per_year = DEFAULT_WORKING_DAYS_PER_YEAR working_hours_per_day = DEFAULT_WORKING_HOURS_PER_DAY now = EPOCH #@-node:<< declarations >> #@nl #@ @+others #@+node:__init__ def __init__(self): self.time_spans = () self._dt_num_can = () self._num_dt_can = () self.working_times = { } self._recalc_working_time() self._make_classes() #@-node:__init__ #@+node:__or__ def __or__(self, other): if isinstance(other, Calendar): return union(self, other) return NotImplemented #@nonl #@-node:__or__ #@+node:clone def clone(self): result = Calendar() result.working_times = self.working_times.copy() result.time_spans = self.time_spans result._recalc_working_time() result._build_mapping() return result #@nonl #@-node:clone #@+node:set_working_days def set_working_days(self, day_range, trange, *further_tranges): """ Sets the working days of an calendar day_range is a string of day abbreviations like 'mon, tue' trange and further_tranges is a time range string like '8:00-10:00' """ time_ranges = [ trange ] + list(further_tranges) time_ranges = filter(bool, map(to_time_range, time_ranges)) days = _to_days(day_range) for k in days.keys(): self.working_times[k] = time_ranges self._recalc_working_time() self._build_mapping() #@-node:set_working_days #@+node:set_vacation def set_vacation(self, value): """ Sets vacation time. value is either a datetime literal or a sequence of items that can be a datetime literals and or pair of datetime literals """ self.time_spans = _add_to_time_spans(self.time_spans, value, True) self._build_mapping() #@-node:set_vacation #@+node:set_extra_work def set_extra_work(self, value): """ Sets extra working time value is either a datetime literal or a sequence of items that can be a datetime literals and or pair of datetime literals """ self.time_spans = _add_to_time_spans(self.time_spans, value, False) self._build_mapping() #@-node:set_extra_work #@+node:from_datetime def from_datetime(self, value): assert(isinstance(value, datetime.datetime)) delta = value - self.EPOCH days = delta.days minutes = delta.seconds / 60 # calculate the weektime weeks = days / 7 wtime = self.week_time * weeks # calculate the daytime days %= 7 dtime = sum(self.day_times[:days]) # calculate the minute time slots = self.working_times.get(days, DEFAULT_WORKING_DAYS[days]) mtime = 0 for start, end in slots: if minutes > end: mtime += end - start else: if minutes > start: mtime += minutes - start break result = wtime + dtime + mtime # map exceptional timespans dt_num_can = self._dt_num_can pos = bisect.bisect(dt_num_can, (value,)) - 1 if pos >= 0: start, end, nstart, nend, cend = dt_num_can[pos] if value < end: if nstart < nend: delta = value - start delta = delta.days * 24 * 60 + delta.seconds / 60 result = nstart + delta else: result = nstart else: result += (nend - cend) # == (result - cend) + nend return result #@-node:from_datetime #@+node:split_time def split_time(self, value): #map exceptional timespans num_dt_can = self._num_dt_can pos = bisect.bisect(num_dt_can, (value, sys.maxint)) - 1 if pos >= 0: nstart, nend, start, end, cend = num_dt_can[pos] if value < nend: value = start + datetime.timedelta(minutes=value - nstart) delta = value - self.EPOCH return delta.days / 7, delta.days % 7, delta.seconds / 60, -1 else: value += (cend - nend) # (value - nend + cend) #calculate the weeks since the epoch weeks = value / self.week_time value %= self.week_time #calculate the remaining days days = 0 for day_time in self.day_times: if value < day_time: break value -= day_time days += 1 #calculate the remaining minutes minutes = 0 slots = self.working_times.get(days, DEFAULT_WORKING_DAYS[days]) index = 0 for start, end in slots: delta = end - start if delta > value: minutes = start + value break else: value -= delta index += 1 return weeks, days, minutes, index #@-node:split_time #@+node:to_starttime def to_starttime(self, value): weeks, days, minutes, index = self.split_time(value) return self.EPOCH + datetime.timedelta(weeks=weeks, days=days, minutes=minutes) #@-node:to_starttime #@+node:to_endtime def to_endtime(self, value): return self.to_starttime(value - 1) + datetime.timedelta(minutes=1) #@-node:to_endtime #@+node:get_working_times def get_working_times(self, day): return self.working_times.get(day, DEFAULT_WORKING_DAYS[day]) #@-node:get_working_times #@+node:_build_mapping def _build_mapping(self): self._dt_num_can = self._num_dt_can = () dt_num_can = [] num_dt_can = [] delta = self.Minutes() for start, end, is_free in self.time_spans: cstart = self.StartDate(start) cend = self.EndDate(end) nstart = cstart + delta if not is_free: d = end - start d = d.days * 24 * 60 + d.seconds / 60 nend = nstart + d else: nend = nstart delta += (nend - nstart) - (cend - cstart) dt_num_can.append((start, end, nstart, nend, cend)) num_dt_can.append((nstart, nend, start, end, cend)) self._dt_num_can = tuple(dt_num_can) self._num_dt_can = tuple(num_dt_can) #@-node:_build_mapping #@+node:_recalc_working_time def _recalc_working_time(self): def slot_sum_time(day): slots = self.working_times.get(day, DEFAULT_WORKING_DAYS[day]) return sum(map(lambda slot: slot[1] - slot[0], slots)) self.day_times = map(slot_sum_time, range(0, 7)) self.week_time = sum(self.day_times) #@-node:_recalc_working_time #@+node:_make_classes def _make_classes(self): #ensure that the clases are instance specific class minutes(_Minutes): calendar = self __slots__ = () class db(_WorkingDateBase): calendar = self _minutes = minutes __slots__ = () class wdt(db): __slots__ = () class edt(db): __slots__ = () def to_datetime(self): return self.to_endtime() self.Minutes, self.StartDate, self.EndDate = minutes, wdt, edt self.WorkingDate = self.StartDate #@-node:_make_classes #@-others _default_calendar = Calendar() WorkingDate = _default_calendar.WorkingDate StartDate = _default_calendar.StartDate EndDate = _default_calendar.EndDate Minutes = _default_calendar.Minutes #@-node:class Calendar #@-others if __name__ == '__main__': cal = Calendar() start = EndDate("10.1.2005") delay = Minutes("4H") start2 = cal.StartDate(start) start3 = cal.StartDate("10.1.2005") #@-node:@file pcalendar.py #@-leo # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
pchaigno/grr
parsers/windows_registry_parser_test.py
6
5285
#!/usr/bin/env python # -*- mode: python; encoding: utf-8 -*- """Tests for grr.parsers.windows_registry_parser.""" from grr.lib import flags from grr.lib import test_lib from grr.lib import utils from grr.lib.rdfvalues import client as rdf_client from grr.lib.rdfvalues import paths as rdf_paths from grr.lib.rdfvalues import protodict as rdf_protodict from grr.parsers import windows_registry_parser class WindowsRegistryParserTest(test_lib.FlowTestsBaseclass): def _MakeRegStat(self, path, value, registry_type): options = rdf_paths.PathSpec.Options.CASE_LITERAL pathspec = rdf_paths.PathSpec(path=path, path_options=options, pathtype=rdf_paths.PathSpec.PathType.REGISTRY) if registry_type == rdf_client.StatEntry.RegistryType.REG_MULTI_SZ: reg_data = rdf_protodict.DataBlob(list=rdf_protodict.BlobArray( content=rdf_protodict.DataBlob(string=value))) else: reg_data = rdf_protodict.DataBlob().SetValue(value) return rdf_client.StatEntry( aff4path=self.client_id.Add("registry").Add(path), pathspec=pathspec, registry_data=reg_data, registry_type=registry_type) def testGetServiceName(self): hklm = "HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/services" parser = windows_registry_parser.WinServicesParser() self.assertEqual(parser._GetServiceName( "%s/SomeService/Start" % hklm), "SomeService") self.assertEqual(parser._GetServiceName( "%s/SomeService/Parameters/ServiceDLL" % hklm), "SomeService") def testWinServicesParser(self): dword = rdf_client.StatEntry.RegistryType.REG_DWORD_LITTLE_ENDIAN reg_str = rdf_client.StatEntry.RegistryType.REG_SZ hklm = "HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services" hklm_set01 = "HKEY_LOCAL_MACHINE/SYSTEM/ControlSet001/services" service_keys = [ ("%s/ACPI/Type" % hklm, 1, dword), ("%s/ACPI/Start" % hklm, 0, dword), ("%s/ACPI/ErrorControl" % hklm, 3, dword), ("%s/ACPI/ImagePath" % hklm, "system32\\drivers\\ACPI.sys", reg_str), ("%s/ACPI/DisplayName" % hklm, "Microsoft ACPI Driver", reg_str), ("%s/ACPI/Group" % hklm, "Boot Bus Extender", reg_str), ("%s/ACPI/DriverPackageId" % hklm, "acpi.inf_amd64_neutral_99aaaaabcccccccc", reg_str), ("%s/AcpiPmi/Start" % hklm_set01, 3, dword), ("%s/AcpiPmi/DisplayName" % hklm_set01, "AcpiPmi", rdf_client.StatEntry.RegistryType.REG_MULTI_SZ), (u"%s/中国日报/DisplayName" % hklm, u"中国日报", reg_str), (u"%s/中国日报/Parameters/ServiceDLL" % hklm, "blah.dll", reg_str) ] stats = [self._MakeRegStat(*x) for x in service_keys] parser = windows_registry_parser.WinServicesParser() results = parser.ParseMultiple(stats, None) names = [] for result in results: if result.display_name == u"中国日报": self.assertEqual(result.display_name, u"中国日报") self.assertEqual(result.service_dll, "blah.dll") names.append(result.display_name) elif utils.SmartStr(result.registry_key).endswith("AcpiPmi"): self.assertEqual(result.name, "AcpiPmi") self.assertEqual(result.startup_type, 3) self.assertEqual(result.display_name, "[u'AcpiPmi']") self.assertEqual(result.registry_key.Path(), "/C.1000000000000000/registry/%s/AcpiPmi" % hklm_set01) names.append(result.display_name) elif utils.SmartStr(result.registry_key).endswith("ACPI"): self.assertEqual(result.name, "ACPI") self.assertEqual(result.service_type, 1) self.assertEqual(result.startup_type, 0) self.assertEqual(result.error_control, 3) self.assertEqual(result.image_path, "system32\\drivers\\ACPI.sys") self.assertEqual(result.display_name, "Microsoft ACPI Driver") self.assertEqual(result.group_name, "Boot Bus Extender") self.assertEqual(result.driver_package_id, "acpi.inf_amd64_neutral_99aaaaabcccccccc") names.append(result.display_name) self.assertItemsEqual(names, [u"中国日报", "[u'AcpiPmi']", "Microsoft ACPI Driver"]) def testWinUserSpecialDirs(self): reg_str = rdf_client.StatEntry.RegistryType.REG_SZ hk_u = "registry/HKEY_USERS/S-1-1-1010-10101-1010" service_keys = [ ("%s/Environment/TEMP" % hk_u, r"temp\path", reg_str), ("%s/Volatile Environment/USERDOMAIN" % hk_u, "GEVULOT", reg_str) ] stats = [self._MakeRegStat(*x) for x in service_keys] parser = windows_registry_parser.WinUserSpecialDirs() results = list(parser.ParseMultiple(stats, None)) self.assertEqual(results[0].temp, r"temp\path") self.assertEqual(results[0].userdomain, "GEVULOT") def testWinSystemDriveParser(self): sysroot = (r"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT" r"\CurrentVersion\SystemRoot") stat = self._MakeRegStat(sysroot, r"C:\Windows", None) parser = windows_registry_parser.WinSystemDriveParser() self.assertEqual(r"C:", parser.Parse(stat, None).next()) def main(argv): test_lib.main(argv) if __name__ == "__main__": flags.StartMain(main)
apache-2.0
alheinecke/tensorflow-xsmm
tensorflow/python/platform/flags_test.py
79
3046
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for our flags implementation.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import unittest from tensorflow.python.platform import app from tensorflow.python.platform import flags flags.DEFINE_string("string_foo", "default_val", "HelpString") flags.DEFINE_integer("int_foo", 42, "HelpString") flags.DEFINE_float("float_foo", 42.0, "HelpString") flags.DEFINE_boolean("bool_foo", True, "HelpString") flags.DEFINE_boolean("bool_negation", True, "HelpString") flags.DEFINE_boolean("bool-dash-negation", True, "HelpString") flags.DEFINE_boolean("bool_a", False, "HelpString") flags.DEFINE_boolean("bool_c", False, "HelpString") flags.DEFINE_boolean("bool_d", True, "HelpString") flags.DEFINE_bool("bool_e", True, "HelpString") FLAGS = flags.FLAGS class FlagsTest(unittest.TestCase): def testString(self): res = FLAGS.string_foo self.assertEqual(res, "default_val") FLAGS.string_foo = "bar" self.assertEqual("bar", FLAGS.string_foo) def testBool(self): res = FLAGS.bool_foo self.assertTrue(res) FLAGS.bool_foo = False self.assertFalse(FLAGS.bool_foo) def testBoolCommandLines(self): # Specified on command line with no args, sets to True, # even if default is False. self.assertEqual(True, FLAGS.bool_a) # --no before the flag forces it to False, even if the # default is True self.assertEqual(False, FLAGS.bool_negation) # --bool_flag=True sets to True self.assertEqual(True, FLAGS.bool_c) # --bool_flag=False sets to False self.assertEqual(False, FLAGS.bool_d) def testInt(self): res = FLAGS.int_foo self.assertEquals(res, 42) FLAGS.int_foo = -1 self.assertEqual(-1, FLAGS.int_foo) def testFloat(self): res = FLAGS.float_foo self.assertEquals(42.0, res) FLAGS.float_foo = -1.0 self.assertEqual(-1.0, FLAGS.float_foo) def main(_): # unittest.main() tries to interpret the unknown flags, so use the # direct functions instead. runner = unittest.TextTestRunner() itersuite = unittest.TestLoader().loadTestsFromTestCase(FlagsTest) runner.run(itersuite) if __name__ == "__main__": # Test command lines sys.argv.extend([ "--bool_a", "--nobool_negation", "--bool_c=True", "--bool_d=False", "and_argument" ]) app.run()
apache-2.0
terracoin/terracoin
qa/rpc-tests/prioritise_transaction.py
1
6000
#!/usr/bin/env python3 # Copyright (c) 2015-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test PrioritiseTransaction code # from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * from test_framework.mininode import COIN, MAX_BLOCK_SIZE class PrioritiseTransactionTest(BitcoinTestFramework): def __init__(self): self.txouts = gen_return_txouts() def setup_chain(self): print("Initializing test directory "+self.options.tmpdir) initialize_chain_clean(self.options.tmpdir, 1) def setup_network(self): self.nodes = [] self.is_network_split = False self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-printpriority=1"])) self.relayfee = self.nodes[0].getnetworkinfo()['relayfee'] def run_test(self): utxo_count = 90 utxos = create_confirmed_utxos(self.relayfee, self.nodes[0], utxo_count) base_fee = self.relayfee*100 # our transactions are smaller than 100kb txids = [] # Create 3 batches of transactions at 3 different fee rate levels range_size = utxo_count // 3 for i in range(3): txids.append([]) start_range = i * range_size end_range = start_range + range_size txids[i] = create_lots_of_big_transactions(self.nodes[0], self.txouts, utxos[start_range:end_range], (i+1)*base_fee) # Make sure that the size of each group of transactions exceeds # MAX_BLOCK_SIZE -- otherwise the test needs to be revised to create # more transactions. mempool = self.nodes[0].getrawmempool(True) sizes = [0, 0, 0] for i in range(3): for j in txids[i]: assert(j in mempool) sizes[i] += mempool[j]['size'] assert(sizes[i] > MAX_BLOCK_SIZE) # Fail => raise utxo_count # add a fee delta to something in the cheapest bucket and make sure it gets mined # also check that a different entry in the cheapest bucket is NOT mined (lower # the priority to ensure its not mined due to priority) self.nodes[0].prioritisetransaction(txids[0][0], 0, int(3*base_fee*COIN)) self.nodes[0].prioritisetransaction(txids[0][1], -1e15, 0) self.nodes[0].generate(1) mempool = self.nodes[0].getrawmempool() print("Assert that prioritised transaction was mined") assert(txids[0][0] not in mempool) assert(txids[0][1] in mempool) high_fee_tx = None for x in txids[2]: if x not in mempool: high_fee_tx = x # Something high-fee should have been mined! assert(high_fee_tx != None) # Add a prioritisation before a tx is in the mempool (de-prioritising a # high-fee transaction so that it's now low fee). self.nodes[0].prioritisetransaction(high_fee_tx, -1e15, -int(2*base_fee*COIN)) # Add everything back to mempool self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) # Check to make sure our high fee rate tx is back in the mempool mempool = self.nodes[0].getrawmempool() assert(high_fee_tx in mempool) # Now verify the modified-high feerate transaction isn't mined before # the other high fee transactions. Keep mining until our mempool has # decreased by all the high fee size that we calculated above. while (self.nodes[0].getmempoolinfo()['bytes'] > sizes[0] + sizes[1]): self.nodes[0].generate(1) # High fee transaction should not have been mined, but other high fee rate # transactions should have been. mempool = self.nodes[0].getrawmempool() print("Assert that de-prioritised transaction is still in mempool") assert(high_fee_tx in mempool) for x in txids[2]: if (x != high_fee_tx): assert(x not in mempool) # Create a free, low priority transaction. Should be rejected. utxo_list = self.nodes[0].listunspent() assert(len(utxo_list) > 0) utxo = utxo_list[0] inputs = [] outputs = {} inputs.append({"txid" : utxo["txid"], "vout" : utxo["vout"]}) outputs[self.nodes[0].getnewaddress()] = utxo["amount"] - self.relayfee raw_tx = self.nodes[0].createrawtransaction(inputs, outputs) tx_hex = self.nodes[0].signrawtransaction(raw_tx)["hex"] txid = self.nodes[0].sendrawtransaction(tx_hex) # A tx that spends an in-mempool tx has 0 priority, so we can use it to # test the effect of using prioritise transaction for mempool acceptance inputs = [] inputs.append({"txid": txid, "vout": 0}) outputs = {} outputs[self.nodes[0].getnewaddress()] = utxo["amount"] - self.relayfee raw_tx2 = self.nodes[0].createrawtransaction(inputs, outputs) tx2_hex = self.nodes[0].signrawtransaction(raw_tx2)["hex"] tx2_id = self.nodes[0].decoderawtransaction(tx2_hex)["txid"] try: self.nodes[0].sendrawtransaction(tx2_hex) except JSONRPCException as exp: assert_equal(exp.error['code'], -26) # insufficient fee assert(tx2_id not in self.nodes[0].getrawmempool()) else: assert(False) # This is a less than 1000-byte transaction, so just set the fee # to be the minimum for a 1000 byte transaction and check that it is # accepted. self.nodes[0].prioritisetransaction(tx2_id, 0, int(self.relayfee*COIN)) print("Assert that prioritised free transaction is accepted to mempool") assert_equal(self.nodes[0].sendrawtransaction(tx2_hex), tx2_id) assert(tx2_id in self.nodes[0].getrawmempool()) if __name__ == '__main__': PrioritiseTransactionTest().main()
mit
bkaradzic/SwiftShader
third_party/SPIRV-Tools/utils/generate_grammar_tables.py
11
34927
#!/usr/bin/env python # Copyright (c) 2016 Google Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Generates various info tables from SPIR-V JSON grammar.""" import errno import json import os.path import re # Prefix for all C variables generated by this script. PYGEN_VARIABLE_PREFIX = 'pygen_variable' # Extensions to recognize, but which don't necessarily come from the SPIR-V # core or KHR grammar files. Get this list from the SPIR-V registery web page. # NOTE: Only put things on this list if it is not in those grammar files. EXTENSIONS_FROM_SPIRV_REGISTRY_AND_NOT_FROM_GRAMMARS = """ SPV_AMD_gcn_shader SPV_AMD_gpu_shader_half_float SPV_AMD_gpu_shader_int16 SPV_AMD_shader_trinary_minmax SPV_KHR_non_semantic_info """ def make_path_to_file(f): """Makes all ancestor directories to the given file, if they don't yet exist. Arguments: f: The file whose ancestor directories are to be created. """ dir = os.path.dirname(os.path.abspath(f)) try: os.makedirs(dir) except OSError as e: if e.errno == errno.EEXIST and os.path.isdir(dir): pass else: raise def convert_min_required_version(version): """Converts the minimal required SPIR-V version encoded in the grammar to the symbol in SPIRV-Tools.""" if version is None: return 'SPV_SPIRV_VERSION_WORD(1, 0)' if version == 'None': return '0xffffffffu' return 'SPV_SPIRV_VERSION_WORD({})'.format(version.replace('.', ',')) def convert_max_required_version(version): """Converts the maximum required SPIR-V version encoded in the grammar to the symbol in SPIRV-Tools.""" if version is None: return '0xffffffffu' return 'SPV_SPIRV_VERSION_WORD({})'.format(version.replace('.', ',')) def compose_capability_list(caps): """Returns a string containing a braced list of capabilities as enums. Arguments: - caps: a sequence of capability names Returns: a string containing the braced list of SpvCapability* enums named by caps. """ return '{' + ', '.join(['SpvCapability{}'.format(c) for c in caps]) + '}' def get_capability_array_name(caps): """Returns the name of the array containing all the given capabilities. Args: - caps: a sequence of capability names """ if not caps: return 'nullptr' return '{}_caps_{}'.format(PYGEN_VARIABLE_PREFIX, ''.join(caps)) def generate_capability_arrays(caps): """Returns the arrays of capabilities. Arguments: - caps: a sequence of sequence of capability names """ caps = sorted(set([tuple(c) for c in caps if c])) arrays = [ 'static const SpvCapability {}[] = {};'.format( get_capability_array_name(c), compose_capability_list(c)) for c in caps] return '\n'.join(arrays) def compose_extension_list(exts): """Returns a string containing a braced list of extensions as enums. Arguments: - exts: a sequence of extension names Returns: a string containing the braced list of extensions named by exts. """ return '{' + ', '.join( ['spvtools::Extension::k{}'.format(e) for e in exts]) + '}' def get_extension_array_name(extensions): """Returns the name of the array containing all the given extensions. Args: - extensions: a sequence of extension names """ if not extensions: return 'nullptr' else: return '{}_exts_{}'.format( PYGEN_VARIABLE_PREFIX, ''.join(extensions)) def generate_extension_arrays(extensions): """Returns the arrays of extensions. Arguments: - caps: a sequence of sequence of extension names """ extensions = sorted(set([tuple(e) for e in extensions if e])) arrays = [ 'static const spvtools::Extension {}[] = {};'.format( get_extension_array_name(e), compose_extension_list(e)) for e in extensions] return '\n'.join(arrays) def convert_operand_kind(operand_tuple): """Returns the corresponding operand type used in spirv-tools for the given operand kind and quantifier used in the JSON grammar. Arguments: - operand_tuple: a tuple of two elements: - operand kind: used in the JSON grammar - quantifier: '', '?', or '*' Returns: a string of the enumerant name in spv_operand_type_t """ kind, quantifier = operand_tuple # The following cases are where we differ between the JSON grammar and # spirv-tools. if kind == 'IdResultType': kind = 'TypeId' elif kind == 'IdResult': kind = 'ResultId' elif kind == 'IdMemorySemantics' or kind == 'MemorySemantics': kind = 'MemorySemanticsId' elif kind == 'IdScope' or kind == 'Scope': kind = 'ScopeId' elif kind == 'IdRef': kind = 'Id' elif kind == 'ImageOperands': kind = 'Image' elif kind == 'Dim': kind = 'Dimensionality' elif kind == 'ImageFormat': kind = 'SamplerImageFormat' elif kind == 'KernelEnqueueFlags': kind = 'KernelEnqFlags' elif kind == 'LiteralExtInstInteger': kind = 'ExtensionInstructionNumber' elif kind == 'LiteralSpecConstantOpInteger': kind = 'SpecConstantOpNumber' elif kind == 'LiteralContextDependentNumber': kind = 'TypedLiteralNumber' elif kind == 'PairLiteralIntegerIdRef': kind = 'LiteralIntegerId' elif kind == 'PairIdRefLiteralInteger': kind = 'IdLiteralInteger' elif kind == 'PairIdRefIdRef': # Used by OpPhi in the grammar kind = 'Id' if kind == 'FPRoundingMode': kind = 'FpRoundingMode' elif kind == 'FPFastMathMode': kind = 'FpFastMathMode' if quantifier == '?': kind = 'Optional{}'.format(kind) elif quantifier == '*': kind = 'Variable{}'.format(kind) return 'SPV_OPERAND_TYPE_{}'.format( re.sub(r'([a-z])([A-Z])', r'\1_\2', kind).upper()) class InstInitializer(object): """Instances holds a SPIR-V instruction suitable for printing as the initializer for spv_opcode_desc_t.""" def __init__(self, opname, caps, exts, operands, version, lastVersion): """Initialization. Arguments: - opname: opcode name (with the 'Op' prefix) - caps: a sequence of capability names required by this opcode - exts: a sequence of names of extensions enabling this enumerant - operands: a sequence of (operand-kind, operand-quantifier) tuples - version: minimal SPIR-V version required for this opcode - lastVersion: last version of SPIR-V that includes this opcode """ assert opname.startswith('Op') self.opname = opname[2:] # Remove the "Op" prefix. self.num_caps = len(caps) self.caps_mask = get_capability_array_name(caps) self.num_exts = len(exts) self.exts = get_extension_array_name(exts) self.operands = [convert_operand_kind(o) for o in operands] self.fix_syntax() operands = [o[0] for o in operands] self.ref_type_id = 'IdResultType' in operands self.def_result_id = 'IdResult' in operands self.version = convert_min_required_version(version) self.lastVersion = convert_max_required_version(lastVersion) def fix_syntax(self): """Fix an instruction's syntax, adjusting for differences between the officially released grammar and how SPIRV-Tools uses the grammar. Fixes: - ExtInst should not end with SPV_OPERAND_VARIABLE_ID. https://github.com/KhronosGroup/SPIRV-Tools/issues/233 """ if (self.opname == 'ExtInst' and self.operands[-1] == 'SPV_OPERAND_TYPE_VARIABLE_ID'): self.operands.pop() def __str__(self): template = ['{{"{opname}"', 'SpvOp{opname}', '{num_caps}', '{caps_mask}', '{num_operands}', '{{{operands}}}', '{def_result_id}', '{ref_type_id}', '{num_exts}', '{exts}', '{min_version}', '{max_version}}}'] return ', '.join(template).format( opname=self.opname, num_caps=self.num_caps, caps_mask=self.caps_mask, num_operands=len(self.operands), operands=', '.join(self.operands), def_result_id=(1 if self.def_result_id else 0), ref_type_id=(1 if self.ref_type_id else 0), num_exts=self.num_exts, exts=self.exts, min_version=self.version, max_version=self.lastVersion) class ExtInstInitializer(object): """Instances holds a SPIR-V extended instruction suitable for printing as the initializer for spv_ext_inst_desc_t.""" def __init__(self, opname, opcode, caps, operands): """Initialization. Arguments: - opname: opcode name - opcode: enumerant value for this opcode - caps: a sequence of capability names required by this opcode - operands: a sequence of (operand-kind, operand-quantifier) tuples """ self.opname = opname self.opcode = opcode self.num_caps = len(caps) self.caps_mask = get_capability_array_name(caps) self.operands = [convert_operand_kind(o) for o in operands] self.operands.append('SPV_OPERAND_TYPE_NONE') def __str__(self): template = ['{{"{opname}"', '{opcode}', '{num_caps}', '{caps_mask}', '{{{operands}}}}}'] return ', '.join(template).format( opname=self.opname, opcode=self.opcode, num_caps=self.num_caps, caps_mask=self.caps_mask, operands=', '.join(self.operands)) def generate_instruction(inst, is_ext_inst): """Returns the C initializer for the given SPIR-V instruction. Arguments: - inst: a dict containing information about a SPIR-V instruction - is_ext_inst: a bool indicating whether |inst| is an extended instruction. Returns: a string containing the C initializer for spv_opcode_desc_t or spv_ext_inst_desc_t """ opname = inst.get('opname') opcode = inst.get('opcode') caps = inst.get('capabilities', []) exts = inst.get('extensions', []) operands = inst.get('operands', {}) operands = [(o['kind'], o.get('quantifier', '')) for o in operands] min_version = inst.get('version', None) max_version = inst.get('lastVersion', None) assert opname is not None if is_ext_inst: return str(ExtInstInitializer(opname, opcode, caps, operands)) else: return str(InstInitializer(opname, caps, exts, operands, min_version, max_version)) def generate_instruction_table(inst_table): """Returns the info table containing all SPIR-V instructions, sorted by opcode, and prefixed by capability arrays. Note: - the built-in sorted() function is guaranteed to be stable. https://docs.python.org/3/library/functions.html#sorted Arguments: - inst_table: a list containing all SPIR-V instructions. """ inst_table = sorted(inst_table, key=lambda k: (k['opcode'], k['opname'])) caps_arrays = generate_capability_arrays( [inst.get('capabilities', []) for inst in inst_table]) exts_arrays = generate_extension_arrays( [inst.get('extensions', []) for inst in inst_table]) insts = [generate_instruction(inst, False) for inst in inst_table] insts = ['static const spv_opcode_desc_t kOpcodeTableEntries[] = {{\n' ' {}\n}};'.format(',\n '.join(insts))] return '{}\n\n{}\n\n{}'.format(caps_arrays, exts_arrays, '\n'.join(insts)) def generate_extended_instruction_table(json_grammar, set_name, operand_kind_prefix=""): """Returns the info table containing all SPIR-V extended instructions, sorted by opcode, and prefixed by capability arrays. Arguments: - inst_table: a list containing all SPIR-V instructions. - set_name: the name of the extended instruction set. - operand_kind_prefix: the prefix, if any, to add to the front of operand kind names. """ if operand_kind_prefix: prefix_operand_kind_names(operand_kind_prefix, json_grammar) inst_table = json_grammar["instructions"] set_name = set_name.replace(".", "_") inst_table = sorted(inst_table, key=lambda k: k['opcode']) caps = [inst.get('capabilities', []) for inst in inst_table] caps_arrays = generate_capability_arrays(caps) insts = [generate_instruction(inst, True) for inst in inst_table] insts = ['static const spv_ext_inst_desc_t {}_entries[] = {{\n' ' {}\n}};'.format(set_name, ',\n '.join(insts))] return '{}\n\n{}'.format(caps_arrays, '\n'.join(insts)) class EnumerantInitializer(object): """Prints an enumerant as the initializer for spv_operand_desc_t.""" def __init__(self, enumerant, value, caps, exts, parameters, version, lastVersion): """Initialization. Arguments: - enumerant: enumerant name - value: enumerant value - caps: a sequence of capability names required by this enumerant - exts: a sequence of names of extensions enabling this enumerant - parameters: a sequence of (operand-kind, operand-quantifier) tuples - version: minimal SPIR-V version required for this opcode - lastVersion: last SPIR-V version this opode appears """ self.enumerant = enumerant self.value = value self.num_caps = len(caps) self.caps = get_capability_array_name(caps) self.num_exts = len(exts) self.exts = get_extension_array_name(exts) self.parameters = [convert_operand_kind(p) for p in parameters] self.version = convert_min_required_version(version) self.lastVersion = convert_max_required_version(lastVersion) def __str__(self): template = ['{{"{enumerant}"', '{value}', '{num_caps}', '{caps}', '{num_exts}', '{exts}', '{{{parameters}}}', '{min_version}', '{max_version}}}'] return ', '.join(template).format( enumerant=self.enumerant, value=self.value, num_caps=self.num_caps, caps=self.caps, num_exts=self.num_exts, exts=self.exts, parameters=', '.join(self.parameters), min_version=self.version, max_version=self.lastVersion) def generate_enum_operand_kind_entry(entry, extension_map): """Returns the C initializer for the given operand enum entry. Arguments: - entry: a dict containing information about an enum entry - extension_map: a dict mapping enum value to list of extensions Returns: a string containing the C initializer for spv_operand_desc_t """ enumerant = entry.get('enumerant') value = entry.get('value') caps = entry.get('capabilities', []) if value in extension_map: exts = extension_map[value] else: exts = [] params = entry.get('parameters', []) params = [p.get('kind') for p in params] params = zip(params, [''] * len(params)) version = entry.get('version', None) max_version = entry.get('lastVersion', None) assert enumerant is not None assert value is not None return str(EnumerantInitializer( enumerant, value, caps, exts, params, version, max_version)) def generate_enum_operand_kind(enum, synthetic_exts_list): """Returns the C definition for the given operand kind. It's a static const named array of spv_operand_desc_t. Also appends to |synthetic_exts_list| a list of extension lists used. """ kind = enum.get('kind') assert kind is not None # Sort all enumerants according to their values, but otherwise # preserve their order so the first name listed in the grammar # as the preferred name for disassembly. if enum.get('category') == 'ValueEnum': def functor(k): return (k['value']) else: def functor(k): return (int(k['value'], 16)) entries = sorted(enum.get('enumerants', []), key=functor) # SubgroupEqMask and SubgroupEqMaskKHR are the same number with # same semantics, but one has no extension list while the other # does. Both should have the extension list. # So create a mapping from enum value to the union of the extensions # across all those grammar entries. Preserve order. extension_map = {} for e in entries: value = e.get('value') extension_map[value] = [] for e in entries: value = e.get('value') exts = e.get('extensions', []) for ext in exts: if ext not in extension_map[value]: extension_map[value].append(ext) synthetic_exts_list.extend(extension_map.values()) name = '{}_{}Entries'.format(PYGEN_VARIABLE_PREFIX, kind) entries = [' {}'.format(generate_enum_operand_kind_entry(e, extension_map)) for e in entries] template = ['static const spv_operand_desc_t {name}[] = {{', '{entries}', '}};'] entries = '\n'.join(template).format( name=name, entries=',\n'.join(entries)) return kind, name, entries def generate_operand_kind_table(enums): """Returns the info table containing all SPIR-V operand kinds.""" # We only need to output info tables for those operand kinds that are enums. enums = [e for e in enums if e.get('category') in ['ValueEnum', 'BitEnum']] caps = [entry.get('capabilities', []) for enum in enums for entry in enum.get('enumerants', [])] caps_arrays = generate_capability_arrays(caps) exts = [entry.get('extensions', []) for enum in enums for entry in enum.get('enumerants', [])] enums = [generate_enum_operand_kind(e, exts) for e in enums] exts_arrays = generate_extension_arrays(exts) # We have three operand kinds that requires their optional counterpart to # exist in the operand info table. three_optional_enums = ['ImageOperands', 'AccessQualifier', 'MemoryAccess'] three_optional_enums = [e for e in enums if e[0] in three_optional_enums] enums.extend(three_optional_enums) enum_kinds, enum_names, enum_entries = zip(*enums) # Mark the last three as optional ones. enum_quantifiers = [''] * (len(enums) - 3) + ['?'] * 3 # And we don't want redefinition of them. enum_entries = enum_entries[:-3] enum_kinds = [convert_operand_kind(e) for e in zip(enum_kinds, enum_quantifiers)] table_entries = zip(enum_kinds, enum_names, enum_names) table_entries = [' {{{}, ARRAY_SIZE({}), {}}}'.format(*e) for e in table_entries] template = [ 'static const spv_operand_desc_group_t {p}_OperandInfoTable[] = {{', '{enums}', '}};'] table = '\n'.join(template).format( p=PYGEN_VARIABLE_PREFIX, enums=',\n'.join(table_entries)) return '\n\n'.join((caps_arrays,) + (exts_arrays,) + enum_entries + (table,)) def get_extension_list(instructions, operand_kinds): """Returns extensions as an alphabetically sorted list of strings.""" things_with_an_extensions_field = [item for item in instructions] enumerants = sum([item.get('enumerants', []) for item in operand_kinds], []) things_with_an_extensions_field.extend(enumerants) extensions = sum([item.get('extensions', []) for item in things_with_an_extensions_field if item.get('extensions')], []) for item in EXTENSIONS_FROM_SPIRV_REGISTRY_AND_NOT_FROM_GRAMMARS.split(): # If it's already listed in a grammar, then don't put it in the # special exceptions list. assert item not in extensions, 'Extension %s is already in a grammar file' % item extensions.extend( EXTENSIONS_FROM_SPIRV_REGISTRY_AND_NOT_FROM_GRAMMARS.split()) # Validator would ignore type declaration unique check. Should only be used # for legacy autogenerated test files containing multiple instances of the # same type declaration, if fixing the test by other methods is too # difficult. Shouldn't be used for any other reasons. extensions.append('SPV_VALIDATOR_ignore_type_decl_unique') return sorted(set(extensions)) def get_capabilities(operand_kinds): """Returns capabilities as a list of JSON objects, in order of appearance.""" enumerants = sum([item.get('enumerants', []) for item in operand_kinds if item.get('kind') in ['Capability']], []) return enumerants def generate_extension_enum(extensions): """Returns enumeration containing extensions declared in the grammar.""" return ',\n'.join(['k' + extension for extension in extensions]) def generate_extension_to_string_mapping(extensions): """Returns mapping function from extensions to corresponding strings.""" function = 'const char* ExtensionToString(Extension extension) {\n' function += ' switch (extension) {\n' template = ' case Extension::k{extension}:\n' \ ' return "{extension}";\n' function += ''.join([template.format(extension=extension) for extension in extensions]) function += ' };\n\n return "";\n}' return function def generate_string_to_extension_mapping(extensions): """Returns mapping function from strings to corresponding extensions.""" function = ''' bool GetExtensionFromString(const char* str, Extension* extension) {{ static const char* known_ext_strs[] = {{ {strs} }}; static const Extension known_ext_ids[] = {{ {ids} }}; const auto b = std::begin(known_ext_strs); const auto e = std::end(known_ext_strs); const auto found = std::equal_range( b, e, str, [](const char* str1, const char* str2) {{ return std::strcmp(str1, str2) < 0; }}); if (found.first == e || found.first == found.second) return false; *extension = known_ext_ids[found.first - b]; return true; }} '''.format(strs=', '.join(['"{}"'.format(e) for e in extensions]), ids=', '.join(['Extension::k{}'.format(e) for e in extensions])) return function def generate_capability_to_string_mapping(operand_kinds): """Returns mapping function from capabilities to corresponding strings. We take care to avoid emitting duplicate values. """ function = 'const char* CapabilityToString(SpvCapability capability) {\n' function += ' switch (capability) {\n' template = ' case SpvCapability{capability}:\n' \ ' return "{capability}";\n' emitted = set() # The values of capabilities we already have emitted for capability in get_capabilities(operand_kinds): value = capability.get('value') if value not in emitted: emitted.add(value) function += template.format(capability=capability.get('enumerant')) function += ' case SpvCapabilityMax:\n' \ ' assert(0 && "Attempting to convert SpvCapabilityMax to string");\n' \ ' return "";\n' function += ' };\n\n return "";\n}' return function def generate_all_string_enum_mappings(extensions, operand_kinds): """Returns all string-to-enum / enum-to-string mapping tables.""" tables = [] tables.append(generate_extension_to_string_mapping(extensions)) tables.append(generate_string_to_extension_mapping(extensions)) tables.append(generate_capability_to_string_mapping(operand_kinds)) return '\n\n'.join(tables) def precondition_operand_kinds(operand_kinds): """For operand kinds that have the same number, make sure they all have the same extension list.""" # Map operand kind and value to list of the union of extensions # for same-valued enumerants. exts = {} for kind_entry in operand_kinds: kind = kind_entry.get('kind') for enum_entry in kind_entry.get('enumerants', []): value = enum_entry.get('value') key = kind + '.' + str(value) if key in exts: exts[key].extend(enum_entry.get('extensions', [])) else: exts[key] = enum_entry.get('extensions', []) exts[key] = sorted(set(exts[key])) # Now make each entry the same list. for kind_entry in operand_kinds: kind = kind_entry.get('kind') for enum_entry in kind_entry.get('enumerants', []): value = enum_entry.get('value') key = kind + '.' + str(value) if len(exts[key]) > 0: enum_entry['extensions'] = exts[key] return operand_kinds def prefix_operand_kind_names(prefix, json_dict): """Modifies json_dict, by prefixing all the operand kind names with the given prefix. Also modifies their uses in the instructions to match. """ old_to_new = {} for operand_kind in json_dict["operand_kinds"]: old_name = operand_kind["kind"] new_name = prefix + old_name operand_kind["kind"] = new_name old_to_new[old_name] = new_name for instruction in json_dict["instructions"]: for operand in instruction.get("operands", []): replacement = old_to_new.get(operand["kind"]) if replacement is not None: operand["kind"] = replacement def main(): import argparse parser = argparse.ArgumentParser(description='Generate SPIR-V info tables') parser.add_argument('--spirv-core-grammar', metavar='<path>', type=str, required=False, help='input JSON grammar file for core SPIR-V ' 'instructions') parser.add_argument('--extinst-debuginfo-grammar', metavar='<path>', type=str, required=False, default=None, help='input JSON grammar file for DebugInfo extended ' 'instruction set') parser.add_argument('--extinst-cldebuginfo100-grammar', metavar='<path>', type=str, required=False, default=None, help='input JSON grammar file for OpenCL.DebugInfo.100 ' 'extended instruction set') parser.add_argument('--extinst-glsl-grammar', metavar='<path>', type=str, required=False, default=None, help='input JSON grammar file for GLSL extended ' 'instruction set') parser.add_argument('--extinst-opencl-grammar', metavar='<path>', type=str, required=False, default=None, help='input JSON grammar file for OpenCL extended ' 'instruction set') parser.add_argument('--core-insts-output', metavar='<path>', type=str, required=False, default=None, help='output file for core SPIR-V instructions') parser.add_argument('--glsl-insts-output', metavar='<path>', type=str, required=False, default=None, help='output file for GLSL extended instruction set') parser.add_argument('--opencl-insts-output', metavar='<path>', type=str, required=False, default=None, help='output file for OpenCL extended instruction set') parser.add_argument('--operand-kinds-output', metavar='<path>', type=str, required=False, default=None, help='output file for operand kinds') parser.add_argument('--extension-enum-output', metavar='<path>', type=str, required=False, default=None, help='output file for extension enumeration') parser.add_argument('--enum-string-mapping-output', metavar='<path>', type=str, required=False, default=None, help='output file for enum-string mappings') parser.add_argument('--extinst-vendor-grammar', metavar='<path>', type=str, required=False, default=None, help='input JSON grammar file for vendor extended ' 'instruction set'), parser.add_argument('--vendor-insts-output', metavar='<path>', type=str, required=False, default=None, help='output file for vendor extended instruction set') parser.add_argument('--vendor-operand-kind-prefix', metavar='<string>', type=str, required=False, default=None, help='prefix for operand kinds (to disambiguate operand type enums)') args = parser.parse_args() # The GN build system needs this because it doesn't handle quoting # empty string arguments well. if args.vendor_operand_kind_prefix == "...nil...": args.vendor_operand_kind_prefix = "" if (args.core_insts_output is None) != \ (args.operand_kinds_output is None): print('error: --core-insts-output and --operand-kinds-output ' 'should be specified together.') exit(1) if args.operand_kinds_output and not (args.spirv_core_grammar and args.extinst_debuginfo_grammar and args.extinst_cldebuginfo100_grammar): print('error: --operand-kinds-output requires --spirv-core-grammar ' 'and --extinst-debuginfo-grammar ' 'and --extinst-cldebuginfo100-grammar') exit(1) if (args.glsl_insts_output is None) != \ (args.extinst_glsl_grammar is None): print('error: --glsl-insts-output and --extinst-glsl-grammar ' 'should be specified together.') exit(1) if (args.opencl_insts_output is None) != \ (args.extinst_opencl_grammar is None): print('error: --opencl-insts-output and --extinst-opencl-grammar ' 'should be specified together.') exit(1) if (args.vendor_insts_output is None) != \ (args.extinst_vendor_grammar is None): print('error: --vendor-insts-output and ' '--extinst-vendor-grammar should be specified together.') exit(1) if all([args.core_insts_output is None, args.glsl_insts_output is None, args.opencl_insts_output is None, args.vendor_insts_output is None, args.extension_enum_output is None, args.enum_string_mapping_output is None]): print('error: at least one output should be specified.') exit(1) if args.spirv_core_grammar is not None: with open(args.spirv_core_grammar) as json_file: core_grammar = json.loads(json_file.read()) with open(args.extinst_debuginfo_grammar) as debuginfo_json_file: debuginfo_grammar = json.loads(debuginfo_json_file.read()) with open(args.extinst_cldebuginfo100_grammar) as cldebuginfo100_json_file: cldebuginfo100_grammar = json.loads(cldebuginfo100_json_file.read()) prefix_operand_kind_names("CLDEBUG100_", cldebuginfo100_grammar) instructions = [] instructions.extend(core_grammar['instructions']) instructions.extend(debuginfo_grammar['instructions']) instructions.extend(cldebuginfo100_grammar['instructions']) operand_kinds = [] operand_kinds.extend(core_grammar['operand_kinds']) operand_kinds.extend(debuginfo_grammar['operand_kinds']) operand_kinds.extend(cldebuginfo100_grammar['operand_kinds']) extensions = get_extension_list(instructions, operand_kinds) operand_kinds = precondition_operand_kinds(operand_kinds) if args.core_insts_output is not None: make_path_to_file(args.core_insts_output) make_path_to_file(args.operand_kinds_output) with open(args.core_insts_output, 'w') as f: f.write(generate_instruction_table( core_grammar['instructions'])) with open(args.operand_kinds_output, 'w') as f: f.write(generate_operand_kind_table(operand_kinds)) if args.extension_enum_output is not None: make_path_to_file(args.extension_enum_output) with open(args.extension_enum_output, 'w') as f: f.write(generate_extension_enum(extensions)) if args.enum_string_mapping_output is not None: make_path_to_file(args.enum_string_mapping_output) with open(args.enum_string_mapping_output, 'w') as f: f.write(generate_all_string_enum_mappings( extensions, operand_kinds)) if args.extinst_glsl_grammar is not None: with open(args.extinst_glsl_grammar) as json_file: grammar = json.loads(json_file.read()) make_path_to_file(args.glsl_insts_output) with open(args.glsl_insts_output, 'w') as f: f.write(generate_extended_instruction_table( grammar, 'glsl')) if args.extinst_opencl_grammar is not None: with open(args.extinst_opencl_grammar) as json_file: grammar = json.loads(json_file.read()) make_path_to_file(args.opencl_insts_output) with open(args.opencl_insts_output, 'w') as f: f.write(generate_extended_instruction_table( grammar, 'opencl')) if args.extinst_vendor_grammar is not None: with open(args.extinst_vendor_grammar) as json_file: grammar = json.loads(json_file.read()) make_path_to_file(args.vendor_insts_output) name = args.extinst_vendor_grammar start = name.find('extinst.') + len('extinst.') name = name[start:-len('.grammar.json')].replace('-', '_') with open(args.vendor_insts_output, 'w') as f: f.write(generate_extended_instruction_table( grammar, name, args.vendor_operand_kind_prefix)) if __name__ == '__main__': main()
apache-2.0
samthor/intellij-community
python/lib/Lib/site-packages/django/contrib/localflavor/jp/jp_prefectures.py
543
2089
from django.utils.translation import ugettext_lazy JP_PREFECTURES = ( ('hokkaido', ugettext_lazy('Hokkaido'),), ('aomori', ugettext_lazy('Aomori'),), ('iwate', ugettext_lazy('Iwate'),), ('miyagi', ugettext_lazy('Miyagi'),), ('akita', ugettext_lazy('Akita'),), ('yamagata', ugettext_lazy('Yamagata'),), ('fukushima', ugettext_lazy('Fukushima'),), ('ibaraki', ugettext_lazy('Ibaraki'),), ('tochigi', ugettext_lazy('Tochigi'),), ('gunma', ugettext_lazy('Gunma'),), ('saitama', ugettext_lazy('Saitama'),), ('chiba', ugettext_lazy('Chiba'),), ('tokyo', ugettext_lazy('Tokyo'),), ('kanagawa', ugettext_lazy('Kanagawa'),), ('yamanashi', ugettext_lazy('Yamanashi'),), ('nagano', ugettext_lazy('Nagano'),), ('niigata', ugettext_lazy('Niigata'),), ('toyama', ugettext_lazy('Toyama'),), ('ishikawa', ugettext_lazy('Ishikawa'),), ('fukui', ugettext_lazy('Fukui'),), ('gifu', ugettext_lazy('Gifu'),), ('shizuoka', ugettext_lazy('Shizuoka'),), ('aichi', ugettext_lazy('Aichi'),), ('mie', ugettext_lazy('Mie'),), ('shiga', ugettext_lazy('Shiga'),), ('kyoto', ugettext_lazy('Kyoto'),), ('osaka', ugettext_lazy('Osaka'),), ('hyogo', ugettext_lazy('Hyogo'),), ('nara', ugettext_lazy('Nara'),), ('wakayama', ugettext_lazy('Wakayama'),), ('tottori', ugettext_lazy('Tottori'),), ('shimane', ugettext_lazy('Shimane'),), ('okayama', ugettext_lazy('Okayama'),), ('hiroshima', ugettext_lazy('Hiroshima'),), ('yamaguchi', ugettext_lazy('Yamaguchi'),), ('tokushima', ugettext_lazy('Tokushima'),), ('kagawa', ugettext_lazy('Kagawa'),), ('ehime', ugettext_lazy('Ehime'),), ('kochi', ugettext_lazy('Kochi'),), ('fukuoka', ugettext_lazy('Fukuoka'),), ('saga', ugettext_lazy('Saga'),), ('nagasaki', ugettext_lazy('Nagasaki'),), ('kumamoto', ugettext_lazy('Kumamoto'),), ('oita', ugettext_lazy('Oita'),), ('miyazaki', ugettext_lazy('Miyazaki'),), ('kagoshima', ugettext_lazy('Kagoshima'),), ('okinawa', ugettext_lazy('Okinawa'),), )
apache-2.0
assefay/inasafe
safe/engine/impact_functions_for_testing/padang_building_impact_model.py
4
7222
"""Impact function based on Padang 2009 post earthquake survey This impact function estimates percentual damage to buildings as a function of ground shaking measured in MMI. Buildings are assumed to fall the 9 classes below as described in the Geoscience Australia/ITB 2009 Padang earthquake survey (http://trove.nla.gov.au/work/38470066). Class Building Type Median (MMI) Beta (MMI) ------------------------------------------------------------------------- 1 URM with river rock walls 7.5 0.11 2 URM with Metal Roof 8.3 0.1 3 Timber frame with masonry in-fill 8.8 0.11 4 RC medium rise Frame with Masonry in-fill walls 8.4 0.05 5 Timber frame with stucco in-fill 9.2 0.11 6 Concrete Shear wall high rise* Hazus C2H 9.7 0.15 7 RC low rise Frame with Masonry in-fill walls 9 0.08 8 Confined Masonry 8.9 0.07 9 Timber frame residential 10.5 0.15 """ from safe.impact_functions.core import (FunctionProvider, get_hazard_layer, get_exposure_layer, get_question) from safe.storage.vector import Vector from safe.common.utilities import (ugettext as tr, format_int) from safe.common.numerics import log_normal_cdf from safe.common.tables import Table, TableRow from safe.impact_functions.mappings import osm2padang, sigab2padang from safe.engine.interpolation import assign_hazard_values_to_exposure_data # Damage curves for each of the nine classes derived from the Padang survey damage_curves = {1: dict(median=7.5, beta=0.11), 2: dict(median=8.3, beta=0.1), 3: dict(median=8.8, beta=0.11), 4: dict(median=8.4, beta=0.05), 5: dict(median=9.2, beta=0.11), 6: dict(median=9.7, beta=0.15), 7: dict(median=9.0, beta=0.08), 8: dict(median=8.9, beta=0.07), 9: dict(median=10.5, beta=0.15)} class PadangEarthquakeBuildingDamageFunction(FunctionProvider): """Impact function for Padang earthquake damage to buildings :param requires category=='hazard' and \ subcategory=='earthquake' and \ layertype=='raster' and \ unit=='MMI' :param requires category=='exposure' and \ subcategory=='structure' and \ layertype=='vector' and \ datatype in ['osm', 'itb', 'sigab'] """ title = tr('Be damaged depending on building type') def run(self, layers): """Risk plugin for Padang building survey """ # Extract data H = get_hazard_layer(layers) # Ground shaking E = get_exposure_layer(layers) # Building locations question = get_question(H.get_name(), E.get_name(), self) # Map from different kinds of datasets to Padang vulnerability classes datatype = E.get_keywords()['datatype'] vclass_tag = 'VCLASS' if datatype.lower() == 'osm': # Map from OSM attributes Emap = osm2padang(E) elif datatype.lower() == 'sigab': # Map from SIGAB attributes Emap = sigab2padang(E) else: Emap = E # Interpolate hazard level to building locations I = assign_hazard_values_to_exposure_data(H, Emap, attribute_name='MMI') # Extract relevant numerical data attributes = I.get_data() N = len(I) # Calculate building damage count_high = count_medium = count_low = count_none = 0 for i in range(N): mmi = float(attributes[i]['MMI']) building_type = Emap.get_data(vclass_tag, i) damage_params = damage_curves[building_type] beta = damage_params['beta'] median = damage_params['median'] percent_damage = log_normal_cdf(mmi, median=median, sigma=beta) * 100 # Add calculated impact to existing attributes attributes[i][self.target_field] = percent_damage # Calculate statistics if percent_damage < 10: count_none += 1 if 10 <= percent_damage < 33: count_low += 1 if 33 <= percent_damage < 66: count_medium += 1 if 66 <= percent_damage: count_high += 1 # Generate impact report table_body = [question, TableRow([tr('Buildings'), tr('Total')], header=True), TableRow([tr('All'), N]), TableRow([tr('No damage'), format_int(count_none)]), TableRow([tr('Low damage'), format_int(count_low)]), TableRow([tr('Medium damage'), format_int(count_medium)]), TableRow([tr('High damage'), format_int(count_high)])] table_body.append(TableRow(tr('Notes'), header=True)) table_body.append(tr('Levels of impact are defined by post 2009 ' 'Padang earthquake survey conducted by Geoscience ' 'Australia and Institute of Teknologi Bandung.')) table_body.append(tr('Unreinforced masonry is assumed where no ' 'structural information is available.')) impact_summary = Table(table_body).toNewlineFreeString() impact_table = impact_summary map_title = tr('Earthquake damage to buildings') # Create style style_classes = [dict(label=tr('No damage'), min=0, max=10, colour='#00ff00', transparency=0), dict(label=tr('Low damage'), min=10, max=33, colour='#ffff00', transparency=0), dict(label=tr('Medium damage'), min=33, max=66, colour='#ffaa00', transparency=0), dict(label=tr('High damage'), min=66, max=100, colour='#ff0000', transparency=0)] style_info = dict(target_field=self.target_field, style_classes=style_classes) # Create vector layer and return V = Vector(data=attributes, projection=E.get_projection(), geometry=E.get_geometry(), name='Estimated pct damage', keywords={'impact_summary': impact_summary, 'impact_table': impact_table, 'map_title': map_title, 'target_field': self.target_field}, style_info=style_info) return V
gpl-3.0
andmos/ansible
test/units/modules/network/f5/test_bigip_ssl_key.py
21
3292
# -*- coding: utf-8 -*- # # Copyright (c) 2017 F5 Networks Inc. # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import pytest import sys if sys.version_info < (2, 7): pytestmark = pytest.mark.skip("F5 Ansible modules require Python >= 2.7") from ansible.module_utils.basic import AnsibleModule try: from library.modules.bigip_ssl_key import ArgumentSpec from library.modules.bigip_ssl_key import ModuleParameters from library.modules.bigip_ssl_key import ModuleManager # In Ansible 2.8, Ansible changed import paths. from test.units.compat import unittest from test.units.compat.mock import Mock from test.units.compat.mock import patch from test.units.modules.utils import set_module_args except ImportError: from ansible.modules.network.f5.bigip_ssl_key import ArgumentSpec from ansible.modules.network.f5.bigip_ssl_key import ModuleParameters from ansible.modules.network.f5.bigip_ssl_key import ModuleManager # Ansible 2.8 imports from units.compat import unittest from units.compat.mock import Mock from units.compat.mock import patch from units.modules.utils import set_module_args fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures') fixture_data = {} def load_fixture(name): path = os.path.join(fixture_path, name) if path in fixture_data: return fixture_data[path] with open(path) as f: data = f.read() try: data = json.loads(data) except Exception: pass fixture_data[path] = data return data class TestParameters(unittest.TestCase): def test_module_parameters_key(self): key_content = load_fixture('create_insecure_key1.key') args = dict( content=key_content, name="cert1", partition="Common", state="present", password='password', server='localhost', user='admin' ) p = ModuleParameters(params=args) assert p.name == 'cert1' assert p.key_filename == 'cert1.key' assert '-----BEGIN RSA PRIVATE KEY-----' in p.content assert '-----END RSA PRIVATE KEY-----' in p.content assert p.key_checksum == '91bdddcf0077e2bb2a0258aae2ae3117be392e83' assert p.state == 'present' class TestModuleManager(unittest.TestCase): def setUp(self): self.spec = ArgumentSpec() def test_import_key_no_key_passphrase(self, *args): set_module_args(dict( name='foo', content=load_fixture('cert1.key'), state='present', password='password', server='localhost', user='admin' )) module = AnsibleModule( argument_spec=self.spec.argument_spec, supports_check_mode=self.spec.supports_check_mode ) # Override methods in the specific type of manager cm = ModuleManager(module=module) cm.exists = Mock(side_effect=[False, True]) cm.create_on_device = Mock(return_value=True) results = cm.exec_module() assert results['changed'] is True
gpl-3.0
zbase/zbase-backup-tools
src/file_server.py
1
10351
#!/usr/bin/env python26 # Copyright 2013 Zynga 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 sys, os import thread, threading from logger import Logger from time import sleep import pdb import socket from sendfile import sendfile import commands import json import consts import util #from util import pause_coalscer, resume_coalescer #globals DEFAULT_SERVER_PORT = 22122 #Error messages INVALID_SYNTAX = "-1\r\nInvalid Syntax\r\n" INVALID_COMMAND = "-1\r\nInvalid Command\r\n" ENOEXIST = "-1\r\nFile not found\r\n" INVALID_TYPE = "-1\r\nInvalid type\r\n" INTERROR = "-1\r\nInternal Error\r\n" ISDIR = "-1\r\nRequested download is a directory\r\n" class FileServer: def __init__(self, disk_mapper, host=None, port=None): self.disk_mapper = disk_mapper if host != None: self.host = host else: self.host = '0.0.0.0' if port != None: self.port = port else: self.port = 22122 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = (self.host, self.port) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind(server_address) self.logger = Logger("RestoreDaemon", "INFO") self.logger.log("Info: ===== Starting restore daemon ====== ") def request_thread(self, connection, client_address): while 1: data = connection.recv(4096) if data == '': print ("Info: client closed connection") connection.close() return data = data.rstrip() try: response_len = self.handle_cmd(connection, data) except Exception, e: connection.send("-1\r\n" + str(e) + "\r\n") continue if response_len == -1: connection.close() return def query_dm(self, vb_id): #query the disk_mapper and get the disk path vb_query_cmd = "curl -s \"http://" + self.disk_mapper + "/api?action=get_vb_mapping&&vbucket=vb_" + vb_id + "\"" status, output = commands.getstatusoutput(vb_query_cmd) if status > 0: print "Failed to execute command %s. Output %s" %(vb_query_cmd, output) return None try: response = json.loads(output) return response except Exception, e: print >> sys.stderr, " Could not json parse output", str(e) return None def get_disk_path(self, vb_id): vb_id = vb_id.lstrip('0') if vb_id == "": vb_id = '0' response = self.query_dm(vb_id) if response == None: return None disk_path = "/"+ response["disk"] + "/" + response["type"] + "/" + response["vb_group"] + "/" + "vb_" + vb_id + "/" return disk_path def get_disk_basepath(self, vb_id): vb_id = vb_id.lstrip('0') if vb_id == "": vb_id = '0' response = self.query_dm(vb_id) if response == None: return None disk_path = "/"+ response["disk"] return disk_path def start(self): self.sock.listen(1) while True: connection, client_address = self.sock.accept() print >>sys.stderr, 'connection from', client_address thread.start_new_thread(self.request_thread, (connection, client_address)) #LIST vb_id filename def handle_download(self, connection=None, data=None, checkpoint_only=False): data = data.split() if checkpoint_only == False: if len(data) != 3: return connection.send(INVALID_SYNTAX) filename = data[2] else: if len(data) != 2: return connection.send(INVALID_SYNTAX) vb_id = str(data[1]).zfill(2) base_path = self.get_disk_path(vb_id) if base_path == None: return connection.send(INTERROR) if checkpoint_only == True: vb_id = vb_id.lstrip('0') if vb_id == "": vb_id = '0' file_path = base_path + "/vbid_" + vb_id + "_" + consts.LAST_CHECKPOINT_FILE else: file_path = base_path + filename if os.path.exists(file_path) == False: return connection.send(ENOEXIST) if os.path.isdir(file_path) == True: return connection.send(ISDIR) print ("info sending file %s" %file_path) file = open(file_path, "rb") size = os.stat(file_path).st_size response_line = str(size) + '\r\n' sent = connection.send(response_line) sent += sendfile(connection.fileno(), file.fileno(), 0, size) sent += connection.send('\r\n') file.close() return sent def handle_lock(self, connection=None, data=None): data = data.split() if len(data) != 3: return connection.send(INVALID_SYNTAX) vb_id = str(data[1]).zfill(2) filename = data[2] base_path = self.get_disk_path(vb_id) if base_path == None: return connection.send(INTERROR) file_path = base_path + filename if os.path.exists(file_path) == True: return connection.send(ENOEXIST) print (" adding lock %s" %file_path) file = open(file_path, "w+") size = os.stat(file_path).st_size sent = connection.send("0\r\n") file.close() return sent def handle_pause(self, connection=None, data=None): data = data.split() if len(data) != 2: return connection.send(INVALID_SYNTAX) vb_id = str(data[1]).zfill(2) base_path = self.get_disk_basepath(vb_id) if base_path == None: return connection.send(INTERROR) util.pause_coalescer(self.logger, base_path) sent = connection.send("0\r\n") return sent def handle_resume(self, connection=None, data=None): data = data.split() if len(data) != 2: return connection.send(INVALID_SYNTAX) vb_id = str(data[1]).zfill(2) base_path = self.get_disk_basepath(vb_id) if base_path == None: return connection.send(INTERROR) util.resume_coalescer(self.logger, base_path) sent = connection.send("0\r\n") return sent #LIST vb_id volume type date_string def handle_list(self, connection=None, data=None): vb_id = 0 data = data.split() if len(data) != 2 and len(data) != 3: return connection.send(INVALID_SYNTAX) vb_id = str(data[1]).zfill(2) list_path = self.get_disk_path(vb_id) if list_path == None: return connection.send(INTERROR) if len(data) == 3: extra = data[2].rstrip('/') list_path = list_path + extra + '/' try: output = os.listdir(list_path) except Exception, e: print ("Problem happen ", str(e)) return connection.send(ENOEXIST) ##format output formatted_output = "" for entry in output: if len(data) == 3: formatted_output += (extra + '/' + entry + "\r\n") else: formatted_output += (entry + "\r\n") return self.send_data(connection, formatted_output) def send_data(self, connection=None, output=None): if connection == None: return -1 response_line = str(len(output)) + "\r\n" try: return_len = connection.send(response_line) return_len += connection.send(output) #return_len += connection.send("\r\n") except e, Exception: print >>sys.stderr, 'sending failed : ', str(e) return return_len def handle_remove(self, connection=None, data=None): data = data.split() if len(data) != 3: return connection.send(INVALID_SYNTAX) vb_id = str(data[1]).zfill(2) filename = data[2] base_path = self.get_disk_path(vb_id) if base_path == None: return connection.send(INTERROR) file_path = base_path + filename if os.path.exists(file_path) == False: return connection.send(ENOEXIST) delete_cmd = "rm -f " + file_path print ("Executing command %s" %delete_cmd) status,output = commands.getstatusoutput(delete_cmd) if status != 0: print ("Delete failed with reason %s" %output) return connection.send("-1\r\n" + output + "\r\n") # success return connection.send("0\r\n") def handle_cmd(self, connection=None, data=None): if data == None: return -1 elif "LIST" in data: return self.handle_list(connection, data) elif "REMOVE" in data: return self.handle_remove(connection, data) elif "DOWNLOAD" in data: return self.handle_download(connection, data) elif "ADDLOCK" in data: return self.handle_lock(connection, data) elif "GETCHECKPOINT" in data: return self.handle_download(connection, data, True) elif "PAUSECOALESCER" in data: return self.handle_pause(connection, data) elif "RESUMECOALESCER" in data: return self.handle_resume(connection, data) else: return connection.send(INVALID_COMMAND) if __name__ == '__main__': if len(sys.argv) != 2: print ("Usage file_server.py disk_mapper") sys.exit(1) else: disk_mapper = sys.argv[1] server_instance = FileServer(disk_mapper, "0.0.0.0", 22122) server_instance.start()
apache-2.0
mameneses/python-deployment
venv/lib/python2.7/site-packages/setuptools/svn_utils.py
98
18879
import os import re import sys from distutils import log import xml.dom.pulldom import shlex import locale import codecs import unicodedata import warnings from setuptools.compat import unicode from setuptools.py31compat import TemporaryDirectory from xml.sax.saxutils import unescape try: import urlparse except ImportError: import urllib.parse as urlparse from subprocess import Popen as _Popen, PIPE as _PIPE #NOTE: Use of the command line options require SVN 1.3 or newer (December 2005) # and SVN 1.3 hasn't been supported by the developers since mid 2008. #subprocess is called several times with shell=(sys.platform=='win32') #see the follow for more information: # http://bugs.python.org/issue8557 # http://stackoverflow.com/questions/5658622/ # python-subprocess-popen-environment-path def _run_command(args, stdout=_PIPE, stderr=_PIPE, encoding=None, stream=0): #regarding the shell argument, see: http://bugs.python.org/issue8557 try: proc = _Popen(args, stdout=stdout, stderr=stderr, shell=(sys.platform == 'win32')) data = proc.communicate()[stream] except OSError: return 1, '' #doubled checked and data = decode_as_string(data, encoding) #communciate calls wait() return proc.returncode, data def _get_entry_schedule(entry): schedule = entry.getElementsByTagName('schedule')[0] return "".join([t.nodeValue for t in schedule.childNodes if t.nodeType == t.TEXT_NODE]) def _get_target_property(target): property_text = target.getElementsByTagName('property')[0] return "".join([t.nodeValue for t in property_text.childNodes if t.nodeType == t.TEXT_NODE]) def _get_xml_data(decoded_str): if sys.version_info < (3, 0): #old versions want an encoded string data = decoded_str.encode('utf-8') else: data = decoded_str return data def joinpath(prefix, *suffix): if not prefix or prefix == '.': return os.path.join(*suffix) return os.path.join(prefix, *suffix) def determine_console_encoding(): try: #try for the preferred encoding encoding = locale.getpreferredencoding() #see if the locale.getdefaultlocale returns null #some versions of python\platforms return US-ASCII #when it cannot determine an encoding if not encoding or encoding == "US-ASCII": encoding = locale.getdefaultlocale()[1] if encoding: codecs.lookup(encoding) # make sure a lookup error is not made except (locale.Error, LookupError): encoding = None is_osx = sys.platform == "darwin" if not encoding: return ["US-ASCII", "utf-8"][is_osx] elif encoding.startswith("mac-") and is_osx: #certain versions of python would return mac-roman as default #OSX as a left over of earlier mac versions. return "utf-8" else: return encoding _console_encoding = determine_console_encoding() def decode_as_string(text, encoding=None): """ Decode the console or file output explicitly using getpreferredencoding. The text paraemeter should be a encoded string, if not no decode occurs If no encoding is given, getpreferredencoding is used. If encoding is specified, that is used instead. This would be needed for SVN --xml output. Unicode is explicitly put in composed NFC form. --xml should be UTF-8 (SVN Issue 2938) the discussion on the Subversion DEV List from 2007 seems to indicate the same. """ #text should be a byte string if encoding is None: encoding = _console_encoding if not isinstance(text, unicode): text = text.decode(encoding) text = unicodedata.normalize('NFC', text) return text def parse_dir_entries(decoded_str): '''Parse the entries from a recursive info xml''' doc = xml.dom.pulldom.parseString(_get_xml_data(decoded_str)) entries = list() for event, node in doc: if event == 'START_ELEMENT' and node.nodeName == 'entry': doc.expandNode(node) if not _get_entry_schedule(node).startswith('delete'): entries.append((node.getAttribute('path'), node.getAttribute('kind'))) return entries[1:] # do not want the root directory def parse_externals_xml(decoded_str, prefix=''): '''Parse a propget svn:externals xml''' prefix = os.path.normpath(prefix) prefix = os.path.normcase(prefix) doc = xml.dom.pulldom.parseString(_get_xml_data(decoded_str)) externals = list() for event, node in doc: if event == 'START_ELEMENT' and node.nodeName == 'target': doc.expandNode(node) path = os.path.normpath(node.getAttribute('path')) if os.path.normcase(path).startswith(prefix): path = path[len(prefix)+1:] data = _get_target_property(node) #data should be decoded already for external in parse_external_prop(data): externals.append(joinpath(path, external)) return externals # do not want the root directory def parse_external_prop(lines): """ Parse the value of a retrieved svn:externals entry. possible token setups (with quotng and backscaping in laters versions) URL[@#] EXT_FOLDERNAME [-r#] URL EXT_FOLDERNAME EXT_FOLDERNAME [-r#] URL """ externals = [] for line in lines.splitlines(): line = line.lstrip() # there might be a "\ " if not line: continue if sys.version_info < (3, 0): #shlex handles NULLs just fine and shlex in 2.7 tries to encode #as ascii automatiically line = line.encode('utf-8') line = shlex.split(line) if sys.version_info < (3, 0): line = [x.decode('utf-8') for x in line] #EXT_FOLDERNAME is either the first or last depending on where #the URL falls if urlparse.urlsplit(line[-1])[0]: external = line[0] else: external = line[-1] external = decode_as_string(external, encoding="utf-8") externals.append(os.path.normpath(external)) return externals def parse_prop_file(filename, key): found = False f = open(filename, 'rt') data = '' try: for line in iter(f.readline, ''): # can't use direct iter! parts = line.split() if len(parts) == 2: kind, length = parts data = f.read(int(length)) if kind == 'K' and data == key: found = True elif kind == 'V' and found: break finally: f.close() return data class SvnInfo(object): ''' Generic svn_info object. No has little knowledge of how to extract information. Use cls.load to instatiate according svn version. Paths are not filesystem encoded. ''' @staticmethod def get_svn_version(): # Temp config directory should be enough to check for repository # This is needed because .svn always creates .subversion and # some operating systems do not handle dot directory correctly. # Real queries in real svn repos with be concerned with it creation with TemporaryDirectory() as tempdir: code, data = _run_command(['svn', '--config-dir', tempdir, '--version', '--quiet']) if code == 0 and data: return data.strip() else: return '' #svnversion return values (previous implementations return max revision) # 4123:4168 mixed revision working copy # 4168M modified working copy # 4123S switched working copy # 4123:4168MS mixed revision, modified, switched working copy revision_re = re.compile(r'(?:([\-0-9]+):)?(\d+)([a-z]*)\s*$', re.I) @classmethod def load(cls, dirname=''): normdir = os.path.normpath(dirname) # Temp config directory should be enough to check for repository # This is needed because .svn always creates .subversion and # some operating systems do not handle dot directory correctly. # Real queries in real svn repos with be concerned with it creation with TemporaryDirectory() as tempdir: code, data = _run_command(['svn', '--config-dir', tempdir, 'info', normdir]) # Must check for some contents, as some use empty directories # in testcases, however only enteries is needed also the info # command above MUST have worked svn_dir = os.path.join(normdir, '.svn') is_svn_wd = (not code or os.path.isfile(os.path.join(svn_dir, 'entries'))) svn_version = tuple(cls.get_svn_version().split('.')) try: base_svn_version = tuple(int(x) for x in svn_version[:2]) except ValueError: base_svn_version = tuple() if not is_svn_wd: #return an instance of this NO-OP class return SvnInfo(dirname) if code or not base_svn_version or base_svn_version < (1, 3): warnings.warn(("No SVN 1.3+ command found: falling back " "on pre 1.7 .svn parsing"), DeprecationWarning) return SvnFileInfo(dirname) if base_svn_version < (1, 5): return Svn13Info(dirname) return Svn15Info(dirname) def __init__(self, path=''): self.path = path self._entries = None self._externals = None def get_revision(self): 'Retrieve the directory revision informatino using svnversion' code, data = _run_command(['svnversion', '-c', self.path]) if code: log.warn("svnversion failed") return 0 parsed = self.revision_re.match(data) if parsed: return int(parsed.group(2)) else: return 0 @property def entries(self): if self._entries is None: self._entries = self.get_entries() return self._entries @property def externals(self): if self._externals is None: self._externals = self.get_externals() return self._externals def iter_externals(self): ''' Iterate over the svn:external references in the repository path. ''' for item in self.externals: yield item def iter_files(self): ''' Iterate over the non-deleted file entries in the repository path ''' for item, kind in self.entries: if kind.lower() == 'file': yield item def iter_dirs(self, include_root=True): ''' Iterate over the non-deleted file entries in the repository path ''' if include_root: yield self.path for item, kind in self.entries: if kind.lower() == 'dir': yield item def get_entries(self): return [] def get_externals(self): return [] class Svn13Info(SvnInfo): def get_entries(self): code, data = _run_command(['svn', 'info', '-R', '--xml', self.path], encoding="utf-8") if code: log.debug("svn info failed") return [] return parse_dir_entries(data) def get_externals(self): #Previous to 1.5 --xml was not supported for svn propget and the -R #output format breaks the shlex compatible semantics. cmd = ['svn', 'propget', 'svn:externals'] result = [] for folder in self.iter_dirs(): code, lines = _run_command(cmd + [folder], encoding="utf-8") if code != 0: log.warn("svn propget failed") return [] #lines should a str for external in parse_external_prop(lines): if folder: external = os.path.join(folder, external) result.append(os.path.normpath(external)) return result class Svn15Info(Svn13Info): def get_externals(self): cmd = ['svn', 'propget', 'svn:externals', self.path, '-R', '--xml'] code, lines = _run_command(cmd, encoding="utf-8") if code: log.debug("svn propget failed") return [] return parse_externals_xml(lines, prefix=os.path.abspath(self.path)) class SvnFileInfo(SvnInfo): def __init__(self, path=''): super(SvnFileInfo, self).__init__(path) self._directories = None self._revision = None def _walk_svn(self, base): entry_file = joinpath(base, '.svn', 'entries') if os.path.isfile(entry_file): entries = SVNEntriesFile.load(base) yield (base, False, entries.parse_revision()) for path in entries.get_undeleted_records(): path = decode_as_string(path) path = joinpath(base, path) if os.path.isfile(path): yield (path, True, None) elif os.path.isdir(path): for item in self._walk_svn(path): yield item def _build_entries(self): entries = list() rev = 0 for path, isfile, dir_rev in self._walk_svn(self.path): if isfile: entries.append((path, 'file')) else: entries.append((path, 'dir')) rev = max(rev, dir_rev) self._entries = entries self._revision = rev def get_entries(self): if self._entries is None: self._build_entries() return self._entries def get_revision(self): if self._revision is None: self._build_entries() return self._revision def get_externals(self): prop_files = [['.svn', 'dir-prop-base'], ['.svn', 'dir-props']] externals = [] for dirname in self.iter_dirs(): prop_file = None for rel_parts in prop_files: filename = joinpath(dirname, *rel_parts) if os.path.isfile(filename): prop_file = filename if prop_file is not None: ext_prop = parse_prop_file(prop_file, 'svn:externals') #ext_prop should be utf-8 coming from svn:externals ext_prop = decode_as_string(ext_prop, encoding="utf-8") externals.extend(parse_external_prop(ext_prop)) return externals def svn_finder(dirname=''): #combined externals due to common interface #combined externals and entries due to lack of dir_props in 1.7 info = SvnInfo.load(dirname) for path in info.iter_files(): yield path for path in info.iter_externals(): sub_info = SvnInfo.load(path) for sub_path in sub_info.iter_files(): yield sub_path class SVNEntriesFile(object): def __init__(self, data): self.data = data @classmethod def load(class_, base): filename = os.path.join(base, '.svn', 'entries') f = open(filename) try: result = SVNEntriesFile.read(f) finally: f.close() return result @classmethod def read(class_, fileobj): data = fileobj.read() is_xml = data.startswith('<?xml') class_ = [SVNEntriesFileText, SVNEntriesFileXML][is_xml] return class_(data) def parse_revision(self): all_revs = self.parse_revision_numbers() + [0] return max(all_revs) class SVNEntriesFileText(SVNEntriesFile): known_svn_versions = { '1.4.x': 8, '1.5.x': 9, '1.6.x': 10, } def __get_cached_sections(self): return self.sections def get_sections(self): SECTION_DIVIDER = '\f\n' sections = self.data.split(SECTION_DIVIDER) sections = [x for x in map(str.splitlines, sections)] try: # remove the SVN version number from the first line svn_version = int(sections[0].pop(0)) if not svn_version in self.known_svn_versions.values(): log.warn("Unknown subversion verson %d", svn_version) except ValueError: return self.sections = sections self.get_sections = self.__get_cached_sections return self.sections def is_valid(self): return bool(self.get_sections()) def get_url(self): return self.get_sections()[0][4] def parse_revision_numbers(self): revision_line_number = 9 rev_numbers = [ int(section[revision_line_number]) for section in self.get_sections() if (len(section) > revision_line_number and section[revision_line_number]) ] return rev_numbers def get_undeleted_records(self): undeleted = lambda s: s and s[0] and (len(s) < 6 or s[5] != 'delete') result = [ section[0] for section in self.get_sections() if undeleted(section) ] return result class SVNEntriesFileXML(SVNEntriesFile): def is_valid(self): return True def get_url(self): "Get repository URL" urlre = re.compile('url="([^"]+)"') return urlre.search(self.data).group(1) def parse_revision_numbers(self): revre = re.compile(r'committed-rev="(\d+)"') return [ int(m.group(1)) for m in revre.finditer(self.data) ] def get_undeleted_records(self): entries_pattern = \ re.compile(r'name="([^"]+)"(?![^>]+deleted="true")', re.I) results = [ unescape(match.group(1)) for match in entries_pattern.finditer(self.data) ] return results if __name__ == '__main__': for name in svn_finder(sys.argv[1]): print(name)
mit
FengPu/TIBS
tibs/pos/test_root_dir2/publisher_3/topicF/acc_fun/email_certification.py
9
23908
#-*- coding: utf-8 -*- from flask import Flask, url_for, redirect, render_template, request from flask_sqlalchemy import SQLAlchemy from wtforms import form, fields, validators from flask.ext import admin, login from flask_admin.contrib import sqla from flask_admin import helpers, expose from flask import jsonify from configobj import ConfigObj from threading import Thread # Create Flask application app = Flask(__name__) @app.route('/pushData/', methods=['POST', 'GET']) def receiveData(): if request.method == 'POST': pushDB(request.data) @app.route('/checkCountry/', methods=['POST', 'GET']) def readFolder(): countryInfo = search_dir_file(1, 'C:/Users/Bai/workspace_python/Is_Setup/Config file') data = { 'status' : 'OK', 'data' : countryInfo } return jsonify(data) @app.route('/Fetch/', methods=['POST', 'GET']) def receiveReq(): response = answer(request.data) return jsonify(response) @app.route('/getCode/', methods=['POST', 'GET']) def fetchCode(): user = User.query.filter_by(id=login.current_user.get_id()).first() regionInfo = parseXmlFile('district') data = { 'status' : 'OK', 'regionInfo' : regionInfo } return jsonify(data) @app.route('/readNationConfig/', methods=['POST', 'GET']) def readConfigs(): user = User.query.filter_by(id=login.current_user.get_id()).first() ConfigInfo = fetchConfigInfo(user.country,user.city) data = { 'status' : 'OK', 'configInfo' : ConfigInfo, 'country' : user.country, 'city' : user.city } return jsonify(data) @app.route('/setup/', methods=['POST', 'GET']) def setup(): user = User.query.filter_by(id=login.current_user.get_id()).first() configInfo = fetchConfigInfo(user.country,user.city) #languageInfo = parseXmlFile('UIlanguage') wardInfo = parseXmlFile('district') data = { 'status' : 'OK', 'configInfo' : configInfo, 'country' : user.country, 'city' : user.city, 'districtInfo' : wardInfo, #'uilanguage' : languageInfo } return jsonify(data) @app.route('/fetchConfig/', methods=['POST', 'GET']) def fetchConfigs(): user = User.query.filter_by(id=login.current_user.get_id()).first() ConfigInfo = fetchConfigInfo(user.country,user.city) data = { 'status' : 'OK', 'data' : ConfigInfo, 'country' : user.country, 'city' : user.city, } return jsonify(data) @app.route('/getShelter/', methods=['POST', 'GET']) def retrieveShelterDb(): public_data = [] for s in db.session.query(Shelter): mapdata={ 'Id' : s.Id, 'Name' : s.Name, 'Type' : s.Type, 'Category' : s.Category, 'District' : s.District, 'Address' : s.Address, 'Telphone' : s.Telphone, 'Latitude' : s.Latitude, 'Longitude' : s.Longitude, 'Description' : s.Description } public_data.append(mapdata) data = { 'status' : 'OK', 'data' : public_data } return jsonify(data) @app.route('/getPOS/', methods=['POST', 'GET']) def retrievePOSDb(): public_data = [] for s in db.session.query(POS): mapdata={ 'id' : s.POS_id, 'district' : s.POS_district, 'method' : s.Partition_method, 'bound_Latlng1' : s.Rectangle_coordinate1, 'bound_Latlng2' : s.Rectangle_coordinate2, 'latitude' : s.POS_latitude, 'longitude' : s.POS_longitude, 'isContact' : s.Is_Available } public_data.append(mapdata) data = { 'status' : 'OK', 'data' : public_data } return jsonify(data) @app.route('/UpdatePOS/', methods=['POST', 'GET']) def update(): if request.method == 'POST': updatePOSDb(request.data) @app.route('/Download/', methods=['POST', 'GET']) def makefile(): if request.method == 'POST': string = (request.data).split('$') createFolder(string[0]) downloadTxt(string[0],string[1]) #downloadImg(string[1],string[2]) @app.route('/Publish/', methods=['POST', 'GET']) def Publish(): if request.method == 'POST': postToHub(request.data) @app.errorhandler(404) def page_not_found(error): return redirect(url_for('hello', name = 'fuzai')) import requests import urllib import urllib2 import os, sys import json import xml.etree.ElementTree as ET import random def answer(request): user = User.query.filter_by(id=login.current_user.get_id()).first() if request == 'cityInfo': ConfigInfo = fetchConfigInfo(user.country,user.city) data = { 'status' : 'OK', 'configInfo' : ConfigInfo, 'country' : user.country, 'city' : user.city } elif request == 'geoInfo': regionInfo = parseXmlFile('district') data = { 'status' : 'OK', 'regionInfo' : regionInfo } elif request == 'exist_Country$City': nationInfo = search_dir_file(1, 'C:/Users/Bai/workspace_python/Is_Setup/Config file') data = { 'status' : 'OK', 'data' : nationInfo } return data def postToHub(POSId): query_args = { 'mode':'publish', 'topic':'http://140.109.22.197/static/Topic/'+POSId+"/"+POSId+'.json' } #query_args = { 'mode':'publish', 'topic':'http://140.109.22.197/static/Topic/985626/985626.json' } data = urllib.urlencode(query_args) url = 'http://project-hosting.iis.sinica.edu.tw/hub/php/' request = urllib2.Request(url,data) response = urllib2.urlopen(request) html = response.read() print html def pushDB(data): data = (request.data).split('$') user = User.query.filter_by(id=login.current_user.get_id()).first() if data[0] == 'facility': shelter = Shelter(City=user.city, Id=data[1], Name=data[2].decode('utf8'), Type=data[3].decode('utf8'),District=data[4].decode('utf8'), Address=data[5].decode('utf8'),Telphone=data[6].decode('utf8'), Latitude=data[7].decode('utf8'), Longitude=data[8].decode('utf8'), Description=data[9].decode('utf8'),Category=data[10]) db.session.add(shelter) db.session.commit() else : pos = POS(POS_city=user.city, POS_id=data[2], POS_district=data[3].decode('utf8'), Partition_method='District',POS_latitude=data[4], POS_longitude=data[5], Is_Available=False) db.session.add(pos) db.session.commit() def insertUserInfo(configData): configData = configData.split('$') checkFolder(configData[0]) user = User.query.filter_by(id=login.current_user.get_id()).first() user.country = configData[0] user.city = configData[1] db.session.commit() def checkFolder(folderName): path = "C:/Users/Bai/workspace_python/Is_Setup/Config file/"+folderName if not os.path.exists(path): os.makedirs( path, 0755 ) def createFolder(folderName): path = "C:/Users/Bai/workspace_python/Is_Setup/static/Topic/"+folderName if not os.path.exists(path): os.makedirs( path, 0755 ) def fetchConfigInfo(country,city): filename = "C:/Users/Bai/workspace_python/Is_Setup/Config file/"+country+'/'+city+'.ini' if os.path.exists(filename): Info = [] config = ConfigObj(filename) configInfo = { "coordinates" : config['Country Information']['Origin Of Coordinates'], "wardpath" : config['Country Information']['District Info Path'], "key" : config['Boundary']['ApiKey'], "posCountryCode" : config['POS Information']['POS_country_code'] } return configInfo def parseXmlFile(category): user = User.query.filter_by(id=login.current_user.get_id()).first() if category == 'district': regionInfo = [] tree = ET.parse('C:/Users/Bai/workspace_python/Is_Setup/District Info/'+user.city+'.xml') root = tree.getroot() for info in root.findall('District'): data = { "District" : info.find("Name").text, "Code" : info.find("PostalCode").text } regionInfo.append(data) return regionInfo else : tree = ET.parse('C:/Users/Bai/workspace_python/Is_Setup/UI Language file/Localization for UI.xml') root = tree.getroot() for menu in root.findall('Menu'): menuText = menu.find(user.ui_language).text for l in root.findall('Label'): labelText = l.find(user.ui_language).text for ptable in root.findall('POSTable'): ptableText = ptable.find(user.ui_language).text for stable in root.findall('SchemeTable'): stableText = stable.find(user.ui_language).text for tab in root.findall('Tab'): tabText = tab.find(user.ui_language).text for btn in root.findall('Button'): btnText = btn.find(user.ui_language).text for t in root.findall('Text'): words = t.find(user.ui_language).text UIInfo = { "Menu" : menuText, "Label" : labelText, "POSTable" : ptableText, "SchemeTable" : stableText, "Tab" : tabText, "Button" : btnText, "Text" : words } return UIInfo def search_dir_file(level, path): global allList dirList = [] fileList = [] diretory_info = [] items = os.listdir(path) for f in items: if(os.path.isdir(path + '/' + f)): if(f[0] == '.'): pass else: dirList.append(f) for dl in dirList: allList={ "Nation" : dl, "City":[] } files = os.listdir(path+ '/' + dl) for f in files: if(os.path.isfile(path + '/' + dl + '/' + f)): fileList.append(f) allList["City"].append({"Name":f[:-4]}) diretory_info.append(allList) return diretory_info def createNewConfig(configData): configData = configData.split('$') user = User.query.filter_by(id=login.current_user.get_id()).first() config = ConfigObj() config.filename = 'C:/Users/Bai/workspace_python/Is_Setup/Config file/'+user.country+'/'+user.city+'.ini' config['Country Information']={} config['Country Information']['Origin Of Coordinates']=configData[0] config['Country Information']['District Info Path']="C:/Users/Bai/workspace_python/Is_Setup/District Info/"+user.city+'.xml' config['Boundary']={} config['Boundary']['ApiKey']=configData[1] config['POS Information']={} config['POS Information']['POS_country_code']="" config.write() def makeFile(content,type): user = User.query.filter_by(id=login.current_user.get_id()).first() filename = "C:/Users/Bai/workspace_python/Is_Setup/District Info/"+user.city+'.xml' f = open(filename, "w") f.write(content) f.close() def downloadTxt(POSID,content): filename = 'C:/Users/Bai/workspace_python/Is_Setup/static/Topic/'+POSID+'/'+POSID+'.json' content = "".join(content.split()) f = open(filename, "w") f.write(content) f.close() def updatePOSDb(POSInfo): POSInfo = POSInfo.split('$') #user = User.query.filter_by(id=login.current_user.get_id()).first() for p in db.session.query(POS): if p.POS_id == POSInfo[0]: p.Partition_method = POSInfo[1] if p.Partition_method == 'District': p.Rectangle_coordinate1 = '' p.Rectangle_coordinate2 = '' else : p.Rectangle_coordinate1 = POSInfo[2] p.Rectangle_coordinate2 = POSInfo[3] db.session.commit() # Create dummy secrey key so we can use sessions app.config['SECRET_KEY'] = '123456790' # Create in-memory database app.config['DATABASE_FILE'] = 'sample_db.sqlite' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + app.config['DATABASE_FILE'] app.config['SQLALCHEMY_ECHO'] = True db = SQLAlchemy(app) # Create user model. For simplicity, it will store passwords in plain text. # Obviously that's not right thing to do in real world application. class User(db.Model): id = db.Column(db.Integer, primary_key=True) login = db.Column(db.String(80), unique=True) email = db.Column(db.String(120)) password = db.Column(db.String(64)) country = db.Column(db.String(32)) city = db.Column(db.String(32)) ui_language = db.Column(db.String(100)) # Flask-Login integration def is_authenticated(self): return True def is_active(self): return True def is_anonymous(self): return False def get_id(self): return self.id # Required for administrative interface def __unicode__(self): return self.username class POS(db.Model): Id = db.Column(db.Integer, primary_key=True) POS_id = db.Column(db.String(100)) POS_city = db.Column(db.String(100)) POS_district = db.Column(db.String(100)) Partition_method = db.Column(db.Unicode(64)) Rectangle_coordinate1 = db.Column(db.Unicode(64)) Rectangle_coordinate2 = db.Column(db.Unicode(64)) POS_latitude = db.Column(db.Unicode(64)) POS_longitude = db.Column(db.Unicode(64)) Is_Available = db.Column(db.Boolean, nullable=False) def __unicode__(self): return self.name class Shelter(db.Model): Number = db.Column(db.Integer, primary_key=True) Id = db.Column(db.String(100)) Name = db.Column(db.Unicode(64)) City = db.Column(db.Unicode(100)) Type = db.Column(db.Unicode(64)) Category = db.Column(db.Unicode(64)) District = db.Column(db.Unicode(100)) Address = db.Column(db.Unicode(100)) Telphone = db.Column(db.Unicode(64)) Latitude = db.Column(db.Unicode(64)) Longitude = db.Column(db.Unicode(64)) Description = db.Column(db.Unicode(255)) def __unicode__(self): return self.name # Define login and registration forms (for flask-login) class LoginForm(form.Form): login = fields.TextField(validators=[validators.required()]) password = fields.PasswordField(validators=[validators.required()]) def validate_login(self, field): user = self.get_user() if user is None: raise validators.ValidationError('Invalid user') if user.password != self.password.data: raise validators.ValidationError('Invalid password') def get_user(self): return db.session.query(User).filter_by(login=self.login.data).first() class RegistrationForm(form.Form): login = fields.TextField(validators=[validators.required()]) email = fields.TextField() password = fields.PasswordField(validators=[validators.required()]) def validate_login(self, field): if db.session.query(User).filter_by(login=self.login.data).count() > 0: raise validators.ValidationError('Duplicate username') # Initialize flask-login def init_login(): login_manager = login.LoginManager() login_manager.init_app(app) # Create user loader function @login_manager.user_loader def load_user(user_id): userId = user_id return db.session.query(User).get(user_id) # Create customized model view class class MyModelView(sqla.ModelView): def is_accessible(self): return login.current_user.is_authenticated() def is_visible(self): if showMenuText == True: return True else : return False # Create customized index view class that handles login & registration class MyAdminIndexView(admin.AdminIndexView): @expose('/') def home(self): global showMenuText if not login.current_user.is_authenticated(): return redirect(url_for('.login_view')) for u in db.session.query(User): if login.current_user.get_id() == u.id: if u.country ==None: showMenuText = False return redirect(url_for('.initial_view')) else : showMenuText = True return super(MyAdminIndexView, self).index() @expose('/initial/') def initial_view(self): return self.render('admin/setup1.html') @expose('/postUserInfo/', methods=['GET', 'POST']) def receiveUserInfo(self): if request.method == 'POST': insertUserInfo(request.data) return redirect(url_for('.countryView')) @expose('/country_config/') def countryView(self): return self.render('admin/setup2.html') @expose('/postCountryInfo/', methods=['GET', 'POST']) def receiveCountryInfo(self): if request.method == 'POST': createNewConfig(request.data) data = request.data.split('$') makeFile(data[2],'wardInfo') @expose('/ImportPOSInfo/') def POSView(self): return self.render('admin/setup3.html') @expose('/postPOSInfo/', methods=['GET', 'POST']) def receivePOSInfo(self): if request.method == 'POST': pushDB(request.data) data = request.data.split('$') user = User.query.filter_by(id=login.current_user.get_id()).first() filename = 'C:/Users/Bai/workspace_python/Is_Setup/Config file/'+user.country+'/'+user.city+'.ini' config = ConfigObj(filename) config['POS Information']['POS_country_code']=data[1] config.write() #menuText = parseXmlFile(user.ui_language) #showMenuText = True #text = menuText.split(',') #admin.add_view(ImportDataView(name=text[0])) #admin.add_view(MonitorView(name=text[1])) #admin.add_view(ContactView(name=text[2])) #return redirect(url_for('.monitorView')) @expose('/monitor/') def monitorView(self): return self.render('monitor.html') @expose('/login/', methods=('GET', 'POST')) def login_view(self): # handle user login form = LoginForm(request.form) if helpers.validate_form_on_submit(form): user = form.get_user() login.login_user(user) if login.current_user.is_authenticated(): return redirect(url_for('.index')) link = '<p>Don\'t have an account? <a href="' + url_for('.register_view') + '">Click here to register.</a></p>' self._template_args['form'] = form self._template_args['link'] = link return super(MyAdminIndexView, self).index() @expose('/register/', methods=('GET', 'POST')) def register_view(self): form = RegistrationForm(request.form) if helpers.validate_form_on_submit(form): user = User() form.populate_obj(user) db.session.add(user) db.session.commit() login.login_user(user) return redirect(url_for('.index')) link = '<p>Already have an account? <a href="' + url_for('.login_view') + '">Click here to log in.</a></p>' self._template_args['form'] = form self._template_args['link'] = link return super(MyAdminIndexView, self).index() @expose('/logout/') def logout_view(self): login.logout_user() return redirect(url_for('.index')) class ImportDataView(admin.BaseView): @admin.expose('/') def index(self): return self.render('InputFacData.html') def is_accessible(self): return login.current_user.is_authenticated() def is_visible(self): if showMenuText == True: return True else : return False class ContactView(admin.BaseView): @admin.expose('/') def index(self): return self.render('contact.html') def is_accessible(self): return login.current_user.is_authenticated() def is_visible(self): if showMenuText == True: return True else : return False class MonitorView(admin.BaseView): @admin.expose('/') def index(self): return self.render('monitor.html') def is_accessible(self): return login.current_user.is_authenticated() def is_visible(self): if showMenuText == True: return True else : return False # Flask views @app.route('/') def index(): return render_template('index.html') @app.route('/textView/') def showText(): return render_template('textview.html') @app.route('/imgView/') def showImg(): return render_template('ImageView.html') @app.route('/checkPOS/', methods=['POST', 'GET']) def checkPOS_is_available(): public_data = [] for p in db.session.query(POS): mapdata={ 'id' : p.POS_id, 'isContact' : p.Is_Available } public_data.append(mapdata) data = { 'status' : 'OK', 'data' : public_data } return jsonify(data) @app.route('/whereAreURLs', methods=['POST', 'GET']) def receiveLoc(): count = 0 latlng = request.args.get('latlng').split(',') for pos in db.session.query(POS): #print pos.POS_latitude if latlng[0] == pos.POS_latitude: count = count + 1 POSID = pos.POS_id pos.Is_Available = True db.session.commit() if count == 0 : data = { 'status' : 'OK', 'hub_url' : 'http://project-hosting.iis.sinica.edu.tw/hub/php/', 'topic_url' : 'wahahaha!!' } else : data = { 'status' : 'OK', 'hub_url' : 'http://project-hosting.iis.sinica.edu.tw/hub/php/', 'topic_url' : 'http://140.109.22.197/static/Topic/'+POSID+'/'+POSID+".json" } return jsonify(data) # Initialize flask-login init_login() # Create admin admin = admin.Admin(app, 'MAD-IS', index_view=MyAdminIndexView(), base_template='my_master.html') #admin = admin.Admin(index_view=MyAdminIndexView()) admin.add_view(MonitorView(name="Monitor")) admin.add_view(ImportDataView(category='Data')) admin.add_view(MyModelView(POS, db.session, category='Data')) admin.add_view(MyModelView(Shelter, db.session, category='Data')) admin.add_view(ContactView(name='Contact Us')) def build_sample_db(): """ Populate a small db with some example entries. """ import string import random db.drop_all() db.create_all() test_user = User(login="test", password="test") db.session.add(test_user) first_names = [ ] for i in range(len(first_names)): user = User() user.first_name = first_names[i] user.last_name = last_names[i] user.login = user.first_name.lower() user.email = user.login + "@example.com" user.password = ''.join(random.choice(string.ascii_lowercase + string.digits) for i in range(10)) db.session.add(user) names = [ ] for i in range(len(names)): pos = POS() db.session.add(pos) sample_text = [ ] for entry in sample_text: shelter = Shelter() db.session.add(shelter) db.session.commit() return if __name__ == '__main__': # Build a sample db on the fly, if one does not exist yet. app_dir = os.path.realpath(os.path.dirname(__file__)) database_path = os.path.join(app_dir, app.config['DATABASE_FILE']) if not os.path.exists(database_path): build_sample_db() #app.run(debug=True) # Start app app.run(host= '140.109.22.197', port=int("80"))
gpl-3.0
muntasirsyed/intellij-community
python/lib/Lib/site-packages/django/contrib/auth/forms.py
71
8829
from django.contrib.auth.models import User from django.contrib.auth import authenticate from django.contrib.auth.tokens import default_token_generator from django.contrib.sites.models import get_current_site from django.template import Context, loader from django import forms from django.utils.translation import ugettext_lazy as _ from django.utils.http import int_to_base36 class UserCreationForm(forms.ModelForm): """ A form that creates a user, with no privileges, from the given username and password. """ username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^[\w.@+-]+$', help_text = _("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."), error_messages = {'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")}) password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput) password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput, help_text = _("Enter the same password as above, for verification.")) class Meta: model = User fields = ("username",) def clean_username(self): username = self.cleaned_data["username"] try: User.objects.get(username=username) except User.DoesNotExist: return username raise forms.ValidationError(_("A user with that username already exists.")) def clean_password2(self): password1 = self.cleaned_data.get("password1", "") password2 = self.cleaned_data["password2"] if password1 != password2: raise forms.ValidationError(_("The two password fields didn't match.")) return password2 def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class UserChangeForm(forms.ModelForm): username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^[\w.@+-]+$', help_text = _("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."), error_messages = {'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")}) class Meta: model = User def __init__(self, *args, **kwargs): super(UserChangeForm, self).__init__(*args, **kwargs) f = self.fields.get('user_permissions', None) if f is not None: f.queryset = f.queryset.select_related('content_type') class AuthenticationForm(forms.Form): """ Base class for authenticating users. Extend this to get a form that accepts username/password logins. """ username = forms.CharField(label=_("Username"), max_length=30) password = forms.CharField(label=_("Password"), widget=forms.PasswordInput) def __init__(self, request=None, *args, **kwargs): """ If request is passed in, the form will validate that cookies are enabled. Note that the request (a HttpRequest object) must have set a cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before running this validation. """ self.request = request self.user_cache = None super(AuthenticationForm, self).__init__(*args, **kwargs) def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: self.user_cache = authenticate(username=username, password=password) if self.user_cache is None: raise forms.ValidationError(_("Please enter a correct username and password. Note that both fields are case-sensitive.")) elif not self.user_cache.is_active: raise forms.ValidationError(_("This account is inactive.")) self.check_for_test_cookie() return self.cleaned_data def check_for_test_cookie(self): if self.request and not self.request.session.test_cookie_worked(): raise forms.ValidationError( _("Your Web browser doesn't appear to have cookies enabled. " "Cookies are required for logging in.")) def get_user_id(self): if self.user_cache: return self.user_cache.id return None def get_user(self): return self.user_cache class PasswordResetForm(forms.Form): email = forms.EmailField(label=_("E-mail"), max_length=75) def clean_email(self): """ Validates that a user exists with the given e-mail address. """ email = self.cleaned_data["email"] self.users_cache = User.objects.filter(email__iexact=email) if len(self.users_cache) == 0: raise forms.ValidationError(_("That e-mail address doesn't have an associated user account. Are you sure you've registered?")) return email def save(self, domain_override=None, email_template_name='registration/password_reset_email.html', use_https=False, token_generator=default_token_generator, from_email=None, request=None): """ Generates a one-use only link for resetting password and sends to the user """ from django.core.mail import send_mail for user in self.users_cache: if not domain_override: current_site = get_current_site(request) site_name = current_site.name domain = current_site.domain else: site_name = domain = domain_override t = loader.get_template(email_template_name) c = { 'email': user.email, 'domain': domain, 'site_name': site_name, 'uid': int_to_base36(user.id), 'user': user, 'token': token_generator.make_token(user), 'protocol': use_https and 'https' or 'http', } send_mail(_("Password reset on %s") % site_name, t.render(Context(c)), from_email, [user.email]) class SetPasswordForm(forms.Form): """ A form that lets a user change set his/her password without entering the old password """ new_password1 = forms.CharField(label=_("New password"), widget=forms.PasswordInput) new_password2 = forms.CharField(label=_("New password confirmation"), widget=forms.PasswordInput) def __init__(self, user, *args, **kwargs): self.user = user super(SetPasswordForm, self).__init__(*args, **kwargs) def clean_new_password2(self): password1 = self.cleaned_data.get('new_password1') password2 = self.cleaned_data.get('new_password2') if password1 and password2: if password1 != password2: raise forms.ValidationError(_("The two password fields didn't match.")) return password2 def save(self, commit=True): self.user.set_password(self.cleaned_data['new_password1']) if commit: self.user.save() return self.user class PasswordChangeForm(SetPasswordForm): """ A form that lets a user change his/her password by entering their old password. """ old_password = forms.CharField(label=_("Old password"), widget=forms.PasswordInput) def clean_old_password(self): """ Validates that the old_password field is correct. """ old_password = self.cleaned_data["old_password"] if not self.user.check_password(old_password): raise forms.ValidationError(_("Your old password was entered incorrectly. Please enter it again.")) return old_password PasswordChangeForm.base_fields.keyOrder = ['old_password', 'new_password1', 'new_password2'] class AdminPasswordChangeForm(forms.Form): """ A form used to change the password of a user in the admin interface. """ password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput) password2 = forms.CharField(label=_("Password (again)"), widget=forms.PasswordInput) def __init__(self, user, *args, **kwargs): self.user = user super(AdminPasswordChangeForm, self).__init__(*args, **kwargs) def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2: if password1 != password2: raise forms.ValidationError(_("The two password fields didn't match.")) return password2 def save(self, commit=True): """ Saves the new password. """ self.user.set_password(self.cleaned_data["password1"]) if commit: self.user.save() return self.user
apache-2.0
schwarz/youtube-dl
youtube_dl/extractor/golem.py
186
2181
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor from ..compat import ( compat_urlparse, ) from ..utils import ( determine_ext, ) class GolemIE(InfoExtractor): _VALID_URL = r'^https?://video\.golem\.de/.+?/(?P<id>.+?)/' _TEST = { 'url': 'http://video.golem.de/handy/14095/iphone-6-und-6-plus-test.html', 'md5': 'c1a2c0a3c863319651c7c992c5ee29bf', 'info_dict': { 'id': '14095', 'format_id': 'high', 'ext': 'mp4', 'title': 'iPhone 6 und 6 Plus - Test', 'duration': 300.44, 'filesize': 65309548, } } _PREFIX = 'http://video.golem.de' def _real_extract(self, url): video_id = self._match_id(url) config = self._download_xml( 'https://video.golem.de/xml/{0}.xml'.format(video_id), video_id) info = { 'id': video_id, 'title': config.findtext('./title', 'golem'), 'duration': self._float(config.findtext('./playtime'), 'duration'), } formats = [] for e in config: url = e.findtext('./url') if not url: continue formats.append({ 'format_id': e.tag, 'url': compat_urlparse.urljoin(self._PREFIX, url), 'height': self._int(e.get('height'), 'height'), 'width': self._int(e.get('width'), 'width'), 'filesize': self._int(e.findtext('filesize'), 'filesize'), 'ext': determine_ext(e.findtext('./filename')), }) self._sort_formats(formats) info['formats'] = formats thumbnails = [] for e in config.findall('.//teaser'): url = e.findtext('./url') if not url: continue thumbnails.append({ 'url': compat_urlparse.urljoin(self._PREFIX, url), 'width': self._int(e.get('width'), 'thumbnail width'), 'height': self._int(e.get('height'), 'thumbnail height'), }) info['thumbnails'] = thumbnails return info
unlicense
ifcharming/original2.0
tests/scripts/examples/sql_coverage/decimal-schema.py
4
1792
#!/usr/bin/env python # This file is part of VoltDB. # Copyright (C) 2008-2011 VoltDB Inc. # # 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 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. { "P1": { "columns": (("CASH", FastSerializer.VOLTTYPE_DECIMAL), ("ID", FastSerializer.VOLTTYPE_INTEGER), ("CREDIT", FastSerializer.VOLTTYPE_DECIMAL), ("RATIO", FastSerializer.VOLTTYPE_FLOAT)), "partitions": (), "indexes": ("ID") }, "R1": { "columns": (("CASH", FastSerializer.VOLTTYPE_DECIMAL), ("ID", FastSerializer.VOLTTYPE_INTEGER), ("CREDIT", FastSerializer.VOLTTYPE_DECIMAL), ("RATIO", FastSerializer.VOLTTYPE_FLOAT)), "partitions": (), "indexes": ("ID") } }
gpl-3.0
caseyrollins/osf.io
scripts/embargo_registrations.py
9
5063
"""Run nightly, this script will activate any pending embargoes that have elapsed the pending approval time and make public and registrations whose embargo end dates have been passed. """ import logging import django from django.utils import timezone from django.db import transaction django.setup() from framework.celery_tasks import app as celery_app from website.app import init_app from website import settings from osf.models import Embargo, Registration, NodeLog from scripts import utils as scripts_utils logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def main(dry_run=True): pending_embargoes = Embargo.objects.filter(state=Embargo.UNAPPROVED) for embargo in pending_embargoes: if should_be_embargoed(embargo): if dry_run: logger.warn('Dry run mode') try: parent_registration = Registration.objects.get(embargo=embargo) except Registration.DoesNotExist: logger.error( 'Embargo {} is not attached to a registration'.format(embargo._id) ) continue logger.warn( 'Embargo {0} approved. Activating embargo for registration {1}' .format(embargo._id, parent_registration._id) ) if not dry_run: if parent_registration.is_deleted: # Clean up any registration failures during archiving embargo.forcibly_reject() embargo.save() continue with transaction.atomic(): try: embargo.state = Embargo.APPROVED parent_registration.registered_from.add_log( action=NodeLog.EMBARGO_APPROVED, params={ 'node': parent_registration.registered_from._id, 'registration': parent_registration._id, 'embargo_id': embargo._id, }, auth=None, ) embargo.save() except Exception as err: logger.error( 'Unexpected error raised when activating embargo for ' 'registration {}. Continuing...'.format(parent_registration)) logger.exception(err) active_embargoes = Embargo.objects.filter(state=Embargo.APPROVED) for embargo in active_embargoes: if embargo.end_date < timezone.now() and not embargo.is_deleted: if dry_run: logger.warn('Dry run mode') parent_registration = Registration.objects.get(embargo=embargo) logger.warn( 'Embargo {0} complete. Making registration {1} public' .format(embargo._id, parent_registration._id) ) if not dry_run: if parent_registration.is_deleted: # Clean up any registration failures during archiving embargo.forcibly_reject() embargo.save() continue with transaction.atomic(): try: embargo.state = Embargo.COMPLETED # Need to save here for node.is_embargoed to return the correct # value in Node#set_privacy embargo.save() for node in parent_registration.node_and_primary_descendants(): node.set_privacy('public', auth=None, save=True) parent_registration.registered_from.add_log( action=NodeLog.EMBARGO_COMPLETED, params={ 'node': parent_registration.registered_from._id, 'registration': parent_registration._id, 'embargo_id': embargo._id, }, auth=None, ) embargo.save() except Exception as err: logger.error( 'Unexpected error raised when completing embargo for ' 'registration {}. Continuing...'.format(parent_registration)) logger.exception(err) def should_be_embargoed(embargo): """Returns true if embargo was initiated more than 48 hours prior.""" return (timezone.now() - embargo.initiation_date) >= settings.EMBARGO_PENDING_TIME and not embargo.is_deleted @celery_app.task(name='scripts.embargo_registrations') def run_main(dry_run=True): init_app(routes=False) if not dry_run: scripts_utils.add_file_logger(logger, __file__) main(dry_run=dry_run) if __name__ == '__main__': main(False)
apache-2.0
xfouloux/Flexget
tests/test_regex_extract.py
9
2245
from __future__ import unicode_literals, division, absolute_import from tests import FlexGetBase class TestRegexExtract(FlexGetBase): __yaml__ = """ tasks: test_1: mock: - {title: 'The.Event.New.York'} regex_extract: prefix: event_ field: title regex: - The\.Event\.(?P<location>.*) test_2: mock: - {title: 'TheShow.Detroit'} regex_extract: prefix: event_ field: title regex: - The\.Event\.(?P<location>.*) test_3: mock: - {title: 'The.Event.New.York'} regex_extract: field: title regex: - The\.Event\.(?P<location>.*) test_4: mock: - {title: 'The.Event.New.York.2015'} regex_extract: prefix: event_ field: title regex: - The\.Event\.(?P<location>[\w\.]*?)\.(?P<year>\d{4}) """ def test_single_group(self): self.execute_task('test_1') entry = self.task.find_entry('entries', title='The.Event.New.York') assert entry is not None assert 'event_location' in entry assert entry['event_location'] == 'New.York' def test_single_group_non_match(self): self.execute_task('test_2') entry = self.task.find_entry('entries', title='TheShow.Detroit') assert entry is not None assert 'event_location' not in entry def test_single_group_no_prefix(self): self.execute_task('test_3') entry = self.task.find_entry('entries', title='The.Event.New.York') assert entry is not None assert 'location' in entry assert entry['location'] == 'New.York' def test_multi_group(self): self.execute_task('test_4') entry = self.task.find_entry('entries', title='The.Event.New.York.2015') assert entry is not None assert 'event_location' in entry assert 'event_year' in entry assert entry['event_location'] == 'New.York' assert entry['event_year'] == '2015'
mit
jelugbo/hebs_repo
common/djangoapps/student/management/commands/transfer_students.py
27
3394
from optparse import make_option from django.core.management.base import BaseCommand from django.contrib.auth.models import User from student.models import CourseEnrollment from shoppingcart.models import CertificateItem from opaque_keys.edx.locations import SlashSeparatedCourseKey class Command(BaseCommand): help = """ This command takes two course ids as input and transfers all students enrolled in one course into the other. This will remove them from the first class and enroll them in the second class in the same mode as the first one. eg. honor, verified, audit. example: # Transfer students from the old demoX class to a new one. manage.py ... transfer_students -f edX/Open_DemoX/edx_demo_course -t edX/Open_DemoX/new_demoX """ option_list = BaseCommand.option_list + ( make_option('-f', '--from', metavar='SOURCE_COURSE', dest='source_course', help='The course to transfer students from.'), make_option('-t', '--to', metavar='DEST_COURSE', dest='dest_course', help='The new course to enroll the student into.'), ) def handle(self, *args, **options): source_key = SlashSeparatedCourseKey.from_deprecated_string(options['source_course']) dest_key = SlashSeparatedCourseKey.from_deprecated_string(options['dest_course']) source_students = User.objects.filter( courseenrollment__course_id=source_key ) for user in source_students: if CourseEnrollment.is_enrolled(user, dest_key): # Un Enroll from source course but don't mess # with the enrollment in the destination course. CourseEnrollment.unenroll(user, source_key) print("Unenrolled {} from {}".format(user.username, source_key.to_deprecated_string())) msg = "Skipping {}, already enrolled in destination course {}" print(msg.format(user.username, dest_key.to_deprecated_string())) continue print("Moving {}.".format(user.username)) # Find the old enrollment. enrollment = CourseEnrollment.objects.get( user=user, course_id=source_key ) # Move the Student between the classes. mode = enrollment.mode old_is_active = enrollment.is_active CourseEnrollment.unenroll(user, source_key) new_enrollment = CourseEnrollment.enroll(user, dest_key, mode=mode) # Unenroll from the new coures if the user had unenrolled # form the old course. if not old_is_active: new_enrollment.update_enrollment(is_active=False) if mode == 'verified': try: certificate_item = CertificateItem.objects.get( course_id=source_key, course_enrollment=enrollment ) except CertificateItem.DoesNotExist: print("No certificate for {}".format(user)) continue certificate_item.course_id = dest_key certificate_item.course_enrollment = new_enrollment certificate_item.save()
agpl-3.0
jkthompson/nupic
examples/prediction/data/extra/generated/GenerateSampleData.py
9
7259
#! /usr/bin/env python # ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- import sys import csv import numpy as np ############################################################################ def writeSimpleTest1(filePath, numRecords, testNumber): """ Generates requested number of records and saves in a csv file """ with open(filePath+'.csv', 'wb') as f: writer = csv.writer(f) if testNumber == 1: writer.writerow(['field1', 'field2']) writer.writerow(['int', 'int']) writer.writerow(['', '']) for i in ranger(0, numRecords): field1 = int(np.random.random_integers(0, 100, 1)) field2 = field1 + int(0.025*np.random.normal(0, 100, 1)) writer.writerow([field1, field2]) elif testNumber == 2: writer.writerow(['field1', 'field2', 'field3']) writer.writerow(['int', 'int', 'int']) writer.writerow(['', '', '']) for i in range(0, numRecords): field1 = int(np.random.random_integers(0, 100, 1)) field2 = field1 + int(0.025*np.random.normal(0, 100, 1)) field3 = int(np.random.random_integers(0, 100, 1)) writer.writerow([field1, field2, field3]) pass elif testNumber == 3: writer.writerow(['field1', 'field2', 'field3', 'field4']) writer.writerow(['int', 'int', 'int', 'int']) writer.writerow(['', '', '', '']) for i in range(0, numRecords): field2 = int(np.random.random_integers(0, 100, 1)) field3 = int(np.random.random_integers(0, 100, 1)) field1 = field2 + field3 field4 = int(np.random.random_integers(0, 100, 1)) writer.writerow([field1, field2, field3, field4]) elif testNumber == 4 or testNumber == 5: writer.writerow(['field1', 'field2']) writer.writerow(['string', 'string']) writer.writerow(['', '']) if testNumber == 5: categories = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p'] else: categories = ['a', 'b', 'c', 'd'] numRecsSaved = 0 firstFieldInd = 0 done = False while not done: while not done: field1 = categories[firstFieldInd] for category in categories: field2 = category writer.writerow([field1, field2]) numRecsSaved += 1 if numRecsSaved == numRecords: done = True break firstFieldInd += 1 if firstFieldInd == len(categories): firstFieldInd = 0 elif testNumber == 6: writer.writerow(['field1', 'field2']) writer.writerow(['string', 'string']) writer.writerow(['', '']) choises = [ ['a', [0.9, 0.05, 0.05]], ['b', [0.05, 0.9, 0.05]], ['c', [0.05, 0.05, 0.9]] ] cat2 = ['d', 'e', 'f'] for i in range(0, numRecords): ind1 = int(np.random.random_integers(0, 2, 1)) field1 = choises[ind1][0] ind2 = np.searchsorted(np.cumsum(choises[ind1][1]), np.random.random()) field2 = cat2[ind2] writer.writerow([field1, field2]) pass elif testNumber == 7: writer.writerow(['field1', 'field2', 'field3']) writer.writerow(['string', 'string', 'string']) writer.writerow(['', '', '']) choises = [ ['a', [0.9, 0.05, 0.05]], ['b', [0.05, 0.9, 0.05]], ['c', [0.05, 0.05, 0.9]] ] cat2 = ['d', 'e', 'f'] cat3 = ['g', 'h', 'i'] for i in range(0, numRecords): ind1 = int(np.random.random_integers(0, 2, 1)) field1 = choises[ind1][0] ind2 = np.searchsorted(np.cumsum(choises[ind1][1]), np.random.random()) field2 = cat2[ind2] ind3 = int(np.random.random_integers(0, 2, 1)) field3 = cat3[ind3] writer.writerow([field1, field2, field3]) pass elif testNumber == 8: writer.writerow(['field1', 'field2', 'field3']) writer.writerow(['string', 'string', 'string']) writer.writerow(['', '', '']) choises = [ ['a', 'd', [0.9, 0.05, 0.05]], ['a', 'e', [0.05, 0.9, 0.05]], ['a', 'f', [0.05, 0.05, 0.9]], ['b', 'd', [0.9, 0.05, 0.05]], ['b', 'e', [0.05, 0.9, 0.05]], ['b', 'f', [0.05, 0.05, 0.9]], ['c', 'd', [0.9, 0.05, 0.05]], ['c', 'e', [0.05, 0.9, 0.05]], ['c', 'f', [0.05, 0.05, 0.9]] ] cat3 = ['g', 'h', 'i'] for i in range(0, numRecords): ind1 = int(np.random.random_integers(0, 8, 1)) field1 = choises[ind1][0] field2 = choises[ind1][1] ind2 = np.searchsorted(np.cumsum(choises[ind1][2]), np.random.random()) field3 = cat3[ind2] writer.writerow([field1, field2, field3]) pass return ############################################################################ if __name__ == '__main__': np.random.seed(83) # Test 1 # 2 fields. field2 = field1 + noise (5%). Values are 0-100 (plus noise) # Test 2 # 3 fields, field 1 and 2 are the same as in #1, but 3rd field is random. # Values are 0-100. # Test 3 # 4 fields, field1 = field2 + field3 (no noise), field4 is random. # Values are 0-100. # Test 4 # 2 fields, categories. Each category can have 4 values (a, b, c, d). # Data in the following structure # (a,a)->(a,b)->(a, c)->(a,d)->(b,a)->(b,b) and so on # Test 5 # 2 fields, categories. The data is the same as in #4, # but each category can have 16 values (a,b, ...p) # Test 6 # 2 fields, categories. First field is one of (a, b, c). # Second field is (a->d, b->e, c->f) with probabilities (0.9 and 0.05, 0.05) # Test 7 # 3 fields. 2 fields are the same as in #6, 3rd field is random (g, h, i) # Test 8 # 3 fields. 1st field is (a, b, c), 2nd is (d, e, f). 3rd field is # (a,d -> g), (a, e -> h), (a, f -> i) and so on, with probabilities # (0.9, 0.05, 0.05) print 'Generating %s with %s records, test #%s' % \ (sys.argv[1], sys.argv[2], sys.argv[3]) writeSimpleTest1(sys.argv[1], int(sys.argv[2]), int(sys.argv[3]))
gpl-3.0
mugurrus/superdesk-core
superdesk/data_updates/00009_20180425-010702_vocabularies.py
3
1112
# -*- coding: utf-8; -*- # This file is part of Superdesk. # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license # # Author : mugur # Creation: 2018-04-25 01:07 from eve.utils import config from superdesk.commands.data_updates import DataUpdate class DataUpdate(DataUpdate): resource = 'vocabularies' update_fields = ['name', 'qcode'] def forwards(self, mongodb_collection, mongodb_database): for vocabulary in mongodb_collection.find({}): if 'schema' in vocabulary: schema = vocabulary['schema'] for field in self.update_fields: if field in vocabulary['schema'] and type(vocabulary['schema']) == dict: schema[field]['required'] = True mongodb_collection.update({'_id': vocabulary.get(config.ID_FIELD)}, {'$set': {'schema': schema}}) def backwards(self, mongodb_collection, mongodb_database): pass
agpl-3.0
alexandrebarachant/mne-python
examples/connectivity/plot_mne_inverse_connectivity_spectrum.py
13
3458
""" ============================================================== Compute full spectrum source space connectivity between labels ============================================================== The connectivity is computed between 4 labels across the spectrum between 5 and 40 Hz. """ # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # # License: BSD (3-clause) import matplotlib.pyplot as plt import mne from mne.datasets import sample from mne.minimum_norm import apply_inverse_epochs, read_inverse_operator from mne.connectivity import spectral_connectivity print(__doc__) data_path = sample.data_path() subjects_dir = data_path + '/subjects' fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif' fname_raw = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif' fname_event = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif' # Load data inverse_operator = read_inverse_operator(fname_inv) raw = mne.io.read_raw_fif(fname_raw) events = mne.read_events(fname_event) # Add a bad channel raw.info['bads'] += ['MEG 2443'] # Pick MEG channels picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=True, exclude='bads') # Define epochs for left-auditory condition event_id, tmin, tmax = 1, -0.2, 0.5 epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=dict(mag=4e-12, grad=4000e-13, eog=150e-6)) # Compute inverse solution and for each epoch. By using "return_generator=True" # stcs will be a generator object instead of a list. snr = 1.0 # use lower SNR for single epochs lambda2 = 1.0 / snr ** 2 method = "dSPM" # use dSPM method (could also be MNE or sLORETA) stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method, pick_ori="normal", return_generator=True) # Read some labels names = ['Aud-lh', 'Aud-rh', 'Vis-lh', 'Vis-rh'] labels = [mne.read_label(data_path + '/MEG/sample/labels/%s.label' % name) for name in names] # Average the source estimates within each label using sign-flips to reduce # signal cancellations, also here we return a generator src = inverse_operator['src'] label_ts = mne.extract_label_time_course(stcs, labels, src, mode='mean_flip', return_generator=True) fmin, fmax = 5., 40. sfreq = raw.info['sfreq'] # the sampling frequency con, freqs, times, n_epochs, n_tapers = spectral_connectivity( label_ts, method='wpli2_debiased', mode='multitaper', sfreq=sfreq, fmin=fmin, fmax=fmax, mt_adaptive=True, n_jobs=1) n_rows, n_cols = con.shape[:2] fig, axes = plt.subplots(n_rows, n_cols, sharex=True, sharey=True) plt.suptitle('Between labels connectivity') for i in range(n_rows): for j in range(i + 1): if i == j: axes[i, j].set_axis_off() continue axes[i, j].plot(freqs, con[i, j, :]) axes[j, i].plot(freqs, con[i, j, :]) if j == 0: axes[i, j].set_ylabel(names[i]) axes[0, i].set_title(names[i]) if i == (n_rows - 1): axes[i, j].set_xlabel(names[j]) axes[i, j].set_xlim([fmin, fmax]) axes[j, i].set_xlim([fmin, fmax]) # Show band limits for f in [8, 12, 18, 35]: axes[i, j].axvline(f, color='k') axes[j, i].axvline(f, color='k') plt.show()
bsd-3-clause
Finntack/pootle
pootle/apps/pootle_terminology/forms.py
9
1813
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django import forms from pootle.i18n.gettext import ugettext as _ from pootle_store.forms import MultiStringFormField from pootle_store.models import Store, Unit def term_unit_form_factory(terminology_store): store_pk = terminology_store.pk # Set store for new terms qs = Store.objects.filter(pk=store_pk) class TermUnitForm(forms.ModelForm): store = forms.ModelChoiceField(queryset=qs, initial=store_pk, widget=forms.HiddenInput) index = forms.IntegerField(required=False, widget=forms.HiddenInput) source_f = MultiStringFormField(required=False, textarea=False) class Meta(object): model = Unit # FIXME: terminology should use its own model! fields = ('index', 'source_f', 'store',) def clean_index(self): # Assign new terms an index value value = self.cleaned_data['index'] if self.instance.id is None: value = terminology_store.max_index() + 1 return value def clean_source_f(self): value = self.cleaned_data['source_f'] if value: existing = terminology_store.findid(value[0]) if existing and existing.id != self.instance.id: raise forms.ValidationError(_('This term already exists ' 'in this file.')) self.instance.setid(value[0]) return value return TermUnitForm
gpl-3.0
markhoney/script.module.pyamf
lib/pyamf/tests/test_alias.py
26
31404
# Copyright (c) The PyAMF Project. # See LICENSE.txt for details. """ Tests for L{ClassAlias} and L{register_class}. Both are the most fundamental parts of PyAMF and the test suite for it is big so it makes sense to have them in one file. @since: 0.5 """ import unittest import pyamf from pyamf import ClassAlias from pyamf.tests.util import ClassCacheClearingTestCase, Spam, get_fqcn try: set except NameError: from sets import Set as set class ClassAliasTestCase(ClassCacheClearingTestCase): """ Test all functionality relating to the class L{ClassAlias}. """ def test_init(self): x = ClassAlias(Spam) self.assertTrue(x.anonymous) self.assertTrue(x.dynamic) self.assertFalse(x.amf3) self.assertFalse(x.external) self.assertEqual(x.readonly_attrs, None) self.assertEqual(x.static_attrs, []) self.assertEqual(x.exclude_attrs, None) self.assertEqual(x.proxy_attrs, None) self.assertEqual(x.alias, '') self.assertEqual(x.klass, Spam) # compiled attributes self.assertEqual(x.decodable_properties, None) self.assertEqual(x.encodable_properties, None) self.assertTrue(x._compiled) def test_init_deferred(self): """ Test for initial deferred compliation """ x = ClassAlias(Spam, defer=True) self.assertTrue(x.anonymous) self.assertEqual(x.dynamic, None) self.assertFalse(x.amf3) self.assertFalse(x.external) self.assertEqual(x.readonly_attrs, None) self.assertEqual(x.static_attrs, None) self.assertEqual(x.exclude_attrs, None) self.assertEqual(x.proxy_attrs, None) self.assertEqual(x.alias, '') self.assertEqual(x.klass, Spam) # compiled attributes self.assertFalse(hasattr(x, 'static_properties')) self.assertFalse(x._compiled) def test_init_kwargs(self): x = ClassAlias(Spam, alias='foo', static_attrs=('bar',), exclude_attrs=('baz',), readonly_attrs='gak', amf3='spam', external='eggs', dynamic='goo', proxy_attrs=('blarg',)) self.assertFalse(x.anonymous) self.assertEqual(x.dynamic, 'goo') self.assertEqual(x.amf3, 'spam') self.assertEqual(x.external, 'eggs') self.assertEqual(x.readonly_attrs, ['a', 'g', 'k']) self.assertEqual(x.static_attrs, ['bar']) self.assertEqual(x.exclude_attrs, ['baz']) self.assertEqual(x.proxy_attrs, ['blarg']) self.assertEqual(x.alias, 'foo') self.assertEqual(x.klass, Spam) # compiled attributes self.assertEqual(x.encodable_properties, ['bar']) self.assertEqual(x.decodable_properties, ['bar']) self.assertTrue(x._compiled) def test_bad_class(self): self.assertRaises(TypeError, ClassAlias, 'eggs', 'blah') def test_init_args(self): class ClassicFoo: def __init__(self, foo, bar): pass class NewFoo(object): def __init__(self, foo, bar): pass self.assertRaises(TypeError, ClassAlias, ClassicFoo) ClassAlias(NewFoo) def test_createInstance(self): x = ClassAlias(Spam, 'org.example.spam.Spam') y = x.createInstance() self.assertTrue(isinstance(y, Spam)) def test_str(self): class Eggs(object): pass x = ClassAlias(Eggs, 'org.example.eggs.Eggs') self.assertEqual(str(x), 'org.example.eggs.Eggs') def test_eq(self): class A(object): pass class B(object): pass x = ClassAlias(A, 'org.example.A') y = ClassAlias(A, 'org.example.A') z = ClassAlias(B, 'org.example.B') self.assertEqual(x, A) self.assertEqual(x, y) self.assertNotEquals(x, z) class GetEncodableAttributesTestCase(unittest.TestCase): """ Tests for L{ClassAlias.getEncodableAttributes} """ def setUp(self): self.alias = ClassAlias(Spam, 'foo', defer=True) self.obj = Spam() def test_empty(self): attrs = self.alias.getEncodableAttributes(self.obj) self.assertEqual(attrs, {}) def test_static(self): self.alias.static_attrs = ['foo', 'bar'] self.alias.compile() self.obj.foo = 'bar' # leave self.obj.bar self.assertFalse(hasattr(self.obj, 'bar')) attrs = self.alias.getEncodableAttributes(self.obj) self.assertEqual(attrs, {'foo': 'bar', 'bar': pyamf.Undefined}) def test_not_dynamic(self): self.alias.compile() self.alias.dynamic = False self.assertEqual(self.alias.getEncodableAttributes(self.obj), {}) def test_dynamic(self): self.alias.compile() self.assertEqual(self.alias.encodable_properties, None) self.obj.foo = 'bar' self.obj.bar = 'foo' attrs = self.alias.getEncodableAttributes(self.obj) self.assertEqual(attrs, {'foo': 'bar', 'bar': 'foo'}) def test_proxy(self): from pyamf import flex c = pyamf.get_encoder(pyamf.AMF3) self.alias.proxy_attrs = ('foo', 'bar') self.alias.compile() self.assertEqual(self.alias.proxy_attrs, ['bar', 'foo']) self.obj.foo = ['bar', 'baz'] self.obj.bar = {'foo': 'gak'} attrs = self.alias.getEncodableAttributes(self.obj, c) k = attrs.keys() k.sort() self.assertEqual(k, ['bar', 'foo']) self.assertTrue(isinstance(attrs['foo'], flex.ArrayCollection)) self.assertEqual(attrs['foo'], ['bar', 'baz']) self.assertTrue(isinstance(attrs['bar'], flex.ObjectProxy)) self.assertEqual(attrs['bar']._amf_object, {'foo': 'gak'}) def test_synonym(self): self.alias.synonym_attrs = {'foo': 'bar'} self.alias.compile() self.assertFalse(self.alias.shortcut_encode) self.assertFalse(self.alias.shortcut_decode) self.obj.foo = 'bar' self.obj.spam = 'eggs' ret = self.alias.getEncodableAttributes(self.obj) self.assertEquals(ret, {'bar': 'bar', 'spam': 'eggs'}) class GetDecodableAttributesTestCase(unittest.TestCase): """ Tests for L{ClassAlias.getDecodableAttributes} """ def setUp(self): self.alias = ClassAlias(Spam, 'foo', defer=True) self.obj = Spam() def test_compile(self): self.assertFalse(self.alias._compiled) self.alias.applyAttributes(self.obj, {}) self.assertTrue(self.alias._compiled) def test_missing_static_property(self): self.alias.static_attrs = ['foo', 'bar'] self.alias.compile() attrs = {'foo': None} # missing bar key .. self.assertRaises(AttributeError, self.alias.getDecodableAttributes, self.obj, attrs) def test_no_static(self): self.alias.compile() attrs = {'foo': None, 'bar': [1, 2, 3]} ret = self.alias.getDecodableAttributes(self.obj, attrs) self.assertEqual(ret, {'foo': None, 'bar': [1, 2, 3]}) def test_readonly(self): self.alias.compile() self.alias.readonly_attrs = ['bar'] attrs = {'foo': None, 'bar': [1, 2, 3]} ret = self.alias.getDecodableAttributes(self.obj, attrs) self.assertEqual(ret, {'foo': None}) def test_not_dynamic(self): self.alias.compile() self.alias.decodable_properties = set(['bar']) self.alias.dynamic = False attrs = {'foo': None, 'bar': [1, 2, 3]} ret = self.alias.getDecodableAttributes(self.obj, attrs) self.assertEqual(ret, {'bar': [1, 2, 3]}) def test_dynamic(self): self.alias.compile() self.alias.static_properties = ['bar'] self.alias.dynamic = True attrs = {'foo': None, 'bar': [1, 2, 3]} ret = self.alias.getDecodableAttributes(self.obj, attrs) self.assertEqual(ret, {'foo': None, 'bar': [1, 2, 3]}) def test_complex(self): self.alias.compile() self.alias.static_properties = ['foo', 'bar'] self.alias.exclude_attrs = ['baz', 'gak'] self.alias.readonly_attrs = ['spam', 'eggs'] attrs = { 'foo': 'foo', 'bar': 'bar', 'baz': 'baz', 'gak': 'gak', 'spam': 'spam', 'eggs': 'eggs', 'dyn1': 'dyn1', 'dyn2': 'dyn2' } ret = self.alias.getDecodableAttributes(self.obj, attrs) self.assertEquals(ret, { 'foo': 'foo', 'bar': 'bar', 'dyn2': 'dyn2', 'dyn1': 'dyn1' }) def test_complex_not_dynamic(self): self.alias.compile() self.alias.decodable_properties = ['foo', 'bar'] self.alias.exclude_attrs = ['baz', 'gak'] self.alias.readonly_attrs = ['spam', 'eggs'] self.alias.dynamic = False attrs = { 'foo': 'foo', 'bar': 'bar', 'baz': 'baz', 'gak': 'gak', 'spam': 'spam', 'eggs': 'eggs', 'dyn1': 'dyn1', 'dyn2': 'dyn2' } ret = self.alias.getDecodableAttributes(self.obj, attrs) self.assertEqual(ret, {'foo': 'foo', 'bar': 'bar'}) def test_static(self): self.alias.dynamic = False self.alias.compile() self.alias.decodable_properties = set(['foo', 'bar']) attrs = { 'foo': 'foo', 'bar': 'bar', 'baz': 'baz', 'gak': 'gak', } ret = self.alias.getDecodableAttributes(self.obj, attrs) self.assertEqual(ret, {'foo': 'foo', 'bar': 'bar'}) def test_proxy(self): from pyamf import flex c = pyamf.get_encoder(pyamf.AMF3) self.alias.proxy_attrs = ('foo', 'bar') self.alias.compile() self.assertEqual(self.alias.proxy_attrs, ['bar', 'foo']) attrs = { 'foo': flex.ArrayCollection(['bar', 'baz']), 'bar': flex.ObjectProxy({'foo': 'gak'}) } ret = self.alias.getDecodableAttributes(self.obj, attrs, c) self.assertEqual(ret, { 'foo': ['bar', 'baz'], 'bar': {'foo': 'gak'} }) def test_synonym(self): self.alias.synonym_attrs = {'foo': 'bar'} self.alias.compile() self.assertFalse(self.alias.shortcut_encode) self.assertFalse(self.alias.shortcut_decode) attrs = { 'foo': 'foo', 'spam': 'eggs' } ret = self.alias.getDecodableAttributes(self.obj, attrs) self.assertEquals(ret, {'bar': 'foo', 'spam': 'eggs'}) class ApplyAttributesTestCase(unittest.TestCase): """ Tests for L{ClassAlias.applyAttributes} """ def setUp(self): self.alias = ClassAlias(Spam, 'foo', defer=True) self.obj = Spam() def test_object(self): class Foo(object): pass attrs = {'foo': 'spam', 'bar': 'eggs'} self.obj = Foo() self.alias = ClassAlias(Foo, 'foo', defer=True) self.assertEqual(self.obj.__dict__, {}) self.alias.applyAttributes(self.obj, attrs) self.assertEqual(self.obj.__dict__, {'foo': 'spam', 'bar': 'eggs'}) def test_classic(self): class Foo: pass attrs = {'foo': 'spam', 'bar': 'eggs'} self.obj = Foo() self.alias = ClassAlias(Foo, 'foo', defer=True) self.assertEqual(self.obj.__dict__, {}) self.alias.applyAttributes(self.obj, attrs) self.assertEqual(self.obj.__dict__, {'foo': 'spam', 'bar': 'eggs'}) def test_readonly(self): self.alias.readonly_attrs = ['foo', 'bar'] attrs = {'foo': 'spam', 'bar': 'eggs'} self.assertEqual(self.obj.__dict__, {}) self.alias.applyAttributes(self.obj, attrs) self.assertEqual(self.obj.__dict__, {}) def test_exclude(self): self.alias.exclude_attrs = ['foo', 'bar'] attrs = {'foo': 'spam', 'bar': 'eggs'} self.assertEqual(self.obj.__dict__, {}) self.alias.applyAttributes(self.obj, attrs) self.assertEqual(self.obj.__dict__, {}) def test_not_dynamic(self): self.alias.static_properties = None self.alias.dynamic = False attrs = {'foo': 'spam', 'bar': 'eggs'} self.assertEqual(self.obj.__dict__, {}) self.alias.applyAttributes(self.obj, attrs) self.assertEqual(self.obj.__dict__, {}) def test_dict(self): attrs = {'foo': 'spam', 'bar': 'eggs'} self.obj = Spam() self.assertEqual(self.obj.__dict__, {}) self.alias.applyAttributes(self.obj, attrs) self.assertEqual(self.obj.__dict__, {'foo': 'spam', 'bar': 'eggs'}) class SimpleCompliationTestCase(unittest.TestCase): """ Tests for L{ClassAlias} property compliation for no inheritance. """ def test_compiled(self): x = ClassAlias(Spam, defer=True) self.assertFalse(x._compiled) x._compiled = True o = x.static_properties = object() x.compile() self.assertTrue(o is x.static_properties) def test_external(self): class A(object): pass class B: pass self.assertRaises(AttributeError, ClassAlias, A, external=True) self.assertRaises(AttributeError, ClassAlias, B, external=True) A.__readamf__ = None B.__readamf__ = None self.assertRaises(AttributeError, ClassAlias, A, external=True) self.assertRaises(AttributeError, ClassAlias, B, external=True) A.__readamf__ = lambda x: None B.__readamf__ = lambda x: None self.assertRaises(AttributeError, ClassAlias, A, external=True) self.assertRaises(AttributeError, ClassAlias, B, external=True) A.__writeamf__ = 'foo' B.__writeamf__ = 'bar' self.assertRaises(TypeError, ClassAlias, A, external=True) self.assertRaises(TypeError, ClassAlias, B, external=True) A.__writeamf__ = lambda x: None B.__writeamf__ = lambda x: None a = ClassAlias(A, external=True) b = ClassAlias(B, external=True) self.assertEqual(a.readonly_attrs, None) self.assertEqual(a.static_attrs, []) self.assertEqual(a.decodable_properties, None) self.assertEqual(a.encodable_properties, None) self.assertEqual(a.exclude_attrs, None) self.assertTrue(a.anonymous) self.assertTrue(a.external) self.assertTrue(a._compiled) self.assertEqual(a.klass, A) self.assertEqual(a.alias, '') # now b self.assertEqual(b.readonly_attrs, None) self.assertEqual(b.static_attrs, []) self.assertEqual(b.decodable_properties, None) self.assertEqual(b.encodable_properties, None) self.assertEqual(b.exclude_attrs, None) self.assertTrue(b.anonymous) self.assertTrue(b.external) self.assertTrue(b._compiled) self.assertEqual(b.klass, B) self.assertEqual(b.alias, '') def test_anonymous(self): x = ClassAlias(Spam, None) x.compile() self.assertTrue(x.anonymous) self.assertTrue(x._compiled) self.assertEqual(x.klass, Spam) self.assertEqual(x.alias, '') def test_exclude(self): x = ClassAlias(Spam, exclude_attrs=['foo', 'bar'], defer=True) self.assertEqual(x.exclude_attrs, ['foo', 'bar']) x.compile() self.assertEqual(x.exclude_attrs, ['bar', 'foo']) def test_readonly(self): x = ClassAlias(Spam, readonly_attrs=['foo', 'bar'], defer=True) self.assertEqual(x.readonly_attrs, ['foo', 'bar']) x.compile() self.assertEqual(x.readonly_attrs, ['bar', 'foo']) def test_static(self): x = ClassAlias(Spam, static_attrs=['foo', 'bar'], defer=True) self.assertEqual(x.static_attrs, ['foo', 'bar']) x.compile() self.assertEqual(x.static_attrs, ['foo', 'bar']) def test_custom_properties(self): class A(ClassAlias): def getCustomProperties(self): self.encodable_properties.update(['foo', 'bar']) self.decodable_properties.update(['bar', 'foo']) a = A(Spam) self.assertEqual(a.encodable_properties, ['bar', 'foo']) self.assertEqual(a.decodable_properties, ['bar', 'foo']) # test combined b = A(Spam, static_attrs=['foo', 'baz', 'gak']) self.assertEqual(b.encodable_properties, ['bar', 'baz', 'foo', 'gak']) self.assertEqual(b.decodable_properties, ['bar', 'baz', 'foo', 'gak']) def test_amf3(self): x = ClassAlias(Spam, amf3=True) self.assertTrue(x.amf3) def test_dynamic(self): x = ClassAlias(Spam, dynamic=True) self.assertTrue(x.dynamic) x = ClassAlias(Spam, dynamic=False) self.assertFalse(x.dynamic) x = ClassAlias(Spam) self.assertTrue(x.dynamic) def test_sealed_external(self): class A(object): __slots__ = ('foo',) class __amf__: external = True def __readamf__(self, foo): pass def __writeamf__(self, foo): pass x = ClassAlias(A) x.compile() self.assertTrue(x.sealed) def test_synonym_attrs(self): x = ClassAlias(Spam, synonym_attrs={'foo': 'bar'}, defer=True) self.assertEquals(x.synonym_attrs, {'foo': 'bar'}) x.compile() self.assertEquals(x.synonym_attrs, {'foo': 'bar'}) class CompilationInheritanceTestCase(ClassCacheClearingTestCase): """ """ def _register(self, alias): pyamf.CLASS_CACHE[get_fqcn(alias.klass)] = alias pyamf.CLASS_CACHE[alias.klass] = alias return alias def test_bases(self): class A: pass class B(A): pass class C(B): pass a = self._register(ClassAlias(A, 'a', defer=True)) b = self._register(ClassAlias(B, 'b', defer=True)) c = self._register(ClassAlias(C, 'c', defer=True)) self.assertEqual(a.bases, None) self.assertEqual(b.bases, None) self.assertEqual(c.bases, None) a.compile() self.assertEqual(a.bases, []) b.compile() self.assertEqual(a.bases, []) self.assertEqual(b.bases, [(A, a)]) c.compile() self.assertEqual(a.bases, []) self.assertEqual(b.bases, [(A, a)]) self.assertEqual(c.bases, [(B, b), (A, a)]) def test_exclude_classic(self): class A: pass class B(A): pass class C(B): pass a = self._register(ClassAlias(A, 'a', exclude_attrs=['foo'], defer=True)) b = self._register(ClassAlias(B, 'b', defer=True)) c = self._register(ClassAlias(C, 'c', exclude_attrs=['bar'], defer=True)) self.assertFalse(a._compiled) self.assertFalse(b._compiled) self.assertFalse(c._compiled) c.compile() self.assertTrue(a._compiled) self.assertTrue(b._compiled) self.assertTrue(c._compiled) self.assertEqual(a.exclude_attrs, ['foo']) self.assertEqual(b.exclude_attrs, ['foo']) self.assertEqual(c.exclude_attrs, ['bar', 'foo']) def test_exclude_new(self): class A(object): pass class B(A): pass class C(B): pass a = self._register(ClassAlias(A, 'a', exclude_attrs=['foo'], defer=True)) b = self._register(ClassAlias(B, 'b', defer=True)) c = self._register(ClassAlias(C, 'c', exclude_attrs=['bar'], defer=True)) self.assertFalse(a._compiled) self.assertFalse(b._compiled) self.assertFalse(c._compiled) c.compile() self.assertTrue(a._compiled) self.assertTrue(b._compiled) self.assertTrue(c._compiled) self.assertEqual(a.exclude_attrs, ['foo']) self.assertEqual(b.exclude_attrs, ['foo']) self.assertEqual(c.exclude_attrs, ['bar', 'foo']) def test_readonly_classic(self): class A: pass class B(A): pass class C(B): pass a = self._register(ClassAlias(A, 'a', readonly_attrs=['foo'], defer=True)) b = self._register(ClassAlias(B, 'b', defer=True)) c = self._register(ClassAlias(C, 'c', readonly_attrs=['bar'], defer=True)) self.assertFalse(a._compiled) self.assertFalse(b._compiled) self.assertFalse(c._compiled) c.compile() self.assertTrue(a._compiled) self.assertTrue(b._compiled) self.assertTrue(c._compiled) self.assertEqual(a.readonly_attrs, ['foo']) self.assertEqual(b.readonly_attrs, ['foo']) self.assertEqual(c.readonly_attrs, ['bar', 'foo']) def test_readonly_new(self): class A(object): pass class B(A): pass class C(B): pass a = self._register(ClassAlias(A, 'a', readonly_attrs=['foo'], defer=True)) b = self._register(ClassAlias(B, 'b', defer=True)) c = self._register(ClassAlias(C, 'c', readonly_attrs=['bar'], defer=True)) self.assertFalse(a._compiled) self.assertFalse(b._compiled) self.assertFalse(c._compiled) c.compile() self.assertTrue(a._compiled) self.assertTrue(b._compiled) self.assertTrue(c._compiled) self.assertEqual(a.readonly_attrs, ['foo']) self.assertEqual(b.readonly_attrs, ['foo']) self.assertEqual(c.readonly_attrs, ['bar', 'foo']) def test_static_classic(self): class A: pass class B(A): pass class C(B): pass a = self._register(ClassAlias(A, 'a', static_attrs=['foo'], defer=True)) b = self._register(ClassAlias(B, 'b', defer=True)) c = self._register(ClassAlias(C, 'c', static_attrs=['bar'], defer=True)) self.assertFalse(a._compiled) self.assertFalse(b._compiled) self.assertFalse(c._compiled) c.compile() self.assertTrue(a._compiled) self.assertTrue(b._compiled) self.assertTrue(c._compiled) self.assertEqual(a.static_attrs, ['foo']) self.assertEqual(b.static_attrs, ['foo']) self.assertEqual(c.static_attrs, ['foo', 'bar']) def test_static_new(self): class A(object): pass class B(A): pass class C(B): pass a = self._register(ClassAlias(A, 'a', static_attrs=['foo'], defer=True)) b = self._register(ClassAlias(B, 'b', defer=True)) c = self._register(ClassAlias(C, 'c', static_attrs=['bar'], defer=True)) self.assertFalse(a._compiled) self.assertFalse(b._compiled) self.assertFalse(c._compiled) c.compile() self.assertTrue(a._compiled) self.assertTrue(b._compiled) self.assertTrue(c._compiled) self.assertEqual(a.static_attrs, ['foo']) self.assertEqual(b.static_attrs, ['foo']) self.assertEqual(c.static_attrs, ['foo', 'bar']) def test_amf3(self): class A: pass class B(A): pass class C(B): pass a = self._register(ClassAlias(A, 'a', amf3=True, defer=True)) b = self._register(ClassAlias(B, 'b', defer=True)) c = self._register(ClassAlias(C, 'c', amf3=False, defer=True)) self.assertFalse(a._compiled) self.assertFalse(b._compiled) self.assertFalse(c._compiled) c.compile() self.assertTrue(a._compiled) self.assertTrue(b._compiled) self.assertTrue(c._compiled) self.assertTrue(a.amf3) self.assertTrue(b.amf3) self.assertFalse(c.amf3) def test_dynamic(self): class A: pass class B(A): pass class C(B): pass a = self._register(ClassAlias(A, 'a', dynamic=False, defer=True)) b = self._register(ClassAlias(B, 'b', defer=True)) c = self._register(ClassAlias(C, 'c', dynamic=True, defer=True)) self.assertFalse(a._compiled) self.assertFalse(b._compiled) self.assertFalse(c._compiled) c.compile() self.assertTrue(a._compiled) self.assertTrue(b._compiled) self.assertTrue(c._compiled) self.assertFalse(a.dynamic) self.assertFalse(b.dynamic) self.assertTrue(c.dynamic) def test_synonym_attrs(self): class A(object): pass class B(A): pass class C(B): pass a = self._register(ClassAlias(A, 'a', synonym_attrs={'foo': 'bar', 'bar': 'baz'}, defer=True)) b = self._register(ClassAlias(B, 'b', defer=True)) c = self._register(ClassAlias(C, 'c', synonym_attrs={'bar': 'spam'}, defer=True)) self.assertFalse(a._compiled) self.assertFalse(b._compiled) self.assertFalse(c._compiled) c.compile() self.assertTrue(a._compiled) self.assertTrue(b._compiled) self.assertTrue(c._compiled) self.assertEquals(a.synonym_attrs, {'foo': 'bar', 'bar': 'baz'}) self.assertEquals(b.synonym_attrs, {'foo': 'bar', 'bar': 'baz'}) self.assertEquals(c.synonym_attrs, {'foo': 'bar', 'bar': 'spam'}) class CompilationIntegrationTestCase(unittest.TestCase): """ Integration tests for ClassAlias's """ def test_slots_classic(self): class A: __slots__ = ('foo', 'bar') class B(A): __slots__ = ('gak',) class C(B): pass class D(C, B): __slots__ = ('spam',) a = ClassAlias(A) self.assertFalse(a.dynamic) self.assertEqual(a.encodable_properties, ['bar', 'foo']) self.assertEqual(a.decodable_properties, ['bar', 'foo']) b = ClassAlias(B) self.assertFalse(b.dynamic) self.assertEqual(b.encodable_properties, ['bar', 'foo', 'gak']) self.assertEqual(b.decodable_properties, ['bar', 'foo', 'gak']) c = ClassAlias(C) self.assertFalse(c.dynamic) self.assertEqual(c.encodable_properties, ['bar', 'foo', 'gak']) self.assertEqual(c.decodable_properties, ['bar', 'foo', 'gak']) d = ClassAlias(D) self.assertFalse(d.dynamic) self.assertEqual(d.encodable_properties, ['bar', 'foo', 'gak', 'spam']) self.assertEqual(d.decodable_properties, ['bar', 'foo', 'gak', 'spam']) def test_slots_new(self): class A(object): __slots__ = ('foo', 'bar') class B(A): __slots__ = ('gak',) class C(B): pass class D(C, B): __slots__ = ('spam',) a = ClassAlias(A) self.assertFalse(a.dynamic) self.assertEqual(a.encodable_properties, ['bar', 'foo']) self.assertEqual(a.decodable_properties, ['bar', 'foo']) b = ClassAlias(B) self.assertFalse(b.dynamic) self.assertEqual(b.encodable_properties, ['bar', 'foo', 'gak']) self.assertEqual(b.decodable_properties, ['bar', 'foo', 'gak']) c = ClassAlias(C) self.assertTrue(c.dynamic) self.assertEqual(c.encodable_properties, ['bar', 'foo', 'gak']) self.assertEqual(c.decodable_properties, ['bar', 'foo', 'gak']) d = ClassAlias(D) self.assertTrue(d.dynamic) self.assertEqual(d.encodable_properties, ['bar', 'foo', 'gak', 'spam']) self.assertEqual(d.decodable_properties, ['bar', 'foo', 'gak', 'spam']) def test_properties(self): class A: a_rw = property(lambda _: None, lambda _, x: None) a_ro = property(lambda _: None) class B(A): b_rw = property(lambda _: None, lambda _, x: None) b_ro = property(lambda _: None) class C(B): pass a = ClassAlias(A) self.assertTrue(a.dynamic) self.assertEqual(a.encodable_properties, ['a_ro', 'a_rw']) self.assertEqual(a.decodable_properties, ['a_rw']) b = ClassAlias(B) self.assertTrue(b.dynamic) self.assertEqual(b.encodable_properties, ['a_ro', 'a_rw', 'b_ro', 'b_rw']) self.assertEqual(b.decodable_properties, ['a_rw', 'b_rw']) c = ClassAlias(C) self.assertTrue(c.dynamic) self.assertEqual(c.encodable_properties, ['a_ro', 'a_rw', 'b_ro', 'b_rw']) self.assertEqual(c.decodable_properties, ['a_rw', 'b_rw']) class RegisterClassTestCase(ClassCacheClearingTestCase): """ Tests for L{pyamf.register_class} """ def tearDown(self): ClassCacheClearingTestCase.tearDown(self) if hasattr(Spam, '__amf__'): del Spam.__amf__ def test_meta(self): self.assertFalse('spam.eggs' in pyamf.CLASS_CACHE.keys()) Spam.__amf__ = { 'alias': 'spam.eggs' } alias = pyamf.register_class(Spam) self.assertTrue('spam.eggs' in pyamf.CLASS_CACHE.keys()) self.assertEqual(pyamf.CLASS_CACHE['spam.eggs'], alias) self.assertTrue(isinstance(alias, pyamf.ClassAlias)) self.assertEqual(alias.klass, Spam) self.assertEqual(alias.alias, 'spam.eggs') self.assertFalse(alias._compiled) def test_kwarg(self): self.assertFalse('spam.eggs' in pyamf.CLASS_CACHE.keys()) alias = pyamf.register_class(Spam, 'spam.eggs') self.assertTrue('spam.eggs' in pyamf.CLASS_CACHE.keys()) self.assertEqual(pyamf.CLASS_CACHE['spam.eggs'], alias) self.assertTrue(isinstance(alias, pyamf.ClassAlias)) self.assertEqual(alias.klass, Spam) self.assertEqual(alias.alias, 'spam.eggs') self.assertFalse(alias._compiled) class UnregisterClassTestCase(ClassCacheClearingTestCase): """ Tests for L{pyamf.unregister_class} """ def test_alias(self): self.assertFalse('foo' in pyamf.CLASS_CACHE) self.assertRaises(pyamf.UnknownClassAlias, pyamf.unregister_class, 'foo') def test_class(self): self.assertFalse(Spam in pyamf.CLASS_CACHE) self.assertRaises(pyamf.UnknownClassAlias, pyamf.unregister_class, Spam) def test_remove(self): alias = ClassAlias(Spam, 'foo', defer=True) pyamf.CLASS_CACHE['foo'] = alias pyamf.CLASS_CACHE[Spam] = alias self.assertFalse(alias.anonymous) ret = pyamf.unregister_class('foo') self.assertFalse('foo' in pyamf.CLASS_CACHE) self.assertFalse(Spam in pyamf.CLASS_CACHE) self.assertTrue(ret is alias) def test_anonymous(self): alias = ClassAlias(Spam, defer=True) pyamf.CLASS_CACHE['foo'] = alias pyamf.CLASS_CACHE[Spam] = alias self.assertTrue(alias.anonymous) ret = pyamf.unregister_class(Spam) self.assertTrue('foo' in pyamf.CLASS_CACHE) self.assertFalse(Spam in pyamf.CLASS_CACHE) self.assertTrue(ret is alias)
mit
dvoraka/pygl-prototype
tests/test_data.py
1
1111
# -*- encoding: utf-8 -*- from __future__ import unicode_literals from __future__ import print_function import unittest import math import data class TestPoint(unittest.TestCase): def setUp(self): pass def test_test(self): self.assertEqual(True, True) def test_chunk_distance(self): p1 = data.Point(0, 0, 0) p2 = data.Point(0, 0, 0) result = p1.chunk_distance(p2) self.assertAlmostEqual(result, 0) p1 = data.Point(0, 0, 0) p2 = data.Point(0, 150, 0) result = p1.chunk_distance(p2) self.assertAlmostEqual(result, 0) p1 = data.Point(-10, 0, 0) p2 = data.Point(10, 0, 0) result = p1.chunk_distance(p2) self.assertAlmostEqual(result, 20) p1 = data.Point(0, 0, 10) p2 = data.Point(0, 0, -10) result = p1.chunk_distance(p2) self.assertAlmostEqual(result, 20) p1 = data.Point(-10, 0, 10) p2 = data.Point(10, 0, -10) result = p1.chunk_distance(p2) self.assertAlmostEqual(result, math.sqrt(pow(20, 2) + pow(-20, 2)))
gpl-3.0
DataCanvasIO/example-modules
modules/modeling/CDH4/item2item/browsing_recommendation/specparser.py
10
27353
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2014, DataCanvasIO # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are # permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of # conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, this list # of conditions and the following disclaimer in the documentation and/or other # materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors may be # used to endorse or promote products derived from this software without specific # prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT # SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED # TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR # BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH # DAMAGE. """ A minimum spec.json parser. """ __version__ = "0.2.9" __author__ = "xiaolin" import json from collections import namedtuple import types import os import sys import time import itertools import subprocess def gettype(name): type_map = { "string" : "str", "integer" : "int", "float" : "float", "enum" : "str", "file" : "str" } if name not in type_map: raise ValueError(name) t = __builtins__.get(type_map[name], types.StringType) if isinstance(t, type): return t raise ValueError(name) def read_whole_file(filename): with open(filename, "r") as f: return f.read() class Input(str): def __new__(self, x, _types): return str.__new__(self, x) def __init__(self, x, _types): self.x = x self._types = _types def __repr__(self): return str(self.x) def __str__(self): return str(self.x) def as_first_line(self): with open(self.x, "r") as f: return f.readline().rstrip() def as_whole(self): with open(self.x, "r") as f: return f.read() def as_file(self, mode="r"): return open(self.x, mode) def as_datasource(self, mode="r"): ds = json.loads(open(self.x, mode).read()) return ds @property def val(self): # TODO: fix types handling if "datasource" in self._types: return self.as_datasource()['URL'] else: return self.as_first_line() @property def types(self): return self._types class Output(str): def __new__(self, x, _types): return str.__new__(self, x) def __init__(self, x, _types): self.x = x self._types = _types def __repr__(self): return str(self.x) def __str__(self): return str(self.x) def as_first_line(self): with open(self.x, "r") as f: return f.readline().rstrip() def as_whole(self): with open(self.x, "r") as f: return f.read() def as_file(self, mode="r"): return open(self.x, mode) @property def val(self): return self.as_first_line() @val.setter def val(self, value): with open(self.x, "w+") as f: f.write(value) @property def types(self): return self._types class Param(str): def __new__(self, x, typeinfo): return str.__new__(self, x) def __init__(self, x, typeinfo): self._x = x self._typeinfo = typeinfo def __repr__(self): return str(self._x) def __str__(self): return str(self._x) @property def val(self): type_handler = { "string" : lambda x: x, "float" : lambda x: float(x), "integer" : lambda x: int(x), "enum" : lambda x: x, "file" : read_whole_file } param_type = self._typeinfo['Type'] if param_type in type_handler: return type_handler[param_type](self._x) else: return self._x def input_output_builder(spec_input, spec_output): import sys params = dict(arg.split("=") for arg in sys.argv[1:]) if not all(k in params for k in spec_input.keys()): raise ValueError("Missing input parameters") if not all(k in params for k in spec_output.keys()): raise ValueError("Missing output parameters") InputSettings = namedtuple('InputSettings', spec_input.keys()) in_params = {in_k:Input(params[in_k], in_type) for in_k, in_type in spec_input.items()} input_settings = InputSettings(**in_params) OutputSettings = namedtuple('OutputSettings', spec_output.keys()) out_params = {out_k:Output(params[out_k], out_type) for out_k,out_type in spec_output.items()} output_settings = OutputSettings(**out_params) return input_settings, output_settings def param_builder(spec_param, param_json): def get_param(k): if k in param_json: return param_json[k]['Val'] else: return spec_param[k]['Default'] ParamSettings = namedtuple('ParamSettings', spec_param.keys()) param_dict = {k:Param(get_param(k), v) for k, v in spec_param.items()} env_settings = ParamSettings(**param_dict) return env_settings def global_param_builder(param_json): return {k:v['Val'] for k, v in param_json.items()} def get_settings(spec_json): moderate_keys = ['Name', 'Param', 'Input', 'Output', 'Cmd', 'Description'] if not all(k in spec_json for k in moderate_keys): raise ValueError("One of param from %s may not exist in 'spec.json'" % str(moderate_keys)) # TODO: condition for appending 'GlobalParam' moderate_keys.append('GlobalParam') ModuleSetting = namedtuple('ModuleSetting', moderate_keys) # Load parameters param_json = get_json_file(os.getenv("ZETRT")) param = param_builder(spec_json['Param'], param_json['PARAM']) json_input, json_output = input_output_builder(spec_json['Input'], spec_json['Output']) # TODO: global_param = global_param_builder(param_json['GLOBAL_PARAM']) settings = ModuleSetting(Name=spec_json['Name'], Description=spec_json['Description'], Param=param, Input=json_input, Output=json_output, Cmd=spec_json['Cmd'], GlobalParam=global_param) return settings def get_json_file(filename): with open(filename, "r") as f: return json.load(f) def get_settings_from_file(filename): with open(filename, "r") as f: return get_settings(json.load(f)) def get_settings_from_string(spec_json_str): print(json.loads(spec_json_str)) return get_settings(json.loads(spec_json_str)) # Various Runtime: Hive, Hadoop, Pig class ZetRuntime(object): def __init__(self, spec_filename="spec.json"): self.settings = get_settings_from_file(spec_filename) def __repr__(self): return str(self.settings) class HadoopRuntime(ZetRuntime): def __init__(self, spec_filename="spec.json"): super(HadoopRuntime, self).__init__(spec_filename=spec_filename) @property def hdfs_root(self): ps = self.settings if 'hdfs_root' in ps.Param._asdict(): return ps.Param.hdfs_root.val else: return '/' def get_hdfs_working_dir(self, path=""): ps = self.settings glb_vars = ps.GlobalParam # return os.path.join(self.hdfs_root, 'tmp/zetjob', glb_vars['userName'], "job%s" % glb_vars['jobId'], "blk%s" % glb_vars['blockId'], path) remote_path = os.path.normpath(os.path.join('tmp/zetjob', glb_vars['userName'], "job%s" % glb_vars['jobId'], "blk%s" % glb_vars['blockId'], path)) return os.path.join(self.hdfs_root, remote_path) def get_hive_namespace(self): ps = self.settings glb_vars = ps.GlobalParam return "zetjobns_%s_job%s_blk%s" % (glb_vars['userName'], glb_vars['jobId'], glb_vars['blockId']) def hdfs_upload_dir(self, local_dir): for root_dir, dirs, files in os.walk(local_dir): for f in sorted(files): f = os.path.normpath(os.path.join(root_dir, f)) f_remote = self.get_hdfs_working_dir(f) hdfs_safe_upload(f, f_remote) yield f_remote def hdfs_clean_working_dir(self): hdfs_working_dir = self.get_hdfs_working_dir() if not clean_hdfs_path(hdfs_working_dir): # TODO : refactor to 'HiveException' raise Exception("Can not clean hdfs path : %s" % hdfs_working_dir) def clean_working_dir(self): self.hdfs_clean_working_dir() class EmrRuntime(HadoopRuntime): def __init__(self, spec_filename="spec.json"): import boto from boto.emr.connection import EmrConnection, RegionInfo super(EmrRuntime, self).__init__(spec_filename) p = self.settings.Param self.s3_conn = boto.connect_s3(p.AWS_ACCESS_KEY_ID, p.AWS_ACCESS_KEY_SECRET) self.s3_bucket = self.s3_conn.get_bucket(p.S3_BUCKET) self.region = p.AWS_Region self.emr_conn = EmrConnection(p.AWS_ACCESS_KEY_ID, p.AWS_ACCESS_KEY_SECRET, region = RegionInfo(name = self.region, endpoint = self.region + '.elasticmapreduce.amazonaws.com')) self.job_flow_id = p.EMR_jobFlowId def get_s3_working_dir(self, path=""): ps = self.settings glb_vars = ps.GlobalParam remote_path = os.path.normpath(os.path.join(self.s3_bucket.name, 'zetjob', glb_vars['userName'], "job%s" % glb_vars['jobId'], "blk%s" % glb_vars['blockId'], path)) return os.path.join("s3://", remote_path) def get_emr_job_name(self): ps = self.settings glb_vars = ps.GlobalParam return os.path.join('zetjob', glb_vars['userName'], "job%s" % glb_vars['jobId'], "blk%s" % glb_vars['blockId']) def s3_upload_dir(self, local_dir): print("EmrHiveRuntime.s3_uploader()") print("s3_upload_dir :::: %s" % local_dir) if local_dir == "": return if not os.path.isdir(local_dir): return s3_upload_dir = self.get_s3_working_dir(local_dir) ext_files = [f for f in sorted(os.listdir(local_dir)) if os.path.isfile(os.path.join(local_dir,f))] for f in ext_files: f_local = os.path.join(local_dir, f) f_remote_full = self.get_s3_working_dir(os.path.join(local_dir, f)) print("S3 Upload :: %s ====> %s" % (f_local, s3_upload_dir)) print("S3 remote_full :: %s" % f_remote_full) yield s3_upload(self.s3_bucket, f_local, f_remote_full) def s3_clean_working_dir(self): s3_working_dir = self.get_s3_working_dir() if not s3_delete(self.s3_bucket, s3_working_dir): # TODO : refactor to 'HiveException' raise Exception("Can not clean s3 path : %s" % s3_working_dir) def s3_upload(self, filename): from urlparse import urlparse parse_ret = urlparse(filename) if parse_ret.scheme == '': s3_working_dir = self.get_s3_working_dir() file_remote = os.path.join(s3_working_dir, os.path.normpath(os.path.basename(filename))) file_remote_full = s3_upload(self.s3_bucket, filename, file_remote) return file_remote_full elif parse_ret.scheme == 's3': return filename else: raise ValueError("Invalid filename to upload to s3: %s" % filename) def clean_working_dir(self): self.s3_clean_working_dir() class HiveRuntime(HadoopRuntime): def files_uploader(self, local_dir): return self.hdfs_upload_dir(local_dir) def hive_output_builder(self, output_name, output_obj): # TODO: refactor this method ps = self.settings glb_vars = ps.GlobalParam out_type = output_obj.types[0] if out_type.startswith("hive.table"): return "zetjob_%s_job%s_blk%s_OUTPUT_%s" % (glb_vars['userName'], glb_vars['jobId'], glb_vars['blockId'], output_name) elif out_type.startswith("hive.hdfs"): return self.get_hdfs_working_dir("OUTPUT_%s" % output_name) else: raise ValueError("Invalid type for hive, type must start with 'hive.table' or 'hive.hdfs'") def header_builder(self, hive_ns, uploaded_files, uploaded_jars): # Build Output Tables for output_name,output_obj in self.settings.Output._asdict().items(): output_obj.val = self.hive_output_builder(output_name, output_obj) return "\n".join( itertools.chain( ["ADD FILE %s;" % f for f in uploaded_files], ["ADD JAR %s;" % f for f in uploaded_jars], ["set hivevar:MYNS = %s;" % hive_ns], ["set hivevar:PARAM_%s = %s;" % (k,v) for k,v in self.settings.Param._asdict().items()], ["set hivevar:INPUT_%s = %s;" % (k,v.val) for k,v in self.settings.Input._asdict().items()], ["set hivevar:OUTPUT_%s = %s;" % (k,v.val) for k,v in self.settings.Output._asdict().items()])) def clean_working_dir(self): self.hdfs_clean_working_dir() def generate_script(self, hive_script, target_filename=None): hive_ns = self.get_hive_namespace() # Upload files and UDF jars if 'FILE_DIR' in self.settings.Param._asdict(): file_dir = self.settings.Param.FILE_DIR uploaded_files = self.files_uploader(file_dir.val) else: uploaded_files = [] if 'UDF_DIR' in self.settings.Param._asdict(): jar_dir = self.settings.Param.UDF_DIR uploaded_jars = self.files_uploader(jar_dir.val) else: uploaded_jars = [] # Build Input, Output and Param header = self.header_builder(hive_ns, uploaded_files, uploaded_jars) if target_filename == None: import tempfile tmp_file = tempfile.NamedTemporaryFile(prefix="hive_generated_", suffix=".hql", delete=False) tmp_file.close() target_filename = tmp_file.name with open(hive_script, "r") as f, open(target_filename, "w+") as out_f: out_f.write("--------------------------\n") out_f.write("-- Header\n") out_f.write("--------------------------\n") out_f.write(header) out_f.write("\n") out_f.write("--------------------------\n") out_f.write("-- Main\n") out_f.write("--------------------------\n") out_f.write("\n") out_f.write(f.read()) return target_filename def execute(self, hive_script, generated_hive_script=None): self.clean_working_dir() generated_hive_script = self.generate_script(hive_script, generated_hive_script) if cmd("beeline -u jdbc:hive2://%s:%s -n hive -p tiger -d org.apache.hive.jdbc.HiveDriver -f '%s' --verbose=true " % (self.settings.Param.HiveServer2_Host, self.settings.Param.HiveServer2_Port, generated_hive_script)) != 0: raise Exception("Failed to execute hive script : %s" % generated_hive_script) class EmrHiveRuntime(EmrRuntime, HiveRuntime): def __init__(self, spec_filename="spec.json"): super(EmrHiveRuntime, self).__init__(spec_filename) def hive_output_builder(self, output_name, output_obj): # TODO : should refactor this function to base class ps = self.settings glb_vars = ps.GlobalParam out_type = output_obj.types[0] if out_type.startswith("hive.table"): return "zetjob_%s_job%s_blk%s_OUTPUT_%s" % (glb_vars['userName'], glb_vars['jobId'], glb_vars['blockId'], output_name) elif out_type.startswith("hive.hdfs"): return self.get_hdfs_working_dir("OUTPUT_%s" % output_name) elif out_type.startswith("hive.s3"): return self.get_s3_working_dir("OUTPUT_%s" % output_name) else: raise ValueError("Invalid type for hive, type must start with 'hive.table' or 'hive.hdfs' or 'hive.s3'") def files_uploader(self, local_dir): return self.s3_upload_dir(local_dir) def emr_execute_hive(self, s3_hive_script): from boto.emr.step import HiveStep hive_step = HiveStep(name=self.get_emr_job_name(), hive_file=s3_hive_script) self.emr_conn.add_jobflow_steps(self.job_flow_id, steps=[hive_step]) emr_wait_job(self.emr_conn, self.job_flow_id) def execute(self, main_hive_script, generated_hive_script=None): self.clean_working_dir() hive_script_local = self.generate_script(main_hive_script, generated_hive_script) s3_working_dir = self.get_s3_working_dir() hive_script_remote = os.path.join(s3_working_dir, os.path.basename(hive_script_local)) hive_script_remote_full = s3_upload(self.s3_bucket, hive_script_local, hive_script_remote) print("========= Generated Hive Script =========") print(open(hive_script_local).read()) print("=========================================") print("EmrHiveRuntime.execute()") self.emr_execute_hive(hive_script_remote_full) class EmrJarRuntime(EmrRuntime): def __init__(self, spec_filename="spec.json"): super(EmrJarRuntime, self).__init__(spec_filename) def execute(self, jar_path, args): from boto.emr.step import JarStep s3_jar_path = s3_upload(self.s3_bucket, jar_path, self.get_s3_working_dir(jar_path)) # s3_jar_path = "s3://run-jars/jar/mahout-core-1.0-SNAPSHOT-job.jar" print("Uploading jar to s3 : %s -> %s" % (jar_path, s3_jar_path)) print("Add jobflow step") step = JarStep(name='cl_filter', jar=s3_jar_path, step_args=args) self.emr_conn.add_jobflow_steps(self.job_flow_id, steps=[step]) print("Waiting jobflow step done") emr_wait_job(self.emr_conn, self.job_flow_id) class PigRuntime(HadoopRuntime): def __init__(self, spec_filename="spec.json"): super(PigRuntime, self).__init__(spec_filename) def files_uploader(self, local_dir): return self.hdfs_upload_dir(local_dir) def pig_output_builder(self, output_name, output_obj): # TODO: refactor this method ps = self.settings glb_vars = ps.GlobalParam out_type = output_obj.types[0] if out_type.startswith("pig.hdfs"): return self.get_hdfs_working_dir("OUTPUT_%s" % output_name) else: raise ValueError("Invalid type for pig, type must start with 'pig.hdfs'") def header_builder(self, uploaded_jars): # Build Output Tables for output_name,output_obj in self.settings.Output._asdict().items(): output_obj.val = self.pig_output_builder(output_name, output_obj) return "\n".join( itertools.chain( ["%%declare PARAM_%s '%s'" % (k,v) for k,v in self.settings.Param._asdict().items()], ["%%declare INPUT_%s '%s'" % (k,v.val) for k,v in self.settings.Input._asdict().items()], ["%%declare OUTPUT_%s '%s'" % (k,v.val) for k,v in self.settings.Output._asdict().items()], ["REGISTER '%s';" % f for f in uploaded_jars] )) def generate_script(self, pig_script, target_filename=None): if 'UDF_DIR' in self.settings.Param._asdict(): jar_dir = self.settings.Param.UDF_DIR uploaded_jars = self.files_uploader(jar_dir.val) else: uploaded_jars = [] # Build Input, Output and Param header = self.header_builder(uploaded_jars) if target_filename == None: import tempfile tmp_file = tempfile.NamedTemporaryFile(prefix="pig_generated_", suffix=".hql", delete=False) tmp_file.close() target_filename = tmp_file.name with open(pig_script, "r") as f, open(target_filename, "w+") as out_f: out_f.write("/*************************\n") out_f.write(" * Header\n") out_f.write(" *************************/\n") out_f.write(header) out_f.write("\n") out_f.write("/*************************\n") out_f.write(" * Main\n") out_f.write(" *************************/\n") out_f.write("\n") out_f.write(f.read()) return target_filename def generate_pig_conf(self): ps = self.settings glb_vars = ps.GlobalParam with open("/home/run/pig.properties", "a") as pf: pf.write("fs.default.name=%s\n" % ps.Param.hdfs_root) pf.write("yarn.resourcemanager.address=%s\n" % ps.Param.yarn_address) pf.write("yarn.resourcemanager.scheduler.address=%s\n" % ps.Param.yarn_scheduler_address) cmd("cat /home/run/pig.properties") def execute(self, pig_script): self.clean_working_dir() self.generate_pig_conf() generated_pig_script = self.generate_script(pig_script) print("========= Generated Pig Script =========") print(open(generated_pig_script).read()) print("=========================================") print("EmrHiveRuntime.execute()") cmd("pig -x mapreduce -P /home/run/pig.properties %s" % generated_pig_script) class EmrPigRuntime(EmrRuntime, PigRuntime): def __init__(self, spec_filename="spec.json"): super(EmrPigRuntime, self).__init__(spec_filename) def files_uploader(self, local_dir): return self.s3_upload_dir(local_dir) def pig_output_builder(self, output_name, output_obj): # TODO : should refactor this function to base class ps = self.settings glb_vars = ps.GlobalParam out_type = output_obj.types[0] if out_type.startswith("pig.hdfs"): return self.get_hdfs_working_dir("OUTPUT_%s" % output_name) elif out_type.startswith("pig.s3"): return self.get_s3_working_dir("OUTPUT_%s" % output_name) else: raise ValueError("Invalid type for pig, type must start with 'pig.hdfs' or 'pig.s3'") def emr_execute_pig(self, pig_filename): from boto.emr.step import PigStep s3_pig_script = self.s3_upload(pig_filename) pig_step = PigStep(name=self.get_emr_job_name(), pig_file=s3_pig_script) self.emr_conn.add_jobflow_steps(self.job_flow_id, steps=[pig_step]) emr_wait_job(self.emr_conn, self.job_flow_id) def execute(self, pig_script): self.clean_working_dir() # TODO: upload S3 additional files generated_pig_script = self.generate_script(pig_script) print("========= Generated Pig Script =========") print(open(generated_pig_script).read()) print("=========================================") print("EmrHiveRuntime.execute()") self.emr_execute_pig(generated_pig_script) # Utility Functions def clean_hdfs_path(p): if cmd("hadoop fs -rm -r -f %s && hadoop fs -mkdir -p %s" % (p, p)) == 0: return True else: return False def hdfs_safe_upload(f_local, f_remote): f_remote_dir = os.path.dirname(f_remote) if cmd("hadoop fs -mkdir -p %s" % f_remote_dir) != 0: raise Exception("Failed to create dir %s" % f_remote_dir) print("HDFS Upload :: %s ====> %s" % (f_local, f_remote)) if cmd("hadoop fs -copyFromLocal %s %s" % (f_local, f_remote_dir)) != 0: raise Exception("Failed to upload file %s to %s" % (f_local, f_remote_dir)) def percent_cb(complete, total): sys.stdout.write('.') sys.stdout.flush() def s3_delete(bucket, s3_path): import boto from urlparse import urlparse print("s3_delete %s" % s3_path) prefix_path = urlparse(s3_path).path[1:] for key in bucket.list(prefix=prefix_path): key.delete() return True def s3_upload(bucket, local_filename, remote_filename): import boto from urlparse import urlparse # max size in bytes before uploading in parts. # between 1 and 5 GB recommended MAX_SIZE = 40 * 1000 * 1000 # size of parts when uploading in parts PART_SIZE = 6 * 1000 * 1000 fn_local = os.path.normpath(local_filename) fn_remote = urlparse(remote_filename).path fn_remote_full = remote_filename filesize = os.path.getsize(local_filename) print("filesize = %d, maxsize = %d" % (filesize, MAX_SIZE)) if filesize > MAX_SIZE: print("Multi-part uploading...") print("From : %s" % fn_local) print("To : %s" % fn_remote_full) mp = bucket.initiate_multipart_upload(fn_local) fp = open(sourcepath,'rb') fp_num = 0 while (fp.tell() < filesize): fp_num += 1 print "uploading part %i" % fp_num mp.upload_part_from_file(fp, fp_num, cb=percent_cb, num_cb=10, size=PART_SIZE) mp.complete_upload() print("") else: print("Single-part upload...") print("From : %s" % fn_local) print("To : %s" % fn_remote_full) k = boto.s3.key.Key(bucket) k.key = fn_remote k.set_contents_from_filename(fn_local, cb=percent_cb, num_cb=10) print("") return fn_remote_full def emr_wait_job(emr_conn, job_flow_id): blocking_states = ['STARTING', 'BOOTSTRAPPING', 'RUNNING'] cnt = 60 * 60 * 1 # 1 hour time.sleep(10) while cnt > 0: jf_state = emr_conn.describe_jobflow(job_flow_id).state print("jobflow_state = %s" % jf_state) if jf_state not in blocking_states: if jf_state == 'WAITING': print("Job done, continue...") return True else: print("Job may failed.") return False cnt = cnt - 1 time.sleep(10) return False def cmd(cmd_str): print("Execute External Command : '%s'" % cmd_str) ret = subprocess.call(cmd_str, shell=True) print("Exit with exit code = %d" % ret) return ret if __name__ == "__main__": # settings = get_settings_from_file("spec.json") # print(settings) # print(settings.Input) # print(settings.Output) # print("-----------------") # i = Input("test.param") # print(i) # print(i.as_one_line()) # print(i.as_all_line()) # t = MyTest(4) # print(t.val) # t.val = 5 # print(t.val) # o = Output("out.param") # print(o) # print(o.val) # o.val = "cacaca" # settings = get_settings_from_file("spec.json") # hive_runtime = HiveRuntime() # print(hive_runtime) emr_hive_runtime = EmrHiveRuntime() emr_hive_runtime.execute()
bsd-3-clause
01000101/python-cloudforms
Cloudforms/managers/provision_request.py
1
4005
''' Cloudforms.ProvisionRequestManager ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Provision Request Manager :license: MIT, see LICENSE for more details. ''' from time import sleep from datetime import datetime, timedelta from Cloudforms.utils import ( update_params, normalize_object, normalize_collection ) class ProvisionRequestManager(object): '''Manages Provision Requests. :param Cloudforms.API.Client client: an API client instance Example:: import Cloudforms client = Cloudforms.Client() preq_mgr = Cloudforms.ProvisionRequestManager(client) ''' def __init__(self, client): self.client = client def get(self, _id, params=None): '''Retrieve details about a provision request on the account :param string _id: Specifies which provision request the request is for :param dict params: response-level options (attributes, limit, etc.) :returns: Dictionary representing the matching provision request Example:: # Gets a list of all provision requests (returns IDs only) preqs = preq_mgr.list({'attributes': 'id'}) for preq in preqs: preq_details = preq_mgr.get(preq['id']) ''' params = update_params(params, {'expand': 'resources'}) return normalize_object( self.client.call('get', '/provision_requests/%s' % _id, params=params)) def list(self, params=None): '''Retrieve a list of all provision requests on the account :param dict params: response-level options (attributes, limit, etc.) :returns: List of dictionaries representing the matching provision requests Example:: # Gets a list of all provision requests (returns IDs only) preqs = preq_mgr.list({'attributes': 'id'}) ''' params = update_params(params, {'expand': 'resources'}) return normalize_collection( self.client.call('get', '/provision_requests', params=params)) def perform_action(self, _id, action, params=None): '''Sends a request to perform an action on a provision request :param string _id: Specifies which provision request the request is for :param string action: The action to request (delete, refresh, etc.) :param dict params: Additional POST request data :returns: ProvisionRequest dictionary object ''' params = update_params(params, {'action': action}) return normalize_object( self.client.call('post', '/provision_requests/%s' % _id, data=params)) def create(self, params=None): '''Creates a new provision request on the account :param dict params: Additional POST request data :returns: ProvisionRequest dictionary object ''' params = update_params(params, {'action': 'create'}) return normalize_object( self.client.call('post', '/provision_requests', data=params)) def wait(self, _id, timeout=30, request_state='finished', params=None): '''Waits for a provision request to reach a certain request_state :param string request_state: wait until the provision request reaches this request_state (case insensitive) :param integer timeout: operation timeout (in seconds) :param dict params: response-level options (attributes, limit, etc.) :returns bool: **True** on success, **False** on error or timeout ''' deadline = datetime.now() + timedelta(seconds=timeout) while datetime.now() <= deadline: preq = self.get(_id, params=params) if not preq or not preq.get('request_state'): return False elif preq.get('request_state').lower() == request_state.lower(): return True sleep(1) return False
mit
wemanuel/smry
smry/Crypto/SelfTest/Random/__init__.py
105
1973
# -*- coding: utf-8 -*- # # SelfTest/Random/__init__.py: Self-test for random number generation modules # # Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net> # # =================================================================== # The contents of this file are dedicated to the public domain. To # the extent that dedication to the public domain is not available, # everyone is granted a worldwide, perpetual, royalty-free, # non-exclusive license to exercise all rights associated with the # contents of this file for any purpose whatsoever. # No rights are reserved. # # 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. # =================================================================== """Self-test for random number generators""" __revision__ = "$Id$" def get_tests(config={}): tests = [] from Crypto.SelfTest.Random import Fortuna; tests += Fortuna.get_tests(config=config) from Crypto.SelfTest.Random import OSRNG; tests += OSRNG.get_tests(config=config) from Crypto.SelfTest.Random import test_random; tests += test_random.get_tests(config=config) from Crypto.SelfTest.Random import test_rpoolcompat; tests += test_rpoolcompat.get_tests(config=config) from Crypto.SelfTest.Random import test__UserFriendlyRNG; tests += test__UserFriendlyRNG.get_tests(config=config) return tests if __name__ == '__main__': import unittest suite = lambda: unittest.TestSuite(get_tests()) unittest.main(defaultTest='suite') # vim:set ts=4 sw=4 sts=4 expandtab:
apache-2.0
ninastempelj/paper_soccer
navodila.py
1
3148
import tkinter as tk import os class Navodila: def __init__(self, master): self.master = master self.polje = tk.Canvas(master) self.polje.pack(fill='both', expand='yes') self.polje.config(bg="grey20") # Vse slike: master.slika_ozadje_id = tk.PhotoImage( file=os.path.join('slike', 'pergament.gif')) master.slika_prvic_id = tk.PhotoImage( file=os.path.join('slike', 'prvic_v_polju.GIF')) master.slika_ponovno_id = tk.PhotoImage( file=os.path.join('slike', 'ponovno_v_polju.gif')) master.slika_rob_id = tk.PhotoImage( file=os.path.join('slike', 'na_robu.gif')) # Vsi napisi naslov = "Navodila igre" napis1 = "Cilj igre je pripeljati žogo v svoj gol. " \ "Vsakemu igralcu smer igre kaže puščica v njegovi barvi," \ " kadar je na vrsti. Igralca izmenično premikata isto žogo," \ " pri tem veljajo pravila:\n" \ " - Žoge ne moremo brcniti dvakrat po isti poti.\n" \ " - Vsak igralec se lahko premakne v vseh 8 različnih smereh" \ " (tudi po diagonali), če pot še ni bila igrana.\n" \ " - Če igralec brcne žogo v točko, kjer je žoga že kdaj " \ "prej bila, jo lahko brcne še enkrat. " napis2 = "Posebna pravila na robu:\n" \ " - Žoga se od roba odbije, isti igralec je na vrsti " \ "še enkrat.\n" \ " - Pot po robu ni mogoča." napis3 = "Lahko se zgodi, da nimamo več nobene možne poti iz polja, " \ "kjer se nahajamo. V tem primeru je igra izenačena. " \ "Igra se konča, če pride do izenačenja, ali eden izmed " \ "igralcev zadane gol." self.polje.create_image(0, 5, anchor="nw", image=master.slika_ozadje_id) self.polje.create_text(170, 25, anchor="nw", text=naslov, font="Helvetica 12 bold", fill="white") self.polje.create_text(65, 50, anchor="nw", text=napis1, width=330, fill="white") self.polje.create_image(70,182, anchor="nw", image=master.slika_prvic_id) self.polje.create_image(235, 182, anchor="nw", image=master.slika_ponovno_id) self.polje.create_text(65, 308, anchor="nw", text=napis2, width=330, fill="white") self.polje.create_image(170, 365, anchor="nw", image=master.slika_rob_id) self.polje.create_text(65, 471, anchor="nw", text=napis3, width=330, fill="white") gumb_nazaj = tk.Button(master, text='Nazaj', command=self.zapri) self.polje.create_window(235,580, window=gumb_nazaj) self.master.attributes("-topmost", True) self.polje.focus_force() master.bind("<Escape>", self.zapri) master.bind("<Return>", self.zapri) self.master.geometry("450x650") def zapri(self, event=None): self.master.destroy()
mit
TeamTwisted/external_chromium_org
tools/memory_inspector/memory_inspector/backends/prebuilts_fetcher.py
90
2102
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """This module fetches and syncs prebuilts from Google Cloud Storage (GCS). See prebuilts/README for a description of the respository <> GCS sync mechanism. """ import hashlib import logging import os import urllib from memory_inspector import constants # Bypass the GCS download logic in unittests and use the *_ForTests mock. in_test_harness = False def GetIfChanged(local_file_path): """Downloads the file from GCS, only if the local one is outdated.""" is_changed = _IsChanged(local_file_path) # In test harness mode we are only interested in checking that the proper # .sha1 files have been checked in (hence the call to _IsChanged() above). if in_test_harness: return _GetIfChanged_ForTests(local_file_path) if not is_changed: return obj_name = _GetRemoteFileID(local_file_path) url = constants.PREBUILTS_BASE_URL + obj_name logging.info('Downloading %s prebuilt from %s.' % (local_file_path, url)) urllib.urlretrieve(url, local_file_path) assert(not _IsChanged(local_file_path)), ('GCS download for %s failed.' % local_file_path) def _IsChanged(local_file_path): """Checks whether the local_file_path exists and matches the expected hash.""" is_changed = True expected_hash = _GetRemoteFileID(local_file_path) if os.path.exists(local_file_path): with open(local_file_path, 'rb') as f: local_hash = hashlib.sha1(f.read()).hexdigest() is_changed = (local_hash != expected_hash) return is_changed def _GetRemoteFileID(local_file_path): """Returns the checked-in hash which identifies the name of file in GCS.""" hash_path = local_file_path + '.sha1' with open(hash_path, 'rb') as f: return f.read(1024).rstrip() def _GetIfChanged_ForTests(local_file_path): """This is the mock version of |GetIfChanged| used only in unittests.""" # Just truncate / create an empty file. open(local_file_path, 'wb').close()
bsd-3-clause
golden-tech-native/gd_facerecognize
facelib/openface/data.py
11
2966
# coding=utf8 # # Copyright 2015-2016 Carnegie Mellon University # # 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. """Module for image data.""" import os import cv2 class Image: """Object containing image metadata.""" def __init__(self, cls, name, path): """ Instantiate an 'Image' object. :param cls: The image's class; the name of the person. :type cls: str :param name: The image's name. :type name: str :param path: Path to the image on disk. :type path: str """ assert cls is not None assert name is not None assert path is not None self.cls = cls self.name = name self.path = path def getBGR(self): """ Load the image from disk in BGR format. :return: BGR image. Shape: (height, width, 3) :rtype: numpy.ndarray """ try: bgr = cv2.imread(self.path) except: bgr = None return bgr def getRGB(self): """ Load the image from disk in RGB format. :return: RGB image. Shape: (height, width, 3) :rtype: numpy.ndarray """ bgr = self.getBGR() if bgr is not None: rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB) else: rgb = None return rgb def __repr__(self): """String representation for printing.""" return "({}, {})".format(self.cls, self.name) def iterImgs(directory): u""" Iterate through the images in a directory. The images should be organized in subdirectories named by the image's class (who the person is):: $ tree directory person-1 ├── image-1.jpg ├── image-2.png ... └── image-p.png ... person-m ├── image-1.png ├── image-2.jpg ... └── image-q.png :param directory: The directory to iterate through. :type directory: str :return: An iterator over Image objects. """ assert directory is not None exts = [".jpg", ".jpeg", ".png"] for subdir, dirs, files in os.walk(directory): for path in files: (imageClass, fName) = (os.path.basename(subdir), path) (imageName, ext) = os.path.splitext(fName) if ext.lower() in exts: yield Image(imageClass, imageName, os.path.join(subdir, fName))
mit
cloudnull/ansible
lib/ansible/plugins/callback/context_demo.py
144
1447
# (C) 2012, Michael DeHaan, <michael.dehaan@gmail.com> # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. from ansible.plugins.callback import CallbackBase class CallbackModule(CallbackBase): """ This is a very trivial example of how any callback function can get at play and task objects. play will be 'None' for runner invocations, and task will be None for 'setup' invocations. """ CALLBACK_VERSION = 2.0 CALLBACK_TYPE = 'aggregate' CALLBACK_TYPE = 'context_demo' def v2_on_any(self, *args, **kwargs): i = 0 self._display.display(" --- ARGS ") for a in args: self._display.display(' %s: %s' % (i, a)) i += 1 self._display.display(" --- KWARGS ") for k in kwargs: self._display.display(' %s: %s' % (k, kwargs[k]))
gpl-3.0
luzheqi1987/nova-annotation
nova/tests/unit/virt/vmwareapi/test_volumeops.py
1
4069
# Copyright 2013 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import contextlib import mock from nova import test from nova.tests.unit.virt.vmwareapi import fake as vmwareapi_fake from nova.tests.unit.virt.vmwareapi import stubs from nova.virt.vmwareapi import driver from nova.virt.vmwareapi import volumeops class VMwareVolumeOpsTestCase(test.NoDBTestCase): def setUp(self): super(VMwareVolumeOpsTestCase, self).setUp() vmwareapi_fake.reset() stubs.set_stubs(self.stubs) self._session = driver.VMwareAPISession() self._volumeops = volumeops.VMwareVolumeOps(self._session) self.instance = {'name': 'fake_name', 'uuid': 'fake_uuid'} def _test_detach_disk_from_vm(self, destroy_disk=False): def fake_call_method(module, method, *args, **kwargs): vmdk_detach_config_spec = kwargs.get('spec') virtual_device_config = vmdk_detach_config_spec.deviceChange[0] self.assertEqual('remove', virtual_device_config.operation) self.assertEqual('ns0:VirtualDeviceConfigSpec', virtual_device_config.obj_name) if destroy_disk: self.assertEqual('destroy', virtual_device_config.fileOperation) else: self.assertFalse(hasattr(virtual_device_config, 'fileOperation')) return 'fake_configure_task' with contextlib.nested( mock.patch.object(self._session, '_wait_for_task'), mock.patch.object(self._session, '_call_method', fake_call_method) ) as (_wait_for_task, _call_method): fake_device = vmwareapi_fake.DataObject() fake_device.backing = vmwareapi_fake.DataObject() fake_device.backing.fileName = 'fake_path' fake_device.key = 'fake_key' self._volumeops.detach_disk_from_vm('fake_vm_ref', self.instance, fake_device, destroy_disk) _wait_for_task.assert_has_calls([ mock.call('fake_configure_task')]) def test_detach_with_destroy_disk_from_vm(self): self._test_detach_disk_from_vm(destroy_disk=True) def test_detach_without_destroy_disk_from_vm(self): self._test_detach_disk_from_vm(destroy_disk=False) def _fake_call_get_dynamic_property(self, uuid, result): def fake_call_method(vim, method, vm_ref, type, prop): expected_prop = 'config.extraConfig["volume-%s"]' % uuid self.assertEqual('VirtualMachine', type) self.assertEqual(expected_prop, prop) return result return fake_call_method def test_get_volume_uuid(self): vm_ref = mock.Mock() uuid = '1234' opt_val = vmwareapi_fake.OptionValue('volume-%s' % uuid, 'volume-val') fake_call = self._fake_call_get_dynamic_property(uuid, opt_val) with mock.patch.object(self._session, "_call_method", fake_call): val = self._volumeops._get_volume_uuid(vm_ref, uuid) self.assertEqual('volume-val', val) def test_get_volume_uuid_not_found(self): vm_ref = mock.Mock() uuid = '1234' fake_call = self._fake_call_get_dynamic_property(uuid, None) with mock.patch.object(self._session, "_call_method", fake_call): val = self._volumeops._get_volume_uuid(vm_ref, uuid) self.assertIsNone(val)
apache-2.0
kittiu/odoo
addons/document/wizard/__init__.py
444
1084
# -*- 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 document_configuration # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
IT-Department-Projects/OOAD-Project
Flask_App/oakcrest/lib/python2.7/site-packages/click/parser.py
199
15510
# -*- coding: utf-8 -*- """ click.parser ~~~~~~~~~~~~ This module started out as largely a copy paste from the stdlib's optparse module with the features removed that we do not need from optparse because we implement them in Click on a higher level (for instance type handling, help formatting and a lot more). The plan is to remove more and more from here over time. The reason this is a different module and not optparse from the stdlib is that there are differences in 2.x and 3.x about the error messages generated and optparse in the stdlib uses gettext for no good reason and might cause us issues. """ import re from collections import deque from .exceptions import UsageError, NoSuchOption, BadOptionUsage, \ BadArgumentUsage def _unpack_args(args, nargs_spec): """Given an iterable of arguments and an iterable of nargs specifications, it returns a tuple with all the unpacked arguments at the first index and all remaining arguments as the second. The nargs specification is the number of arguments that should be consumed or `-1` to indicate that this position should eat up all the remainders. Missing items are filled with `None`. """ args = deque(args) nargs_spec = deque(nargs_spec) rv = [] spos = None def _fetch(c): try: if spos is None: return c.popleft() else: return c.pop() except IndexError: return None while nargs_spec: nargs = _fetch(nargs_spec) if nargs == 1: rv.append(_fetch(args)) elif nargs > 1: x = [_fetch(args) for _ in range(nargs)] # If we're reversed, we're pulling in the arguments in reverse, # so we need to turn them around. if spos is not None: x.reverse() rv.append(tuple(x)) elif nargs < 0: if spos is not None: raise TypeError('Cannot have two nargs < 0') spos = len(rv) rv.append(None) # spos is the position of the wildcard (star). If it's not `None`, # we fill it with the remainder. if spos is not None: rv[spos] = tuple(args) args = [] rv[spos + 1:] = reversed(rv[spos + 1:]) return tuple(rv), list(args) def _error_opt_args(nargs, opt): if nargs == 1: raise BadOptionUsage('%s option requires an argument' % opt) raise BadOptionUsage('%s option requires %d arguments' % (opt, nargs)) def split_opt(opt): first = opt[:1] if first.isalnum(): return '', opt if opt[1:2] == first: return opt[:2], opt[2:] return first, opt[1:] def normalize_opt(opt, ctx): if ctx is None or ctx.token_normalize_func is None: return opt prefix, opt = split_opt(opt) return prefix + ctx.token_normalize_func(opt) def split_arg_string(string): """Given an argument string this attempts to split it into small parts.""" rv = [] for match in re.finditer(r"('([^'\\]*(?:\\.[^'\\]*)*)'" r'|"([^"\\]*(?:\\.[^"\\]*)*)"' r'|\S+)\s*', string, re.S): arg = match.group().strip() if arg[:1] == arg[-1:] and arg[:1] in '"\'': arg = arg[1:-1].encode('ascii', 'backslashreplace') \ .decode('unicode-escape') try: arg = type(string)(arg) except UnicodeError: pass rv.append(arg) return rv class Option(object): def __init__(self, opts, dest, action=None, nargs=1, const=None, obj=None): self._short_opts = [] self._long_opts = [] self.prefixes = set() for opt in opts: prefix, value = split_opt(opt) if not prefix: raise ValueError('Invalid start character for option (%s)' % opt) self.prefixes.add(prefix[0]) if len(prefix) == 1 and len(value) == 1: self._short_opts.append(opt) else: self._long_opts.append(opt) self.prefixes.add(prefix) if action is None: action = 'store' self.dest = dest self.action = action self.nargs = nargs self.const = const self.obj = obj @property def takes_value(self): return self.action in ('store', 'append') def process(self, value, state): if self.action == 'store': state.opts[self.dest] = value elif self.action == 'store_const': state.opts[self.dest] = self.const elif self.action == 'append': state.opts.setdefault(self.dest, []).append(value) elif self.action == 'append_const': state.opts.setdefault(self.dest, []).append(self.const) elif self.action == 'count': state.opts[self.dest] = state.opts.get(self.dest, 0) + 1 else: raise ValueError('unknown action %r' % self.action) state.order.append(self.obj) class Argument(object): def __init__(self, dest, nargs=1, obj=None): self.dest = dest self.nargs = nargs self.obj = obj def process(self, value, state): if self.nargs > 1: holes = sum(1 for x in value if x is None) if holes == len(value): value = None elif holes != 0: raise BadArgumentUsage('argument %s takes %d values' % (self.dest, self.nargs)) state.opts[self.dest] = value state.order.append(self.obj) class ParsingState(object): def __init__(self, rargs): self.opts = {} self.largs = [] self.rargs = rargs self.order = [] class OptionParser(object): """The option parser is an internal class that is ultimately used to parse options and arguments. It's modelled after optparse and brings a similar but vastly simplified API. It should generally not be used directly as the high level Click classes wrap it for you. It's not nearly as extensible as optparse or argparse as it does not implement features that are implemented on a higher level (such as types or defaults). :param ctx: optionally the :class:`~click.Context` where this parser should go with. """ def __init__(self, ctx=None): #: The :class:`~click.Context` for this parser. This might be #: `None` for some advanced use cases. self.ctx = ctx #: This controls how the parser deals with interspersed arguments. #: If this is set to `False`, the parser will stop on the first #: non-option. Click uses this to implement nested subcommands #: safely. self.allow_interspersed_args = True #: This tells the parser how to deal with unknown options. By #: default it will error out (which is sensible), but there is a #: second mode where it will ignore it and continue processing #: after shifting all the unknown options into the resulting args. self.ignore_unknown_options = False if ctx is not None: self.allow_interspersed_args = ctx.allow_interspersed_args self.ignore_unknown_options = ctx.ignore_unknown_options self._short_opt = {} self._long_opt = {} self._opt_prefixes = set(['-', '--']) self._args = [] def add_option(self, opts, dest, action=None, nargs=1, const=None, obj=None): """Adds a new option named `dest` to the parser. The destination is not inferred (unlike with optparse) and needs to be explicitly provided. Action can be any of ``store``, ``store_const``, ``append``, ``appnd_const`` or ``count``. The `obj` can be used to identify the option in the order list that is returned from the parser. """ if obj is None: obj = dest opts = [normalize_opt(opt, self.ctx) for opt in opts] option = Option(opts, dest, action=action, nargs=nargs, const=const, obj=obj) self._opt_prefixes.update(option.prefixes) for opt in option._short_opts: self._short_opt[opt] = option for opt in option._long_opts: self._long_opt[opt] = option def add_argument(self, dest, nargs=1, obj=None): """Adds a positional argument named `dest` to the parser. The `obj` can be used to identify the option in the order list that is returned from the parser. """ if obj is None: obj = dest self._args.append(Argument(dest=dest, nargs=nargs, obj=obj)) def parse_args(self, args): """Parses positional arguments and returns ``(values, args, order)`` for the parsed options and arguments as well as the leftover arguments if there are any. The order is a list of objects as they appear on the command line. If arguments appear multiple times they will be memorized multiple times as well. """ state = ParsingState(args) try: self._process_args_for_options(state) self._process_args_for_args(state) except UsageError: if self.ctx is None or not self.ctx.resilient_parsing: raise return state.opts, state.largs, state.order def _process_args_for_args(self, state): pargs, args = _unpack_args(state.largs + state.rargs, [x.nargs for x in self._args]) for idx, arg in enumerate(self._args): arg.process(pargs[idx], state) state.largs = args state.rargs = [] def _process_args_for_options(self, state): while state.rargs: arg = state.rargs.pop(0) arglen = len(arg) # Double dashes always handled explicitly regardless of what # prefixes are valid. if arg == '--': return elif arg[:1] in self._opt_prefixes and arglen > 1: self._process_opts(arg, state) elif self.allow_interspersed_args: state.largs.append(arg) else: state.rargs.insert(0, arg) return # Say this is the original argument list: # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)] # ^ # (we are about to process arg(i)). # # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of # [arg0, ..., arg(i-1)] (any options and their arguments will have # been removed from largs). # # The while loop will usually consume 1 or more arguments per pass. # If it consumes 1 (eg. arg is an option that takes no arguments), # then after _process_arg() is done the situation is: # # largs = subset of [arg0, ..., arg(i)] # rargs = [arg(i+1), ..., arg(N-1)] # # If allow_interspersed_args is false, largs will always be # *empty* -- still a subset of [arg0, ..., arg(i-1)], but # not a very interesting subset! def _match_long_opt(self, opt, explicit_value, state): if opt not in self._long_opt: possibilities = [word for word in self._long_opt if word.startswith(opt)] raise NoSuchOption(opt, possibilities=possibilities) option = self._long_opt[opt] if option.takes_value: # At this point it's safe to modify rargs by injecting the # explicit value, because no exception is raised in this # branch. This means that the inserted value will be fully # consumed. if explicit_value is not None: state.rargs.insert(0, explicit_value) nargs = option.nargs if len(state.rargs) < nargs: _error_opt_args(nargs, opt) elif nargs == 1: value = state.rargs.pop(0) else: value = tuple(state.rargs[:nargs]) del state.rargs[:nargs] elif explicit_value is not None: raise BadOptionUsage('%s option does not take a value' % opt) else: value = None option.process(value, state) def _match_short_opt(self, arg, state): stop = False i = 1 prefix = arg[0] unknown_options = [] for ch in arg[1:]: opt = normalize_opt(prefix + ch, self.ctx) option = self._short_opt.get(opt) i += 1 if not option: if self.ignore_unknown_options: unknown_options.append(ch) continue raise NoSuchOption(opt) if option.takes_value: # Any characters left in arg? Pretend they're the # next arg, and stop consuming characters of arg. if i < len(arg): state.rargs.insert(0, arg[i:]) stop = True nargs = option.nargs if len(state.rargs) < nargs: _error_opt_args(nargs, opt) elif nargs == 1: value = state.rargs.pop(0) else: value = tuple(state.rargs[:nargs]) del state.rargs[:nargs] else: value = None option.process(value, state) if stop: break # If we got any unknown options we re-combinate the string of the # remaining options and re-attach the prefix, then report that # to the state as new larg. This way there is basic combinatorics # that can be achieved while still ignoring unknown arguments. if self.ignore_unknown_options and unknown_options: state.largs.append(prefix + ''.join(unknown_options)) def _process_opts(self, arg, state): explicit_value = None # Long option handling happens in two parts. The first part is # supporting explicitly attached values. In any case, we will try # to long match the option first. if '=' in arg: long_opt, explicit_value = arg.split('=', 1) else: long_opt = arg norm_long_opt = normalize_opt(long_opt, self.ctx) # At this point we will match the (assumed) long option through # the long option matching code. Note that this allows options # like "-foo" to be matched as long options. try: self._match_long_opt(norm_long_opt, explicit_value, state) except NoSuchOption: # At this point the long option matching failed, and we need # to try with short options. However there is a special rule # which says, that if we have a two character options prefix # (applies to "--foo" for instance), we do not dispatch to the # short option code and will instead raise the no option # error. if arg[:2] not in self._opt_prefixes: return self._match_short_opt(arg, state) if not self.ignore_unknown_options: raise state.largs.append(arg)
mit
abramovd/OdiZ
OdiZ/arithmetic/Zmax.py
1
2394
from __future__ import division import numpy as np import scipy as sp from scipy.optimize import minimize from .Rmax import Rmax from .convmaxR import convmaxR def Zmax(Z1A, Z1As, Z1B, Z1Bs, Z2A, Z2As, Z2B, Z2Bs): m1 = len(Z1As) m2 = len(Z2As) n1 = len(Z1Bs) n2 = len(Z2Bs) e = 0.0001 x01 = [1 for i in range(m1)] x02 = [1 for i in range(m2)] Aeq = tuple([(e, None) for i in range(m1)]) global C1 C1 = Z1A p1 = [] for i in range(n1): global d1 d1 = Z1Bs[i] fun1 = lambda x: (np.dot(C1, x) - d1) * (np.dot(C1, x) - d1) x = minimize(fun1, x01, method = 'SLSQP', bounds = Aeq, constraints = ({'type': 'eq', 'fun': lambda x: 1 - sum(x)})) p1.append(x.x) p1 = np.array(p1).transpose() C2 = Z2A p2 = [] for i in range(n2): global d2 d2 = Z1Bs[i] fun2 = lambda x: (np.dot(C2, x) - d2) * (np.dot(C2, x) - d2) x = minimize(fun2, x02, method = 'SLSQP', bounds = Aeq, constraints = ({'type': 'eq', 'fun': lambda x: 1 - sum(x)})) p2.append(x.x) p2 = np.matrix(p2).transpose() Z3A, Z3As = Rmax(Z1A,Z1As,Z2A,Z2As) u = p1 v = p2 ZconvM = [] for k1 in range(n1): for k2 in range(n2): ZconvM.append(convmaxR(u[:, k1], v[:, k2])) p3 = np.array(ZconvM).transpose() Z1p=p1 Z2p=p2 Z3p=p3 Z12B = np.zeros((n1, n2)) for k1 in range(n1): for k2 in range(n2): Z12B[k1, k2] = min(Z1B[k1], Z2B[k2]) Z3B = Z12B.max(axis = 0) Z12Bs = np.zeros((n1, n2)) for k1 in range(n1): for k2 in range(n2): Z12Bs[k1, k2] = np.dot(Z3A, convmaxR(u[:, k1], v[:, k2])) Z3Bs = Z12Bs.max(axis = 0) Z3Bs = np.unique(Z3Bs) return Z3A, Z3As, Z3B, Z3Bs, Z3p, Z1p, Z2p if __name__ == "__main__": Z1As=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; Z1A=[0, 0, 0, 0, 0.2, 0.4, 0.6, 0.8, 1, 0.5, 0] Z1Bs=[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] Z1B=[0, 0, 0, 0, 0.5, 1, 0.5, 0, 0, 0, 0] Z2As=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Z2A=[0, 0, 0.5, 1, 0.5, 0, 0, 0, 0, 0, 0] Z2Bs=[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] Z2B=[0, 0, 0, 0, 0, 0, 0, 0.5, 1, 0.5, 0] print(Zmax(Z1A, Z1As, Z1B, Z1Bs, Z2A, Z2As, Z2B, Z2Bs))
apache-2.0
christophlsa/odoo
addons/hr_holidays/wizard/hr_holidays_summary_employees.py
337
2152
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import time from openerp.osv import fields, osv class hr_holidays_summary_employee(osv.osv_memory): _name = 'hr.holidays.summary.employee' _description = 'HR Leaves Summary Report By Employee' _columns = { 'date_from': fields.date('From', required=True), 'emp': fields.many2many('hr.employee', 'summary_emp_rel', 'sum_id', 'emp_id', 'Employee(s)'), 'holiday_type': fields.selection([('Approved','Approved'),('Confirmed','Confirmed'),('both','Both Approved and Confirmed')], 'Select Leave Type', required=True) } _defaults = { 'date_from': lambda *a: time.strftime('%Y-%m-01'), 'holiday_type': 'Approved', } def print_report(self, cr, uid, ids, context=None): data = self.read(cr, uid, ids, context=context)[0] data['emp'] = context['active_ids'] datas = { 'ids': [], 'model': 'hr.employee', 'form': data } return { 'type': 'ir.actions.report.xml', 'report_name': 'holidays.summary', 'datas': datas, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
MSusik/invenio
invenio/celery/tasks.py
2
1202
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2013 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA from invenio.celery import celery @celery.task def invenio_version(): """ Task that will return the current running Invenio version """ from invenio.config import CFG_VERSION return CFG_VERSION @celery.task def invenio_db_test(num): """ Task will execute a simple query in the database""" from invenio.ext.sqlalchemy import db return db.engine.execute("select %s" % int(num)).scalar()
gpl-2.0
baojianzhou/DLReadingGroup
keras/keras/layers/wrappers.py
3
12210
# -*- coding: utf-8 -*- from __future__ import absolute_import import copy import inspect from ..engine import Layer from ..engine import InputSpec from .. import backend as K class Wrapper(Layer): """Abstract wrapper base class. Wrappers take another layer and augment it in various ways. Do not use this class as a layer, it is only an abstract base class. Two usable wrappers are the `TimeDistributed` and `Bidirectional` wrappers. # Arguments layer: The layer to be wrapped. """ def __init__(self, layer, **kwargs): self.layer = layer super(Wrapper, self).__init__(**kwargs) def build(self, input_shape=None): self.built = True @property def activity_regularizer(self): if hasattr(self.layer, 'activity_regularizer'): return self.layer.activity_regularizer else: return None @property def trainable_weights(self): return self.layer.trainable_weights @property def non_trainable_weights(self): return self.layer.non_trainable_weights @property def updates(self): if hasattr(self.layer, 'updates'): return self.layer.updates return [] def get_updates_for(self, inputs=None): if inputs is None: updates = self.layer.get_updates_for(None) return updates + super(Wrapper, self).get_updates_for(None) return super(Wrapper, self).get_updates_for(inputs) @property def losses(self): if hasattr(self.layer, 'losses'): return self.layer.losses return [] def get_losses_for(self, inputs=None): if inputs is None: losses = self.layer.get_losses_for(None) return losses + super(Wrapper, self).get_losses_for(None) return super(Wrapper, self).get_losses_for(inputs) @property def constraints(self): return self.layer.constraints def get_weights(self): return self.layer.get_weights() def set_weights(self, weights): self.layer.set_weights(weights) def get_config(self): config = {'layer': {'class_name': self.layer.__class__.__name__, 'config': self.layer.get_config()}} base_config = super(Wrapper, self).get_config() return dict(list(base_config.items()) + list(config.items())) @classmethod def from_config(cls, config, custom_objects=None): from . import deserialize as deserialize_layer layer = deserialize_layer(config.pop('layer'), custom_objects=custom_objects) return cls(layer, **config) class TimeDistributed(Wrapper): """This wrapper allows to apply a layer to every temporal slice of an input. The input should be at least 3D, and the dimension of index one will be considered to be the temporal dimension. Consider a batch of 32 samples, where each sample is a sequence of 10 vectors of 16 dimensions. The batch input shape of the layer is then `(32, 10, 16)`, and the `input_shape`, not including the samples dimension, is `(10, 16)`. You can then use `TimeDistributed` to apply a `Dense` layer to each of the 10 timesteps, independently: ```python # as the first layer in a model model = Sequential() model.add(TimeDistributed(Dense(8), input_shape=(10, 16))) # now model.output_shape == (None, 10, 8) ``` The output will then have shape `(32, 10, 8)`. In subsequent layers, there is no need for the `input_shape`: ```python model.add(TimeDistributed(Dense(32))) # now model.output_shape == (None, 10, 32) ``` The output will then have shape `(32, 10, 32)`. `TimeDistributed` can be used with arbitrary layers, not just `Dense`, for instance with a `Conv2D` layer: ```python model = Sequential() model.add(TimeDistributed(Conv2D(64, (3, 3)), input_shape=(10, 299, 299, 3))) ``` # Arguments layer: a layer instance. """ def __init__(self, layer, **kwargs): super(TimeDistributed, self).__init__(layer, **kwargs) self.supports_masking = True def build(self, input_shape): assert len(input_shape) >= 3 self.input_spec = InputSpec(shape=input_shape) child_input_shape = (input_shape[0],) + input_shape[2:] if not self.layer.built: self.layer.build(child_input_shape) self.layer.built = True super(TimeDistributed, self).build() def compute_output_shape(self, input_shape): child_input_shape = (input_shape[0],) + input_shape[2:] child_output_shape = self.layer.compute_output_shape(child_input_shape) timesteps = input_shape[1] return (child_output_shape[0], timesteps) + child_output_shape[1:] def call(self, inputs, mask=None): input_shape = K.int_shape(inputs) if input_shape[0]: # batch size matters, use rnn-based implementation def step(x, _): output = self.layer.call(x) return output, [] _, outputs, _ = K.rnn(step, inputs, initial_states=[], input_length=input_shape[1], unroll=False) y = outputs else: # No batch size specified, therefore the layer will be able # to process batches of any size. # We can go with reshape-based implementation for performance. input_length = input_shape[1] if not input_length: input_length = K.shape(inputs)[1] # Shape: (num_samples * timesteps, ...) inputs = K.reshape(inputs, (-1,) + input_shape[2:]) y = self.layer.call(inputs) # (num_samples * timesteps, ...) # Shape: (num_samples, timesteps, ...) output_shape = self.compute_output_shape(input_shape) y = K.reshape(y, (-1, input_length) + output_shape[2:]) # Apply activity regularizer if any: if (hasattr(self.layer, 'activity_regularizer') and self.layer.activity_regularizer is not None): regularization_loss = self.layer.activity_regularizer(y) self.add_loss(regularization_loss, inputs) return y class Bidirectional(Wrapper): """Bidirectional wrapper for RNNs. # Arguments layer: `Recurrent` instance. merge_mode: Mode by which outputs of the forward and backward RNNs will be combined. One of {'sum', 'mul', 'concat', 'ave', None}. If None, the outputs will not be combined, they will be returned as a list. # Raises ValueError: In case of invalid `merge_mode` argument. # Examples ```python model = Sequential() model.add(Bidirectional(LSTM(10, return_sequences=True), input_shape=(5, 10))) model.add(Bidirectional(LSTM(10))) model.add(Dense(5)) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='rmsprop') ``` """ def __init__(self, layer, merge_mode='concat', weights=None, **kwargs): super(Bidirectional, self).__init__(layer, **kwargs) if merge_mode not in ['sum', 'mul', 'ave', 'concat', None]: raise ValueError('Invalid merge mode. ' 'Merge mode should be one of ' '{"sum", "mul", "ave", "concat", None}') self.forward_layer = copy.copy(layer) config = layer.get_config() config['go_backwards'] = not config['go_backwards'] self.backward_layer = layer.__class__.from_config(config) self.forward_layer.name = 'forward_' + self.forward_layer.name self.backward_layer.name = 'backward_' + self.backward_layer.name self.merge_mode = merge_mode if weights: nw = len(weights) self.forward_layer.initial_weights = weights[:nw // 2] self.backward_layer.initial_weights = weights[nw // 2:] self.stateful = layer.stateful self.return_sequences = layer.return_sequences self.supports_masking = True def get_weights(self): return self.forward_layer.get_weights() + self.backward_layer.get_weights() def set_weights(self, weights): nw = len(weights) self.forward_layer.set_weights(weights[:nw // 2]) self.backward_layer.set_weights(weights[nw // 2:]) def compute_output_shape(self, input_shape): if self.merge_mode in ['sum', 'ave', 'mul']: return self.forward_layer.compute_output_shape(input_shape) elif self.merge_mode == 'concat': shape = list(self.forward_layer.compute_output_shape(input_shape)) shape[-1] *= 2 return tuple(shape) elif self.merge_mode is None: return [self.forward_layer.compute_output_shape(input_shape)] * 2 def call(self, inputs, training=None, mask=None): kwargs = {} func_args = inspect.getargspec(self.layer.call).args if 'training' in func_args: kwargs['training'] = training if 'mask' in func_args: kwargs['mask'] = mask y = self.forward_layer.call(inputs, **kwargs) y_rev = self.backward_layer.call(inputs, **kwargs) if self.return_sequences: y_rev = K.reverse(y_rev, 1) if self.merge_mode == 'concat': output = K.concatenate([y, y_rev]) elif self.merge_mode == 'sum': output = y + y_rev elif self.merge_mode == 'ave': output = (y + y_rev) / 2 elif self.merge_mode == 'mul': output = y * y_rev elif self.merge_mode is None: output = [y, y_rev] # Properly set learning phase if 0 < self.layer.dropout + self.layer.recurrent_dropout: if self.merge_mode is None: for out in output: out._uses_learning_phase = True else: output._uses_learning_phase = True return output def reset_states(self): self.forward_layer.reset_states() self.backward_layer.reset_states() def build(self, input_shape): with K.name_scope(self.forward_layer.name): self.forward_layer.build(input_shape) with K.name_scope(self.backward_layer.name): self.backward_layer.build(input_shape) self.built = True def compute_mask(self, inputs, mask): if self.return_sequences: if not self.merge_mode: return [mask, mask] else: return mask else: return None @property def trainable_weights(self): if hasattr(self.forward_layer, 'trainable_weights'): return (self.forward_layer.trainable_weights + self.backward_layer.trainable_weights) return [] @property def non_trainable_weights(self): if hasattr(self.forward_layer, 'non_trainable_weights'): return (self.forward_layer.non_trainable_weights + self.backward_layer.non_trainable_weights) return [] @property def updates(self): if hasattr(self.forward_layer, 'updates'): return self.forward_layer.updates + self.backward_layer.updates return [] @property def losses(self): if hasattr(self.forward_layer, 'losses'): return self.forward_layer.losses + self.backward_layer.losses return [] @property def constraints(self): constraints = {} if hasattr(self.forward_layer, 'constraints'): constraints.update(self.forward_layer.constraints) constraints.update(self.backward_layer.constraints) return constraints def get_config(self): config = {'merge_mode': self.merge_mode} base_config = super(Bidirectional, self).get_config() return dict(list(base_config.items()) + list(config.items()))
apache-2.0
pestefo/viz-youtube
paralell_coordinates/data_processer.py
1
3038
# Processes from: # id, views, comments, related_video_1, ... , related_video_20 # to: # views(id), comments(id), views(related_video_1), comments(related_video_1) # ... # views(id), comments(id), views(related_video_20), comments(related_video_20) import csv import copy global dict1File global dict2File def resetFiles(): dict1File.seek(0) dict2File.seek(0) def get_video_for_id(id,dictionary): resetFiles() try: while True : current_video = dictionary.next() if current_video["id"] == id: return current_video except StopIteration : return {} def get_related_videos(video,dictionaries): related_ids = [video["related_1"],video["related_2"],video["related_3"],video["related_4"],video["related_5"],video["related_6"],video["related_7"],video["related_8"],video["related_9"],video["related_10"],video["related_11"],video["related_12"],video["related_13"],video["related_14"],video["related_15"],video["related_16"],video["related_17"],video["related_18"],video["related_19"],video["related_20"]] #related_ids = [video["related_1"],video["related_2"],video["related_3"]] related_videos = [] for related_id in related_ids: video = get_video_for_id(related_id,dictionaries[1]) if not video: video = get_video_for_id(related_id,dictionaries[0]) related_videos.append(video) return related_videos if __name__ == '__main__': path_to_dir = "../data/datasets/0403/" dict1File1 = open(path_to_dir+"0-2.txt", "rb") dict1File = open(path_to_dir+"0.txt", "rb") dict2File = open(path_to_dir+"1.txt", "rb") outputFile = open("data.csv", "w") # Dictionaries dict1 = csv.DictReader(dict1File, delimiter="\t") dict2 = csv.DictReader(dict2File, delimiter="\t") videos = csv.DictReader(dict1File1, delimiter="\t") counter = 1 outputFile.write("related_comments,comments,views,related_views\n") # try: for video in videos: related_videos = get_related_videos(video,[dict1,dict2]) for related_video in related_videos: if related_video != {}: try: line = related_video['comments']+','+video['comments']+','+video['views']+','+related_video['views']+'\n' outputFile.write(line) except TypeError: print related_video # print related_video['comments']+'\t'+video['comments']+'\t'+video['views']+'\t'+related_video['views'] counter += 1 print str(counter)+"/"+"326" # while True : # video = videos.next() # print video # related_videos = get_related_videos(video,[dict1,dict2]) # # # for related_video in related_videos: # if related_video != {}: # print related_video['comments']+'\t'+video['comments']+'\t'+video['views']+'\t'+related_video['views'] # counter -= 1 # # if counter == 0: # break #
mit
sethp-jive/mitmproxy
libmproxy/console/__init__.py
15
21639
from __future__ import absolute_import import mailcap import mimetypes import tempfile import os import os.path import shlex import signal import stat import subprocess import sys import traceback import urwid import weakref from .. import controller, flow, script, contentviews from . import flowlist, flowview, help, window, signals, options from . import grideditor, palettes, statusbar, palettepicker EVENTLOG_SIZE = 500 class ConsoleState(flow.State): def __init__(self): flow.State.__init__(self) self.focus = None self.follow_focus = None self.default_body_view = contentviews.get("Auto") self.flowsettings = weakref.WeakKeyDictionary() self.last_search = None def __setattr__(self, name, value): self.__dict__[name] = value signals.update_settings.send(self) def add_flow_setting(self, flow, key, value): d = self.flowsettings.setdefault(flow, {}) d[key] = value def get_flow_setting(self, flow, key, default=None): d = self.flowsettings.get(flow, {}) return d.get(key, default) def add_flow(self, f): super(ConsoleState, self).add_flow(f) if self.focus is None: self.set_focus(0) elif self.follow_focus: self.set_focus(len(self.view) - 1) self.set_flow_marked(f, False) return f def update_flow(self, f): super(ConsoleState, self).update_flow(f) if self.focus is None: self.set_focus(0) return f def set_limit(self, limit): ret = flow.State.set_limit(self, limit) self.set_focus(self.focus) return ret def get_focus(self): if not self.view or self.focus is None: return None, None return self.view[self.focus], self.focus def set_focus(self, idx): if self.view: if idx >= len(self.view): idx = len(self.view) - 1 elif idx < 0: idx = 0 self.focus = idx else: self.focus = None def set_focus_flow(self, f): self.set_focus(self.view.index(f)) def get_from_pos(self, pos): if len(self.view) <= pos or pos < 0: return None, None return self.view[pos], pos def get_next(self, pos): return self.get_from_pos(pos + 1) def get_prev(self, pos): return self.get_from_pos(pos - 1) def delete_flow(self, f): if f in self.view and self.view.index(f) <= self.focus: self.focus -= 1 if self.focus < 0: self.focus = None ret = flow.State.delete_flow(self, f) self.set_focus(self.focus) return ret def clear(self): marked_flows = [] for f in self.flows: if self.flow_marked(f): marked_flows.append(f) super(ConsoleState, self).clear() for f in marked_flows: self.add_flow(f) self.set_flow_marked(f, True) if len(self.flows.views) == 0: self.focus = None else: self.focus = 0 self.set_focus(self.focus) def flow_marked(self, flow): return self.get_flow_setting(flow, "marked", False) def set_flow_marked(self, flow, marked): self.add_flow_setting(flow, "marked", marked) class Options(object): attributes = [ "app", "app_domain", "app_ip", "anticache", "anticomp", "client_replay", "eventlog", "keepserving", "kill", "intercept", "limit", "no_server", "refresh_server_playback", "rfile", "scripts", "showhost", "replacements", "rheaders", "setheaders", "server_replay", "stickycookie", "stickyauth", "stream_large_bodies", "verbosity", "wfile", "nopop", "palette", "palette_transparent", "no_mouse" ] def __init__(self, **kwargs): for k, v in kwargs.items(): setattr(self, k, v) for i in self.attributes: if not hasattr(self, i): setattr(self, i, None) class ConsoleMaster(flow.FlowMaster): palette = [] def __init__(self, server, options): flow.FlowMaster.__init__(self, server, ConsoleState()) self.stream_path = None self.options = options for i in options.replacements: self.replacehooks.add(*i) for i in options.setheaders: self.setheaders.add(*i) r = self.set_intercept(options.intercept) if r: print >> sys.stderr, "Intercept error:", r sys.exit(1) if options.limit: self.set_limit(options.limit) r = self.set_stickycookie(options.stickycookie) if r: print >> sys.stderr, "Sticky cookies error:", r sys.exit(1) r = self.set_stickyauth(options.stickyauth) if r: print >> sys.stderr, "Sticky auth error:", r sys.exit(1) self.set_stream_large_bodies(options.stream_large_bodies) self.refresh_server_playback = options.refresh_server_playback self.anticache = options.anticache self.anticomp = options.anticomp self.killextra = options.kill self.rheaders = options.rheaders self.nopop = options.nopop self.showhost = options.showhost self.palette = options.palette self.palette_transparent = options.palette_transparent self.eventlog = options.eventlog self.eventlist = urwid.SimpleListWalker([]) if options.client_replay: self.client_playback_path(options.client_replay) if options.server_replay: self.server_playback_path(options.server_replay) if options.scripts: for i in options.scripts: err = self.load_script(i) if err: print >> sys.stderr, "Script load error:", err sys.exit(1) if options.outfile: err = self.start_stream_to_path( options.outfile[0], options.outfile[1] ) if err: print >> sys.stderr, "Stream file error:", err sys.exit(1) self.view_stack = [] if options.app: self.start_app(self.options.app_host, self.options.app_port) signals.call_in.connect(self.sig_call_in) signals.pop_view_state.connect(self.sig_pop_view_state) signals.push_view_state.connect(self.sig_push_view_state) signals.sig_add_event.connect(self.sig_add_event) def __setattr__(self, name, value): self.__dict__[name] = value signals.update_settings.send(self) def sig_add_event(self, sender, e, level): needed = dict(error=0, info=1, debug=2).get(level, 1) if self.options.verbosity < needed: return if level == "error": e = urwid.Text(("error", str(e))) else: e = urwid.Text(str(e)) self.eventlist.append(e) if len(self.eventlist) > EVENTLOG_SIZE: self.eventlist.pop(0) self.eventlist.set_focus(len(self.eventlist) - 1) def add_event(self, e, level): signals.add_event(e, level) def sig_call_in(self, sender, seconds, callback, args=()): def cb(*_): return callback(*args) self.loop.set_alarm_in(seconds, cb) def sig_pop_view_state(self, sender): if len(self.view_stack) > 1: self.view_stack.pop() self.loop.widget = self.view_stack[-1] else: signals.status_prompt_onekey.send( self, prompt = "Quit", keys = ( ("yes", "y"), ("no", "n"), ), callback = self.quit, ) def sig_push_view_state(self, sender, window): self.view_stack.append(window) self.loop.widget = window self.loop.draw_screen() def start_stream_to_path(self, path, mode="wb"): path = os.path.expanduser(path) try: f = file(path, mode) self.start_stream(f, None) except IOError as v: return str(v) self.stream_path = path def _run_script_method(self, method, s, f): status, val = s.run(method, f) if val: if status: signals.add_event("Method %s return: %s" % (method, val), "debug") else: signals.add_event( "Method %s error: %s" % (method, val[1]), "error") def run_script_once(self, command, f): if not command: return signals.add_event("Running script on flow: %s" % command, "debug") try: s = script.Script(command, self) except script.ScriptError as v: signals.status_message.send( message = "Error loading script." ) signals.add_event("Error loading script:\n%s" % v.args[0], "error") return if f.request: self._run_script_method("request", s, f) if f.response: self._run_script_method("response", s, f) if f.error: self._run_script_method("error", s, f) s.unload() signals.flow_change.send(self, flow = f) def set_script(self, command): if not command: return ret = self.load_script(command) if ret: signals.status_message.send(message=ret) def toggle_eventlog(self): self.eventlog = not self.eventlog signals.pop_view_state.send(self) self.view_flowlist() def _readflows(self, path): """ Utitility function that reads a list of flows or prints an error to the UI if that fails. Returns - None, if there was an error. - a list of flows, otherwise. """ try: return flow.read_flows_from_paths(path) except flow.FlowReadError as e: signals.status_message.send(message=e.strerror) def client_playback_path(self, path): if not isinstance(path, list): path = [path] flows = self._readflows(path) if flows: self.start_client_playback(flows, False) def server_playback_path(self, path): if not isinstance(path, list): path = [path] flows = self._readflows(path) if flows: self.start_server_playback( flows, self.killextra, self.rheaders, False, self.nopop, self.options.replay_ignore_params, self.options.replay_ignore_content, self.options.replay_ignore_payload_params, self.options.replay_ignore_host ) def spawn_editor(self, data): fd, name = tempfile.mkstemp('', "mproxy") os.write(fd, data) os.close(fd) c = os.environ.get("EDITOR") # if no EDITOR is set, assume 'vi' if not c: c = "vi" cmd = shlex.split(c) cmd.append(name) self.ui.stop() try: subprocess.call(cmd) except: signals.status_message.send( message = "Can't start editor: %s" % " ".join(c) ) else: data = open(name, "rb").read() self.ui.start() os.unlink(name) return data def spawn_external_viewer(self, data, contenttype): if contenttype: contenttype = contenttype.split(";")[0] ext = mimetypes.guess_extension(contenttype) or "" else: ext = "" fd, name = tempfile.mkstemp(ext, "mproxy") os.write(fd, data) os.close(fd) # read-only to remind the user that this is a view function os.chmod(name, stat.S_IREAD) cmd = None shell = False if contenttype: c = mailcap.getcaps() cmd, _ = mailcap.findmatch(c, contenttype, filename=name) if cmd: shell = True if not cmd: # hm which one should get priority? c = os.environ.get("PAGER") or os.environ.get("EDITOR") if not c: c = "less" cmd = shlex.split(c) cmd.append(name) self.ui.stop() try: subprocess.call(cmd, shell=shell) except: signals.status_message.send( message="Can't start external viewer: %s" % " ".join(c) ) self.ui.start() os.unlink(name) def set_palette(self, name): self.palette = name self.ui.register_palette( palettes.palettes[name].palette(self.palette_transparent) ) self.ui.clear() def ticker(self, *userdata): changed = self.tick(self.masterq, timeout=0) if changed: self.loop.draw_screen() signals.update_settings.send() self.loop.set_alarm_in(0.01, self.ticker) def run(self): self.ui = urwid.raw_display.Screen() self.ui.set_terminal_properties(256) self.set_palette(self.palette) self.loop = urwid.MainLoop( urwid.SolidFill("x"), screen = self.ui, handle_mouse = not self.options.no_mouse, ) self.server.start_slave( controller.Slave, controller.Channel(self.masterq, self.should_exit) ) if self.options.rfile: ret = self.load_flows_path(self.options.rfile) if ret and self.state.flow_count(): signals.add_event( "File truncated or corrupted. " "Loaded as many flows as possible.", "error" ) elif ret and not self.state.flow_count(): self.shutdown() print >> sys.stderr, "Could not load file:", ret sys.exit(1) self.loop.set_alarm_in(0.01, self.ticker) # It's not clear why we need to handle this explicitly - without this, # mitmproxy hangs on keyboard interrupt. Remove if we ever figure it # out. def exit(s, f): raise urwid.ExitMainLoop signal.signal(signal.SIGINT, exit) self.loop.set_alarm_in( 0.0001, lambda *args: self.view_flowlist() ) try: self.loop.run() except Exception: self.loop.stop() sys.stdout.flush() print >> sys.stderr, traceback.format_exc() print >> sys.stderr, "mitmproxy has crashed!" print >> sys.stderr, "Please lodge a bug report at:" print >> sys.stderr, "\thttps://github.com/mitmproxy/mitmproxy" print >> sys.stderr, "Shutting down..." sys.stderr.flush() self.shutdown() def view_help(self, helpctx): signals.push_view_state.send( self, window = window.Window( self, help.HelpView(helpctx), None, statusbar.StatusBar(self, help.footer), None ) ) def view_options(self): for i in self.view_stack: if isinstance(i["body"], options.Options): return signals.push_view_state.send( self, window = window.Window( self, options.Options(self), None, statusbar.StatusBar(self, options.footer), options.help_context, ) ) def view_palette_picker(self): signals.push_view_state.send( self, window = window.Window( self, palettepicker.PalettePicker(self), None, statusbar.StatusBar(self, palettepicker.footer), palettepicker.help_context, ) ) def view_grideditor(self, ge): signals.push_view_state.send( self, window = window.Window( self, ge, None, statusbar.StatusBar(self, grideditor.FOOTER), ge.make_help() ) ) def view_flowlist(self): if self.ui.started: self.ui.clear() if self.state.follow_focus: self.state.set_focus(self.state.flow_count()) if self.eventlog: body = flowlist.BodyPile(self) else: body = flowlist.FlowListBox(self) signals.push_view_state.send( self, window = window.Window( self, body, None, statusbar.StatusBar(self, flowlist.footer), flowlist.help_context ) ) def view_flow(self, flow, tab_offset=0): self.state.set_focus_flow(flow) signals.push_view_state.send( self, window = window.Window( self, flowview.FlowView(self, self.state, flow, tab_offset), flowview.FlowViewHeader(self, flow), statusbar.StatusBar(self, flowview.footer), flowview.help_context ) ) def _write_flows(self, path, flows): if not path: return path = os.path.expanduser(path) try: f = file(path, "wb") fw = flow.FlowWriter(f) for i in flows: fw.add(i) f.close() except IOError as v: signals.status_message.send(message=v.strerror) def save_one_flow(self, path, flow): return self._write_flows(path, [flow]) def save_flows(self, path): return self._write_flows(path, self.state.view) def save_marked_flows(self, path): marked_flows = [] for f in self.state.view: if self.state.flow_marked(f): marked_flows.append(f) return self._write_flows(path, marked_flows) def load_flows_callback(self, path): if not path: return ret = self.load_flows_path(path) return ret or "Flows loaded from %s" % path def load_flows_path(self, path): reterr = None try: flow.FlowMaster.load_flows_file(self, path) except flow.FlowReadError as v: reterr = str(v) signals.flowlist_change.send(self) return reterr def accept_all(self): self.state.accept_all(self) def set_limit(self, txt): v = self.state.set_limit(txt) signals.flowlist_change.send(self) return v def set_intercept(self, txt): return self.state.set_intercept(txt) def change_default_display_mode(self, t): v = contentviews.get_by_shortcut(t) self.state.default_body_view = v self.refresh_focus() def edit_scripts(self, scripts): commands = [x[0] for x in scripts] # remove outer array if commands == [s.command for s in self.scripts]: return self.unload_scripts() for command in commands: self.load_script(command) signals.update_settings.send(self) def stop_client_playback_prompt(self, a): if a != "n": self.stop_client_playback() def stop_server_playback_prompt(self, a): if a != "n": self.stop_server_playback() def quit(self, a): if a != "n": raise urwid.ExitMainLoop def shutdown(self): self.state.killall(self) flow.FlowMaster.shutdown(self) def clear_flows(self): self.state.clear() signals.flowlist_change.send(self) def toggle_follow_flows(self): # toggle flow follow self.state.follow_focus = not self.state.follow_focus # jump to most recent flow if follow is now on if self.state.follow_focus: self.state.set_focus(self.state.flow_count()) signals.flowlist_change.send(self) def delete_flow(self, f): self.state.delete_flow(f) signals.flowlist_change.send(self) def refresh_focus(self): if self.state.view: signals.flow_change.send( self, flow = self.state.view[self.state.focus] ) def process_flow(self, f): if self.state.intercept and f.match( self.state.intercept) and not f.request.is_replay: f.intercept(self) else: f.reply() signals.flowlist_change.send(self) signals.flow_change.send(self, flow = f) def clear_events(self): self.eventlist[:] = [] # Handlers def handle_error(self, f): f = flow.FlowMaster.handle_error(self, f) if f: self.process_flow(f) return f def handle_request(self, f): f = flow.FlowMaster.handle_request(self, f) if f: self.process_flow(f) return f def handle_response(self, f): f = flow.FlowMaster.handle_response(self, f) if f: self.process_flow(f) return f
mit
luiseduardohdbackup/odoo
openerp/addons/base/ir/ir_needaction.py
455
2704
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2009-Today OpenERP SA (<http://www.openerp.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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.osv import osv class ir_needaction_mixin(osv.AbstractModel): """Mixin class for objects using the need action feature. Need action feature can be used by models that have to be able to signal that an action is required on a particular record. If in the business logic an action must be performed by somebody, for instance validation by a manager, this mechanism allows to set a list of users asked to perform an action. Models using the 'need_action' feature should override the ``_needaction_domain_get`` method. This method returns a domain to filter records requiring an action for a specific user. This class also offers several global services: - ``_needaction_count``: returns the number of actions uid has to perform """ _name = 'ir.needaction_mixin' _needaction = True #------------------------------------------------------ # Addons API #------------------------------------------------------ def _needaction_domain_get(self, cr, uid, context=None): """ Returns the domain to filter records that require an action :return: domain or False is no action """ return False #------------------------------------------------------ # "Need action" API #------------------------------------------------------ def _needaction_count(self, cr, uid, domain=None, context=None): """ Get the number of actions uid has to perform. """ dom = self._needaction_domain_get(cr, uid, context=context) if not dom: return 0 res = self.search(cr, uid, (domain or []) + dom, limit=100, order='id DESC', context=context) return len(res)
agpl-3.0
ehashman/oh-mainline
vendor/packages/Django/tests/regressiontests/utils/functional.py
93
1084
from django.utils import unittest from django.utils.functional import lazy, lazy_property class FunctionalTestCase(unittest.TestCase): def test_lazy(self): t = lazy(lambda: tuple(range(3)), list, tuple) for a, b in zip(t(), range(3)): self.assertEqual(a, b) def test_lazy_base_class(self): """Test that lazy also finds base class methods in the proxy object""" class Base(object): def base_method(self): pass class Klazz(Base): pass t = lazy(lambda: Klazz(), Klazz)() self.assertTrue('base_method' in dir(t)) def test_lazy_property(self): class A(object): def _get_do(self): raise NotImplementedError def _set_do(self, value): raise NotImplementedError do = lazy_property(_get_do, _set_do) class B(A): def _get_do(self): return "DO IT" self.assertRaises(NotImplementedError, lambda: A().do) self.assertEqual(B().do, 'DO IT')
agpl-3.0
2014cdbg6/cdbg6
wsgi/static/Brython2.1.0-20140419-113919/Lib/unittest/loader.py
739
13883
"""Loading unittests.""" import os import re import sys import traceback import types import functools from fnmatch import fnmatch from . import case, suite, util __unittest = True # what about .pyc or .pyo (etc) # we would need to avoid loading the same tests multiple times # from '.py', '.pyc' *and* '.pyo' VALID_MODULE_NAME = re.compile(r'[_a-z]\w*\.py$', re.IGNORECASE) def _make_failed_import_test(name, suiteClass): message = 'Failed to import test module: %s\n%s' % (name, traceback.format_exc()) return _make_failed_test('ModuleImportFailure', name, ImportError(message), suiteClass) def _make_failed_load_tests(name, exception, suiteClass): return _make_failed_test('LoadTestsFailure', name, exception, suiteClass) def _make_failed_test(classname, methodname, exception, suiteClass): def testFailure(self): raise exception attrs = {methodname: testFailure} TestClass = type(classname, (case.TestCase,), attrs) return suiteClass((TestClass(methodname),)) def _jython_aware_splitext(path): if path.lower().endswith('$py.class'): return path[:-9] return os.path.splitext(path)[0] class TestLoader(object): """ This class is responsible for loading tests according to various criteria and returning them wrapped in a TestSuite """ testMethodPrefix = 'test' sortTestMethodsUsing = staticmethod(util.three_way_cmp) suiteClass = suite.TestSuite _top_level_dir = None def loadTestsFromTestCase(self, testCaseClass): """Return a suite of all tests cases contained in testCaseClass""" if issubclass(testCaseClass, suite.TestSuite): raise TypeError("Test cases should not be derived from TestSuite." \ " Maybe you meant to derive from TestCase?") testCaseNames = self.getTestCaseNames(testCaseClass) if not testCaseNames and hasattr(testCaseClass, 'runTest'): testCaseNames = ['runTest'] loaded_suite = self.suiteClass(map(testCaseClass, testCaseNames)) return loaded_suite def loadTestsFromModule(self, module, use_load_tests=True): """Return a suite of all tests cases contained in the given module""" tests = [] for name in dir(module): obj = getattr(module, name) if isinstance(obj, type) and issubclass(obj, case.TestCase): tests.append(self.loadTestsFromTestCase(obj)) load_tests = getattr(module, 'load_tests', None) tests = self.suiteClass(tests) if use_load_tests and load_tests is not None: try: return load_tests(self, tests, None) except Exception as e: return _make_failed_load_tests(module.__name__, e, self.suiteClass) return tests def loadTestsFromName(self, name, module=None): """Return a suite of all tests cases given a string specifier. The name may resolve either to a module, a test case class, a test method within a test case class, or a callable object which returns a TestCase or TestSuite instance. The method optionally resolves the names relative to a given module. """ parts = name.split('.') if module is None: parts_copy = parts[:] while parts_copy: try: module = __import__('.'.join(parts_copy)) break except ImportError: del parts_copy[-1] if not parts_copy: raise parts = parts[1:] obj = module for part in parts: parent, obj = obj, getattr(obj, part) if isinstance(obj, types.ModuleType): return self.loadTestsFromModule(obj) elif isinstance(obj, type) and issubclass(obj, case.TestCase): return self.loadTestsFromTestCase(obj) elif (isinstance(obj, types.FunctionType) and isinstance(parent, type) and issubclass(parent, case.TestCase)): name = parts[-1] inst = parent(name) # static methods follow a different path if not isinstance(getattr(inst, name), types.FunctionType): return self.suiteClass([inst]) elif isinstance(obj, suite.TestSuite): return obj if callable(obj): test = obj() if isinstance(test, suite.TestSuite): return test elif isinstance(test, case.TestCase): return self.suiteClass([test]) else: raise TypeError("calling %s returned %s, not a test" % (obj, test)) else: raise TypeError("don't know how to make test from: %s" % obj) def loadTestsFromNames(self, names, module=None): """Return a suite of all tests cases found using the given sequence of string specifiers. See 'loadTestsFromName()'. """ suites = [self.loadTestsFromName(name, module) for name in names] return self.suiteClass(suites) def getTestCaseNames(self, testCaseClass): """Return a sorted sequence of method names found within testCaseClass """ def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix): return attrname.startswith(prefix) and \ callable(getattr(testCaseClass, attrname)) testFnNames = list(filter(isTestMethod, dir(testCaseClass))) if self.sortTestMethodsUsing: testFnNames.sort(key=functools.cmp_to_key(self.sortTestMethodsUsing)) return testFnNames def discover(self, start_dir, pattern='test*.py', top_level_dir=None): """Find and return all test modules from the specified start directory, recursing into subdirectories to find them and return all tests found within them. Only test files that match the pattern will be loaded. (Using shell style pattern matching.) All test modules must be importable from the top level of the project. If the start directory is not the top level directory then the top level directory must be specified separately. If a test package name (directory with '__init__.py') matches the pattern then the package will be checked for a 'load_tests' function. If this exists then it will be called with loader, tests, pattern. If load_tests exists then discovery does *not* recurse into the package, load_tests is responsible for loading all tests in the package. The pattern is deliberately not stored as a loader attribute so that packages can continue discovery themselves. top_level_dir is stored so load_tests does not need to pass this argument in to loader.discover(). """ set_implicit_top = False if top_level_dir is None and self._top_level_dir is not None: # make top_level_dir optional if called from load_tests in a package top_level_dir = self._top_level_dir elif top_level_dir is None: set_implicit_top = True top_level_dir = start_dir top_level_dir = os.path.abspath(top_level_dir) if not top_level_dir in sys.path: # all test modules must be importable from the top level directory # should we *unconditionally* put the start directory in first # in sys.path to minimise likelihood of conflicts between installed # modules and development versions? sys.path.insert(0, top_level_dir) self._top_level_dir = top_level_dir is_not_importable = False if os.path.isdir(os.path.abspath(start_dir)): start_dir = os.path.abspath(start_dir) if start_dir != top_level_dir: is_not_importable = not os.path.isfile(os.path.join(start_dir, '__init__.py')) else: # support for discovery from dotted module names try: __import__(start_dir) except ImportError: is_not_importable = True else: the_module = sys.modules[start_dir] top_part = start_dir.split('.')[0] start_dir = os.path.abspath(os.path.dirname((the_module.__file__))) if set_implicit_top: self._top_level_dir = self._get_directory_containing_module(top_part) sys.path.remove(top_level_dir) if is_not_importable: raise ImportError('Start directory is not importable: %r' % start_dir) tests = list(self._find_tests(start_dir, pattern)) return self.suiteClass(tests) def _get_directory_containing_module(self, module_name): module = sys.modules[module_name] full_path = os.path.abspath(module.__file__) if os.path.basename(full_path).lower().startswith('__init__.py'): return os.path.dirname(os.path.dirname(full_path)) else: # here we have been given a module rather than a package - so # all we can do is search the *same* directory the module is in # should an exception be raised instead return os.path.dirname(full_path) def _get_name_from_path(self, path): path = _jython_aware_splitext(os.path.normpath(path)) _relpath = os.path.relpath(path, self._top_level_dir) assert not os.path.isabs(_relpath), "Path must be within the project" assert not _relpath.startswith('..'), "Path must be within the project" name = _relpath.replace(os.path.sep, '.') return name def _get_module_from_name(self, name): __import__(name) return sys.modules[name] def _match_path(self, path, full_path, pattern): # override this method to use alternative matching strategy return fnmatch(path, pattern) def _find_tests(self, start_dir, pattern): """Used by discovery. Yields test suites it loads.""" paths = os.listdir(start_dir) for path in paths: full_path = os.path.join(start_dir, path) if os.path.isfile(full_path): if not VALID_MODULE_NAME.match(path): # valid Python identifiers only continue if not self._match_path(path, full_path, pattern): continue # if the test file matches, load it name = self._get_name_from_path(full_path) try: module = self._get_module_from_name(name) except: yield _make_failed_import_test(name, self.suiteClass) else: mod_file = os.path.abspath(getattr(module, '__file__', full_path)) realpath = _jython_aware_splitext(os.path.realpath(mod_file)) fullpath_noext = _jython_aware_splitext(os.path.realpath(full_path)) if realpath.lower() != fullpath_noext.lower(): module_dir = os.path.dirname(realpath) mod_name = _jython_aware_splitext(os.path.basename(full_path)) expected_dir = os.path.dirname(full_path) msg = ("%r module incorrectly imported from %r. Expected %r. " "Is this module globally installed?") raise ImportError(msg % (mod_name, module_dir, expected_dir)) yield self.loadTestsFromModule(module) elif os.path.isdir(full_path): if not os.path.isfile(os.path.join(full_path, '__init__.py')): continue load_tests = None tests = None if fnmatch(path, pattern): # only check load_tests if the package directory itself matches the filter name = self._get_name_from_path(full_path) package = self._get_module_from_name(name) load_tests = getattr(package, 'load_tests', None) tests = self.loadTestsFromModule(package, use_load_tests=False) if load_tests is None: if tests is not None: # tests loaded from package file yield tests # recurse into the package for test in self._find_tests(full_path, pattern): yield test else: try: yield load_tests(self, tests, pattern) except Exception as e: yield _make_failed_load_tests(package.__name__, e, self.suiteClass) defaultTestLoader = TestLoader() def _makeLoader(prefix, sortUsing, suiteClass=None): loader = TestLoader() loader.sortTestMethodsUsing = sortUsing loader.testMethodPrefix = prefix if suiteClass: loader.suiteClass = suiteClass return loader def getTestCaseNames(testCaseClass, prefix, sortUsing=util.three_way_cmp): return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass) def makeSuite(testCaseClass, prefix='test', sortUsing=util.three_way_cmp, suiteClass=suite.TestSuite): return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase( testCaseClass) def findTestCases(module, prefix='test', sortUsing=util.three_way_cmp, suiteClass=suite.TestSuite): return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(\ module)
gpl-2.0
Endika/OpenUpgrade
addons/l10n_be_intrastat/__openerp__.py
257
1631
# -*- encoding: utf-8 -*- ############################################################################## # # Odoo, Open Source Business Applications # Copyright (C) 2014-2015 Odoo S.A. <http://www.odoo.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Belgian Intrastat Declaration', 'version': '1.0', 'category': 'Reporting', 'description': """ Generates Intrastat XML report for declaration Based on invoices. """, 'author': 'Odoo SA', 'depends': ['report_intrastat', 'sale_stock', 'account_accountant', 'l10n_be'], 'data': [ 'data/regions.xml', 'data/report.intrastat.code.csv', 'data/transaction.codes.xml', 'data/transport.modes.xml', 'security/groups.xml', 'security/ir.model.access.csv', 'l10n_be_intrastat.xml', 'wizard/l10n_be_intrastat_xml_view.xml', ], 'installable': True, }
agpl-3.0
FNST-OpenStack/horizon
openstack_dashboard/test/integration_tests/tests/test_projects.py
32
1209
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from openstack_dashboard.test.integration_tests import helpers PROJECT_NAME = helpers.gen_random_resource_name("project") class TestCreateDeleteProject(helpers.AdminTestCase): def setUp(self): super(TestCreateDeleteProject, self).setUp() self.projects_page = self.home_pg.go_to_identity_projectspage() def test_create_delete_project(self): self.projects_page.create_project(PROJECT_NAME) self.assertTrue(self.projects_page.is_project_present(PROJECT_NAME)) self.projects_page.delete_project(PROJECT_NAME) self.assertFalse(self.projects_page.is_project_present(PROJECT_NAME))
apache-2.0
TileHalo/servo
components/script/dom/bindings/codegen/parser/WebIDL.py
28
249009
# 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/. """ A WebIDL parser. """ from ply import lex, yacc import re import os import traceback import math from collections import defaultdict # Machinery def parseInt(literal): string = literal sign = 0 base = 0 if string[0] == '-': sign = -1 string = string[1:] else: sign = 1 if string[0] == '0' and len(string) > 1: if string[1] == 'x' or string[1] == 'X': base = 16 string = string[2:] else: base = 8 string = string[1:] else: base = 10 value = int(string, base) return value * sign # Magic for creating enums def M_add_class_attribs(attribs, start): def foo(name, bases, dict_): for v, k in enumerate(attribs): dict_[k] = start + v assert 'length' not in dict_ dict_['length'] = start + len(attribs) return type(name, bases, dict_) return foo def enum(*names, **kw): if len(kw) == 1: base = kw['base'].__class__ start = base.length else: assert len(kw) == 0 base = object start = 0 class Foo(base): __metaclass__ = M_add_class_attribs(names, start) def __setattr__(self, name, value): # this makes it read-only raise NotImplementedError return Foo() class WebIDLError(Exception): def __init__(self, message, locations, warning=False): self.message = message self.locations = [str(loc) for loc in locations] self.warning = warning def __str__(self): return "%s: %s%s%s" % (self.warning and 'warning' or 'error', self.message, ", " if len(self.locations) != 0 else "", "\n".join(self.locations)) class Location(object): def __init__(self, lexer, lineno, lexpos, filename): self._line = None self._lineno = lineno self._lexpos = lexpos self._lexdata = lexer.lexdata self._file = filename if filename else "<unknown>" def __eq__(self, other): return (self._lexpos == other._lexpos and self._file == other._file) def filename(self): return self._file def resolve(self): if self._line: return startofline = self._lexdata.rfind('\n', 0, self._lexpos) + 1 endofline = self._lexdata.find('\n', self._lexpos, self._lexpos + 80) if endofline != -1: self._line = self._lexdata[startofline:endofline] else: self._line = self._lexdata[startofline:] self._colno = self._lexpos - startofline # Our line number seems to point to the start of self._lexdata self._lineno += self._lexdata.count('\n', 0, startofline) def get(self): self.resolve() return "%s line %s:%s" % (self._file, self._lineno, self._colno) def _pointerline(self): return " " * self._colno + "^" def __str__(self): self.resolve() return "%s line %s:%s\n%s\n%s" % (self._file, self._lineno, self._colno, self._line, self._pointerline()) class BuiltinLocation(object): def __init__(self, text): self.msg = text + "\n" def __eq__(self, other): return (isinstance(other, BuiltinLocation) and self.msg == other.msg) def filename(self): return '<builtin>' def resolve(self): pass def get(self): return self.msg def __str__(self): return self.get() # Data Model class IDLObject(object): def __init__(self, location): self.location = location self.userData = dict() def filename(self): return self.location.filename() def isInterface(self): return False def isEnum(self): return False def isCallback(self): return False def isType(self): return False def isDictionary(self): return False def isUnion(self): return False def isTypedef(self): return False def getUserData(self, key, default): return self.userData.get(key, default) def setUserData(self, key, value): self.userData[key] = value def addExtendedAttributes(self, attrs): assert False # Override me! def handleExtendedAttribute(self, attr): assert False # Override me! def _getDependentObjects(self): assert False # Override me! def getDeps(self, visited=None): """ Return a set of files that this object depends on. If any of these files are changed the parser needs to be rerun to regenerate a new IDLObject. The visited argument is a set of all the objects already visited. We must test to see if we are in it, and if so, do nothing. This prevents infinite recursion.""" # NB: We can't use visited=set() above because the default value is # evaluated when the def statement is evaluated, not when the function # is executed, so there would be one set for all invocations. if visited is None: visited = set() if self in visited: return set() visited.add(self) deps = set() if self.filename() != "<builtin>": deps.add(self.filename()) for d in self._getDependentObjects(): deps.update(d.getDeps(visited)) return deps class IDLScope(IDLObject): def __init__(self, location, parentScope, identifier): IDLObject.__init__(self, location) self.parentScope = parentScope if identifier: assert isinstance(identifier, IDLIdentifier) self._name = identifier else: self._name = None self._dict = {} self.globalNames = set() # A mapping from global name to the set of global interfaces # that have that global name. self.globalNameMapping = defaultdict(set) self.primaryGlobalAttr = None self.primaryGlobalName = None def __str__(self): return self.QName() def QName(self): if self._name: return self._name.QName() + "::" return "::" def ensureUnique(self, identifier, object): """ Ensure that there is at most one 'identifier' in scope ('self'). Note that object can be None. This occurs if we end up here for an interface type we haven't seen yet. """ assert isinstance(identifier, IDLUnresolvedIdentifier) assert not object or isinstance(object, IDLObjectWithIdentifier) assert not object or object.identifier == identifier if identifier.name in self._dict: if not object: return # ensureUnique twice with the same object is not allowed assert id(object) != id(self._dict[identifier.name]) replacement = self.resolveIdentifierConflict(self, identifier, self._dict[identifier.name], object) self._dict[identifier.name] = replacement return assert object self._dict[identifier.name] = object def resolveIdentifierConflict(self, scope, identifier, originalObject, newObject): if (isinstance(originalObject, IDLExternalInterface) and isinstance(newObject, IDLExternalInterface) and originalObject.identifier.name == newObject.identifier.name): return originalObject if (isinstance(originalObject, IDLExternalInterface) or isinstance(newObject, IDLExternalInterface)): raise WebIDLError( "Name collision between " "interface declarations for identifier '%s' at '%s' and '%s'" % (identifier.name, originalObject.location, newObject.location), []) if (isinstance(originalObject, IDLDictionary) or isinstance(newObject, IDLDictionary)): raise WebIDLError( "Name collision between dictionary declarations for " "identifier '%s'.\n%s\n%s" % (identifier.name, originalObject.location, newObject.location), []) # We do the merging of overloads here as opposed to in IDLInterface # because we need to merge overloads of NamedConstructors and we need to # detect conflicts in those across interfaces. See also the comment in # IDLInterface.addExtendedAttributes for "NamedConstructor". if (originalObject.tag == IDLInterfaceMember.Tags.Method and newObject.tag == IDLInterfaceMember.Tags.Method): return originalObject.addOverload(newObject) # Default to throwing, derived classes can override. conflictdesc = "\n\t%s at %s\n\t%s at %s" % (originalObject, originalObject.location, newObject, newObject.location) raise WebIDLError( "Multiple unresolvable definitions of identifier '%s' in scope '%s%s" % (identifier.name, str(self), conflictdesc), []) def _lookupIdentifier(self, identifier): return self._dict[identifier.name] def lookupIdentifier(self, identifier): assert isinstance(identifier, IDLIdentifier) assert identifier.scope == self return self._lookupIdentifier(identifier) class IDLIdentifier(IDLObject): def __init__(self, location, scope, name): IDLObject.__init__(self, location) self.name = name assert isinstance(scope, IDLScope) self.scope = scope def __str__(self): return self.QName() def QName(self): return self.scope.QName() + self.name def __hash__(self): return self.QName().__hash__() def __eq__(self, other): return self.QName() == other.QName() def object(self): return self.scope.lookupIdentifier(self) class IDLUnresolvedIdentifier(IDLObject): def __init__(self, location, name, allowDoubleUnderscore=False, allowForbidden=False): IDLObject.__init__(self, location) assert len(name) > 0 if name == "__noSuchMethod__": raise WebIDLError("__noSuchMethod__ is deprecated", [location]) if name[:2] == "__" and name != "__content" and not allowDoubleUnderscore: raise WebIDLError("Identifiers beginning with __ are reserved", [location]) if name[0] == '_' and not allowDoubleUnderscore: name = name[1:] # TODO: Bug 872377, Restore "toJSON" to below list. # We sometimes need custom serialization, so allow toJSON for now. if (name in ["constructor", "toString"] and not allowForbidden): raise WebIDLError("Cannot use reserved identifier '%s'" % (name), [location]) self.name = name def __str__(self): return self.QName() def QName(self): return "<unresolved scope>::" + self.name def resolve(self, scope, object): assert isinstance(scope, IDLScope) assert not object or isinstance(object, IDLObjectWithIdentifier) assert not object or object.identifier == self scope.ensureUnique(self, object) identifier = IDLIdentifier(self.location, scope, self.name) if object: object.identifier = identifier return identifier def finish(self): assert False # Should replace with a resolved identifier first. class IDLObjectWithIdentifier(IDLObject): def __init__(self, location, parentScope, identifier): IDLObject.__init__(self, location) assert isinstance(identifier, IDLUnresolvedIdentifier) self.identifier = identifier if parentScope: self.resolve(parentScope) self.treatNullAs = "Default" def resolve(self, parentScope): assert isinstance(parentScope, IDLScope) assert isinstance(self.identifier, IDLUnresolvedIdentifier) self.identifier.resolve(parentScope, self) def checkForStringHandlingExtendedAttributes(self, attrs, isDictionaryMember=False, isOptional=False): """ A helper function to deal with TreatNullAs. Returns the list of attrs it didn't handle itself. """ assert isinstance(self, IDLArgument) or isinstance(self, IDLAttribute) unhandledAttrs = list() for attr in attrs: if not attr.hasValue(): unhandledAttrs.append(attr) continue identifier = attr.identifier() value = attr.value() if identifier == "TreatNullAs": if not self.type.isDOMString() or self.type.nullable(): raise WebIDLError("[TreatNullAs] is only allowed on " "arguments or attributes whose type is " "DOMString", [self.location]) if isDictionaryMember: raise WebIDLError("[TreatNullAs] is not allowed for " "dictionary members", [self.location]) if value != 'EmptyString': raise WebIDLError("[TreatNullAs] must take the identifier " "'EmptyString', not '%s'" % value, [self.location]) self.treatNullAs = value else: unhandledAttrs.append(attr) return unhandledAttrs class IDLObjectWithScope(IDLObjectWithIdentifier, IDLScope): def __init__(self, location, parentScope, identifier): assert isinstance(identifier, IDLUnresolvedIdentifier) IDLObjectWithIdentifier.__init__(self, location, parentScope, identifier) IDLScope.__init__(self, location, parentScope, self.identifier) class IDLIdentifierPlaceholder(IDLObjectWithIdentifier): def __init__(self, location, identifier): assert isinstance(identifier, IDLUnresolvedIdentifier) IDLObjectWithIdentifier.__init__(self, location, None, identifier) def finish(self, scope): try: scope._lookupIdentifier(self.identifier) except: raise WebIDLError("Unresolved type '%s'." % self.identifier, [self.location]) obj = self.identifier.resolve(scope, None) return scope.lookupIdentifier(obj) class IDLExposureMixins(): def __init__(self, location): # _exposureGlobalNames are the global names listed in our [Exposed] # extended attribute. exposureSet is the exposure set as defined in the # Web IDL spec: it contains interface names. self._exposureGlobalNames = set() self.exposureSet = set() self._location = location self._globalScope = None def finish(self, scope): assert scope.parentScope is None self._globalScope = scope # Verify that our [Exposed] value, if any, makes sense. for globalName in self._exposureGlobalNames: if globalName not in scope.globalNames: raise WebIDLError("Unknown [Exposed] value %s" % globalName, [self._location]) if len(self._exposureGlobalNames) == 0: self._exposureGlobalNames.add(scope.primaryGlobalName) globalNameSetToExposureSet(scope, self._exposureGlobalNames, self.exposureSet) def isExposedInWindow(self): return 'Window' in self.exposureSet def isExposedInAnyWorker(self): return len(self.getWorkerExposureSet()) > 0 def isExposedInSystemGlobals(self): return 'BackstagePass' in self.exposureSet def isExposedInSomeButNotAllWorkers(self): """ Returns true if the Exposed extended attribute for this interface exposes it in some worker globals but not others. The return value does not depend on whether the interface is exposed in Window or System globals. """ if not self.isExposedInAnyWorker(): return False workerScopes = self.parentScope.globalNameMapping["Worker"] return len(workerScopes.difference(self.exposureSet)) > 0 def getWorkerExposureSet(self): workerScopes = self._globalScope.globalNameMapping["Worker"] return workerScopes.intersection(self.exposureSet) class IDLExternalInterface(IDLObjectWithIdentifier, IDLExposureMixins): def __init__(self, location, parentScope, identifier): raise WebIDLError("Servo does not support external interfaces.", [self.location]) class IDLPartialInterface(IDLObject): def __init__(self, location, name, members, nonPartialInterface): assert isinstance(name, IDLUnresolvedIdentifier) IDLObject.__init__(self, location) self.identifier = name self.members = members # propagatedExtendedAttrs are the ones that should get # propagated to our non-partial interface. self.propagatedExtendedAttrs = [] self._nonPartialInterface = nonPartialInterface self._finished = False nonPartialInterface.addPartialInterface(self) def addExtendedAttributes(self, attrs): for attr in attrs: identifier = attr.identifier() if identifier in ["Constructor", "NamedConstructor"]: self.propagatedExtendedAttrs.append(attr) elif identifier == "Exposed": # This just gets propagated to all our members. for member in self.members: if len(member._exposureGlobalNames) != 0: raise WebIDLError("[Exposed] specified on both a " "partial interface member and on the " "partial interface itself", [member.location, attr.location]) member.addExtendedAttributes([attr]) else: raise WebIDLError("Unknown extended attribute %s on partial " "interface" % identifier, [attr.location]) def finish(self, scope): if self._finished: return self._finished = True # Need to make sure our non-partial interface gets finished so it can # report cases when we only have partial interfaces. self._nonPartialInterface.finish(scope) def validate(self): pass def convertExposedAttrToGlobalNameSet(exposedAttr, targetSet): assert len(targetSet) == 0 if exposedAttr.hasValue(): targetSet.add(exposedAttr.value()) else: assert exposedAttr.hasArgs() targetSet.update(exposedAttr.args()) def globalNameSetToExposureSet(globalScope, nameSet, exposureSet): for name in nameSet: exposureSet.update(globalScope.globalNameMapping[name]) class IDLInterface(IDLObjectWithScope, IDLExposureMixins): def __init__(self, location, parentScope, name, parent, members, isKnownNonPartial): assert isinstance(parentScope, IDLScope) assert isinstance(name, IDLUnresolvedIdentifier) assert isKnownNonPartial or not parent assert isKnownNonPartial or len(members) == 0 self.parent = None self._callback = False self._finished = False self.members = [] self.maplikeOrSetlike = None self._partialInterfaces = [] self._extendedAttrDict = {} # namedConstructors needs deterministic ordering because bindings code # outputs the constructs in the order that namedConstructors enumerates # them. self.namedConstructors = list() self.implementedInterfaces = set() self._consequential = False self._isKnownNonPartial = False # self.interfacesBasedOnSelf is the set of interfaces that inherit from # self or have self as a consequential interface, including self itself. # Used for distinguishability checking. self.interfacesBasedOnSelf = set([self]) # self.interfacesImplementingSelf is the set of interfaces that directly # have self as a consequential interface self.interfacesImplementingSelf = set() self._hasChildInterfaces = False self._isOnGlobalProtoChain = False # Tracking of the number of reserved slots we need for our # members and those of ancestor interfaces. self.totalMembersInSlots = 0 # Tracking of the number of own own members we have in slots self._ownMembersInSlots = 0 IDLObjectWithScope.__init__(self, location, parentScope, name) IDLExposureMixins.__init__(self, location) if isKnownNonPartial: self.setNonPartial(location, parent, members) def __str__(self): return "Interface '%s'" % self.identifier.name def ctor(self): identifier = IDLUnresolvedIdentifier(self.location, "constructor", allowForbidden=True) try: return self._lookupIdentifier(identifier) except: return None def resolveIdentifierConflict(self, scope, identifier, originalObject, newObject): assert isinstance(scope, IDLScope) assert isinstance(originalObject, IDLInterfaceMember) assert isinstance(newObject, IDLInterfaceMember) retval = IDLScope.resolveIdentifierConflict(self, scope, identifier, originalObject, newObject) # Might be a ctor, which isn't in self.members if newObject in self.members: self.members.remove(newObject) return retval def finish(self, scope): if self._finished: return self._finished = True if not self._isKnownNonPartial: raise WebIDLError("Interface %s does not have a non-partial " "declaration" % self.identifier.name, [self.location]) IDLExposureMixins.finish(self, scope) # Now go ahead and merge in our partial interfaces. for partial in self._partialInterfaces: partial.finish(scope) self.addExtendedAttributes(partial.propagatedExtendedAttrs) self.members.extend(partial.members) # Generate maplike/setlike interface members. Since generated members # need to be treated like regular interface members, do this before # things like exposure setting. for member in self.members: if member.isMaplikeOrSetlike(): # Check that we only have one interface declaration (currently # there can only be one maplike/setlike declaration per # interface) if self.maplikeOrSetlike: raise WebIDLError("%s declaration used on " "interface that already has %s " "declaration" % (member.maplikeOrSetlikeType, self.maplikeOrSetlike.maplikeOrSetlikeType), [self.maplikeOrSetlike.location, member.location]) self.maplikeOrSetlike = member # If we've got a maplike or setlike declaration, we'll be building all of # our required methods in Codegen. Generate members now. self.maplikeOrSetlike.expand(self.members, self.isJSImplemented()) # Now that we've merged in our partial interfaces, set the # _exposureGlobalNames on any members that don't have it set yet. Note # that any partial interfaces that had [Exposed] set have already set up # _exposureGlobalNames on all the members coming from them, so this is # just implementing the "members default to interface that defined them" # and "partial interfaces default to interface they're a partial for" # rules from the spec. for m in self.members: # If m, or the partial interface m came from, had [Exposed] # specified, it already has a nonempty exposure global names set. if len(m._exposureGlobalNames) == 0: m._exposureGlobalNames.update(self._exposureGlobalNames) assert not self.parent or isinstance(self.parent, IDLIdentifierPlaceholder) parent = self.parent.finish(scope) if self.parent else None if parent and isinstance(parent, IDLExternalInterface): raise WebIDLError("%s inherits from %s which does not have " "a definition" % (self.identifier.name, self.parent.identifier.name), [self.location]) assert not parent or isinstance(parent, IDLInterface) self.parent = parent assert iter(self.members) if self.parent: self.parent.finish(scope) self.parent._hasChildInterfaces = True self.totalMembersInSlots = self.parent.totalMembersInSlots # Interfaces with [Global] or [PrimaryGlobal] must not # have anything inherit from them if (self.parent.getExtendedAttribute("Global") or self.parent.getExtendedAttribute("PrimaryGlobal")): # Note: This is not a self.parent.isOnGlobalProtoChain() check # because ancestors of a [Global] interface can have other # descendants. raise WebIDLError("[Global] interface has another interface " "inheriting from it", [self.location, self.parent.location]) # Make sure that we're not exposed in places where our parent is not if not self.exposureSet.issubset(self.parent.exposureSet): raise WebIDLError("Interface %s is exposed in globals where its " "parent interface %s is not exposed." % (self.identifier.name, self.parent.identifier.name), [self.location, self.parent.location]) # Callbacks must not inherit from non-callbacks or inherit from # anything that has consequential interfaces. # XXXbz Can non-callbacks inherit from callbacks? Spec issue pending. # XXXbz Can callbacks have consequential interfaces? Spec issue pending if self.isCallback(): if not self.parent.isCallback(): raise WebIDLError("Callback interface %s inheriting from " "non-callback interface %s" % (self.identifier.name, self.parent.identifier.name), [self.location, self.parent.location]) elif self.parent.isCallback(): raise WebIDLError("Non-callback interface %s inheriting from " "callback interface %s" % (self.identifier.name, self.parent.identifier.name), [self.location, self.parent.location]) # Interfaces which have interface objects can't inherit # from [NoInterfaceObject] interfaces. if (self.parent.getExtendedAttribute("NoInterfaceObject") and not self.getExtendedAttribute("NoInterfaceObject")): raise WebIDLError("Interface %s does not have " "[NoInterfaceObject] but inherits from " "interface %s which does" % (self.identifier.name, self.parent.identifier.name), [self.location, self.parent.location]) for iface in self.implementedInterfaces: iface.finish(scope) cycleInGraph = self.findInterfaceLoopPoint(self) if cycleInGraph: raise WebIDLError("Interface %s has itself as ancestor or " "implemented interface" % self.identifier.name, [self.location, cycleInGraph.location]) if self.isCallback(): # "implements" should have made sure we have no # consequential interfaces. assert len(self.getConsequentialInterfaces()) == 0 # And that we're not consequential. assert not self.isConsequential() # Now resolve() and finish() our members before importing the # ones from our implemented interfaces. # resolve() will modify self.members, so we need to iterate # over a copy of the member list here. for member in list(self.members): member.resolve(self) for member in self.members: member.finish(scope) # Now that we've finished our members, which has updated their exposure # sets, make sure they aren't exposed in places where we are not. for member in self.members: if not member.exposureSet.issubset(self.exposureSet): raise WebIDLError("Interface member has larger exposure set " "than the interface itself", [member.location, self.location]) ctor = self.ctor() if ctor is not None: assert len(ctor._exposureGlobalNames) == 0 ctor._exposureGlobalNames.update(self._exposureGlobalNames) ctor.finish(scope) for ctor in self.namedConstructors: assert len(ctor._exposureGlobalNames) == 0 ctor._exposureGlobalNames.update(self._exposureGlobalNames) ctor.finish(scope) # Make a copy of our member list, so things that implement us # can get those without all the stuff we implement ourselves # admixed. self.originalMembers = list(self.members) # Import everything from our consequential interfaces into # self.members. Sort our consequential interfaces by name # just so we have a consistent order. for iface in sorted(self.getConsequentialInterfaces(), cmp=cmp, key=lambda x: x.identifier.name): # Flag the interface as being someone's consequential interface iface.setIsConsequentialInterfaceOf(self) # Verify that we're not exposed somewhere where iface is not exposed if not self.exposureSet.issubset(iface.exposureSet): raise WebIDLError("Interface %s is exposed in globals where its " "consequential interface %s is not exposed." % (self.identifier.name, iface.identifier.name), [self.location, iface.location]) # If we have a maplike or setlike, and the consequential interface # also does, throw an error. if iface.maplikeOrSetlike and self.maplikeOrSetlike: raise WebIDLError("Maplike/setlike interface %s cannot have " "maplike/setlike interface %s as a " "consequential interface" % (self.identifier.name, iface.identifier.name), [self.maplikeOrSetlike.location, iface.maplikeOrSetlike.location]) additionalMembers = iface.originalMembers for additionalMember in additionalMembers: for member in self.members: if additionalMember.identifier.name == member.identifier.name: raise WebIDLError( "Multiple definitions of %s on %s coming from 'implements' statements" % (member.identifier.name, self), [additionalMember.location, member.location]) self.members.extend(additionalMembers) iface.interfacesImplementingSelf.add(self) for ancestor in self.getInheritedInterfaces(): ancestor.interfacesBasedOnSelf.add(self) if (ancestor.maplikeOrSetlike is not None and self.maplikeOrSetlike is not None): raise WebIDLError("Cannot have maplike/setlike on %s that " "inherits %s, which is already " "maplike/setlike" % (self.identifier.name, ancestor.identifier.name), [self.maplikeOrSetlike.location, ancestor.maplikeOrSetlike.location]) for ancestorConsequential in ancestor.getConsequentialInterfaces(): ancestorConsequential.interfacesBasedOnSelf.add(self) # Deal with interfaces marked [Unforgeable], now that we have our full # member list, except unforgeables pulled in from parents. We want to # do this before we set "originatingInterface" on our unforgeable # members. if self.getExtendedAttribute("Unforgeable"): # Check that the interface already has all the things the # spec would otherwise require us to synthesize and is # missing the ones we plan to synthesize. if not any(m.isMethod() and m.isStringifier() for m in self.members): raise WebIDLError("Unforgeable interface %s does not have a " "stringifier" % self.identifier.name, [self.location]) for m in self.members: if ((m.isMethod() and m.isJsonifier()) or m.identifier.name == "toJSON"): raise WebIDLError("Unforgeable interface %s has a " "jsonifier so we won't be able to add " "one ourselves" % self.identifier.name, [self.location, m.location]) if m.identifier.name == "valueOf" and not m.isStatic(): raise WebIDLError("Unforgeable interface %s has a valueOf " "member so we won't be able to add one " "ourselves" % self.identifier.name, [self.location, m.location]) for member in self.members: if ((member.isAttr() or member.isMethod()) and member.isUnforgeable() and not hasattr(member, "originatingInterface")): member.originatingInterface = self # Compute slot indices for our members before we pull in unforgeable # members from our parent. Also, maplike/setlike declarations get a # slot to hold their backing object. for member in self.members: if ((member.isAttr() and (member.getExtendedAttribute("StoreInSlot") or member.getExtendedAttribute("Cached"))) or member.isMaplikeOrSetlike()): member.slotIndex = self.totalMembersInSlots self.totalMembersInSlots += 1 if member.getExtendedAttribute("StoreInSlot"): self._ownMembersInSlots += 1 if self.parent: # Make sure we don't shadow any of the [Unforgeable] attributes on # our ancestor interfaces. We don't have to worry about # consequential interfaces here, because those have already been # imported into the relevant .members lists. And we don't have to # worry about anything other than our parent, because it has already # imported its ancestors unforgeable attributes into its member # list. for unforgeableMember in (member for member in self.parent.members if (member.isAttr() or member.isMethod()) and member.isUnforgeable()): shadows = [m for m in self.members if (m.isAttr() or m.isMethod()) and not m.isStatic() and m.identifier.name == unforgeableMember.identifier.name] if len(shadows) != 0: locs = [unforgeableMember.location] + [s.location for s in shadows] raise WebIDLError("Interface %s shadows [Unforgeable] " "members of %s" % (self.identifier.name, ancestor.identifier.name), locs) # And now just stick it in our members, since we won't be # inheriting this down the proto chain. If we really cared we # could try to do something where we set up the unforgeable # attributes/methods of ancestor interfaces, with their # corresponding getters, on our interface, but that gets pretty # complicated and seems unnecessary. self.members.append(unforgeableMember) # At this point, we have all of our members. If the current interface # uses maplike/setlike, check for collisions anywhere in the current # interface or higher in the inheritance chain. if self.maplikeOrSetlike: testInterface = self isAncestor = False while testInterface: self.maplikeOrSetlike.checkCollisions(testInterface.members, isAncestor) isAncestor = True testInterface = testInterface.parent # Ensure that there's at most one of each {named,indexed} # {getter,setter,creator,deleter}, at most one stringifier, # and at most one legacycaller. Note that this last is not # quite per spec, but in practice no one overloads # legacycallers. specialMembersSeen = {} for member in self.members: if not member.isMethod(): continue if member.isGetter(): memberType = "getters" elif member.isSetter(): memberType = "setters" elif member.isCreator(): memberType = "creators" elif member.isDeleter(): memberType = "deleters" elif member.isStringifier(): memberType = "stringifiers" elif member.isJsonifier(): memberType = "jsonifiers" elif member.isLegacycaller(): memberType = "legacycallers" else: continue if (memberType != "stringifiers" and memberType != "legacycallers" and memberType != "jsonifiers"): if member.isNamed(): memberType = "named " + memberType else: assert member.isIndexed() memberType = "indexed " + memberType if memberType in specialMembersSeen: raise WebIDLError("Multiple " + memberType + " on %s" % (self), [self.location, specialMembersSeen[memberType].location, member.location]) specialMembersSeen[memberType] = member if self._isOnGlobalProtoChain: # Make sure we have no named setters, creators, or deleters for memberType in ["setter", "creator", "deleter"]: memberId = "named " + memberType + "s" if memberId in specialMembersSeen: raise WebIDLError("Interface with [Global] has a named %s" % memberType, [self.location, specialMembersSeen[memberId].location]) # Make sure we're not [OverrideBuiltins] if self.getExtendedAttribute("OverrideBuiltins"): raise WebIDLError("Interface with [Global] also has " "[OverrideBuiltins]", [self.location]) # Mark all of our ancestors as being on the global's proto chain too parent = self.parent while parent: # Must not inherit from an interface with [OverrideBuiltins] if parent.getExtendedAttribute("OverrideBuiltins"): raise WebIDLError("Interface with [Global] inherits from " "interface with [OverrideBuiltins]", [self.location, parent.location]) parent._isOnGlobalProtoChain = True parent = parent.parent def validate(self): # We don't support consequential unforgeable interfaces. Need to check # this here, becaue in finish() an interface might not know yet that # it's consequential. if self.getExtendedAttribute("Unforgeable") and self.isConsequential(): raise WebIDLError( "%s is an unforgeable consequential interface" % self.identifier.name, [self.location] + list(i.location for i in (self.interfacesBasedOnSelf - {self}))) # We also don't support inheriting from unforgeable interfaces. if self.getExtendedAttribute("Unforgeable") and self.hasChildInterfaces(): locations = ([self.location] + list(i.location for i in self.interfacesBasedOnSelf if i.parent == self)) raise WebIDLError("%s is an unforgeable ancestor interface" % self.identifier.name, locations) for member in self.members: member.validate() if self.isCallback() and member.getExtendedAttribute("Replaceable"): raise WebIDLError("[Replaceable] used on an attribute on " "interface %s which is a callback interface" % self.identifier.name, [self.location, member.location]) # Check that PutForwards refers to another attribute and that no # cycles exist in forwarded assignments. if member.isAttr(): iface = self attr = member putForwards = attr.getExtendedAttribute("PutForwards") if putForwards and self.isCallback(): raise WebIDLError("[PutForwards] used on an attribute " "on interface %s which is a callback " "interface" % self.identifier.name, [self.location, member.location]) while putForwards is not None: forwardIface = attr.type.unroll().inner fowardAttr = None for forwardedMember in forwardIface.members: if (not forwardedMember.isAttr() or forwardedMember.identifier.name != putForwards[0]): continue if forwardedMember == member: raise WebIDLError("Cycle detected in forwarded " "assignments for attribute %s on " "%s" % (member.identifier.name, self), [member.location]) fowardAttr = forwardedMember break if fowardAttr is None: raise WebIDLError("Attribute %s on %s forwards to " "missing attribute %s" % (attr.identifier.name, iface, putForwards), [attr.location]) iface = forwardIface attr = fowardAttr putForwards = attr.getExtendedAttribute("PutForwards") # Check that the name of an [Alias] doesn't conflict with an # interface member. if member.isMethod(): for alias in member.aliases: if self.isOnGlobalProtoChain(): raise WebIDLError("[Alias] must not be used on a " "[Global] interface operation", [member.location]) if (member.getExtendedAttribute("Exposed") or member.getExtendedAttribute("ChromeOnly") or member.getExtendedAttribute("Pref") or member.getExtendedAttribute("Func") or member.getExtendedAttribute("AvailableIn") or member.getExtendedAttribute("CheckAnyPermissions") or member.getExtendedAttribute("CheckAllPermissions")): raise WebIDLError("[Alias] must not be used on a " "conditionally exposed operation", [member.location]) if member.isStatic(): raise WebIDLError("[Alias] must not be used on a " "static operation", [member.location]) if member.isIdentifierLess(): raise WebIDLError("[Alias] must not be used on an " "identifierless operation", [member.location]) if member.isUnforgeable(): raise WebIDLError("[Alias] must not be used on an " "[Unforgeable] operation", [member.location]) for m in self.members: if m.identifier.name == alias: raise WebIDLError("[Alias=%s] has same name as " "interface member" % alias, [member.location, m.location]) if m.isMethod() and m != member and alias in m.aliases: raise WebIDLError("duplicate [Alias=%s] definitions" % alias, [member.location, m.location]) if (self.getExtendedAttribute("Pref") and self._exposureGlobalNames != set([self.parentScope.primaryGlobalName])): raise WebIDLError("[Pref] used on an interface that is not %s-only" % self.parentScope.primaryGlobalName, [self.location]) for attribute in ["CheckAnyPermissions", "CheckAllPermissions"]: if (self.getExtendedAttribute(attribute) and self._exposureGlobalNames != set([self.parentScope.primaryGlobalName])): raise WebIDLError("[%s] used on an interface that is " "not %s-only" % (attribute, self.parentScope.primaryGlobalName), [self.location]) # Conditional exposure makes no sense for interfaces with no # interface object, unless they're navigator properties. if (self.isExposedConditionally() and not self.hasInterfaceObject() and not self.getNavigatorProperty()): raise WebIDLError("Interface with no interface object is " "exposed conditionally", [self.location]) def isInterface(self): return True def isExternal(self): return False def setIsConsequentialInterfaceOf(self, other): self._consequential = True self.interfacesBasedOnSelf.add(other) def isConsequential(self): return self._consequential def setCallback(self, value): self._callback = value def isCallback(self): return self._callback def isSingleOperationInterface(self): assert self.isCallback() or self.isJSImplemented() return ( # JS-implemented things should never need the # this-handling weirdness of single-operation interfaces. not self.isJSImplemented() and # Not inheriting from another interface not self.parent and # No consequential interfaces len(self.getConsequentialInterfaces()) == 0 and # No attributes of any kinds not any(m.isAttr() for m in self.members) and # There is at least one regular operation, and all regular # operations have the same identifier len(set(m.identifier.name for m in self.members if m.isMethod() and not m.isStatic())) == 1) def inheritanceDepth(self): depth = 0 parent = self.parent while parent: depth = depth + 1 parent = parent.parent return depth def hasConstants(self): return any(m.isConst() for m in self.members) def hasInterfaceObject(self): if self.isCallback(): return self.hasConstants() return not hasattr(self, "_noInterfaceObject") def hasInterfacePrototypeObject(self): return not self.isCallback() and self.getUserData('hasConcreteDescendant', False) def addExtendedAttributes(self, attrs): for attr in attrs: identifier = attr.identifier() # Special cased attrs if identifier == "TreatNonCallableAsNull": raise WebIDLError("TreatNonCallableAsNull cannot be specified on interfaces", [attr.location, self.location]) if identifier == "TreatNonObjectAsNull": raise WebIDLError("TreatNonObjectAsNull cannot be specified on interfaces", [attr.location, self.location]) elif identifier == "NoInterfaceObject": if not attr.noArguments(): raise WebIDLError("[NoInterfaceObject] must take no arguments", [attr.location]) if self.ctor(): raise WebIDLError("Constructor and NoInterfaceObject are incompatible", [self.location]) self._noInterfaceObject = True elif identifier == "Constructor" or identifier == "NamedConstructor" or identifier == "ChromeConstructor": if identifier == "Constructor" and not self.hasInterfaceObject(): raise WebIDLError(str(identifier) + " and NoInterfaceObject are incompatible", [self.location]) if identifier == "NamedConstructor" and not attr.hasValue(): raise WebIDLError("NamedConstructor must either take an identifier or take a named argument list", [attr.location]) if identifier == "ChromeConstructor" and not self.hasInterfaceObject(): raise WebIDLError(str(identifier) + " and NoInterfaceObject are incompatible", [self.location]) args = attr.args() if attr.hasArgs() else [] if self.identifier.name == "Promise": promiseType = BuiltinTypes[IDLBuiltinType.Types.any] else: promiseType = None retType = IDLWrapperType(self.location, self, promiseType) if identifier == "Constructor" or identifier == "ChromeConstructor": name = "constructor" allowForbidden = True else: name = attr.value() allowForbidden = False methodIdentifier = IDLUnresolvedIdentifier(self.location, name, allowForbidden=allowForbidden) method = IDLMethod(self.location, methodIdentifier, retType, args, static=True) # Constructors are always NewObject and are always # assumed to be able to throw (since there's no way to # indicate otherwise) and never have any other # extended attributes. method.addExtendedAttributes( [IDLExtendedAttribute(self.location, ("NewObject",)), IDLExtendedAttribute(self.location, ("Throws",))]) if identifier == "ChromeConstructor": method.addExtendedAttributes( [IDLExtendedAttribute(self.location, ("ChromeOnly",))]) if identifier == "Constructor" or identifier == "ChromeConstructor": method.resolve(self) else: # We need to detect conflicts for NamedConstructors across # interfaces. We first call resolve on the parentScope, # which will merge all NamedConstructors with the same # identifier accross interfaces as overloads. method.resolve(self.parentScope) # Then we look up the identifier on the parentScope. If the # result is the same as the method we're adding then it # hasn't been added as an overload and it's the first time # we've encountered a NamedConstructor with that identifier. # If the result is not the same as the method we're adding # then it has been added as an overload and we need to check # whether the result is actually one of our existing # NamedConstructors. newMethod = self.parentScope.lookupIdentifier(method.identifier) if newMethod == method: self.namedConstructors.append(method) elif newMethod not in self.namedConstructors: raise WebIDLError("NamedConstructor conflicts with a NamedConstructor of a different interface", [method.location, newMethod.location]) elif (identifier == "ArrayClass"): if not attr.noArguments(): raise WebIDLError("[ArrayClass] must take no arguments", [attr.location]) if self.parent: raise WebIDLError("[ArrayClass] must not be specified on " "an interface with inherited interfaces", [attr.location, self.location]) elif (identifier == "ExceptionClass"): if not attr.noArguments(): raise WebIDLError("[ExceptionClass] must take no arguments", [attr.location]) if self.parent: raise WebIDLError("[ExceptionClass] must not be specified on " "an interface with inherited interfaces", [attr.location, self.location]) elif identifier == "Global": if attr.hasValue(): self.globalNames = [attr.value()] elif attr.hasArgs(): self.globalNames = attr.args() else: self.globalNames = [self.identifier.name] self.parentScope.globalNames.update(self.globalNames) for globalName in self.globalNames: self.parentScope.globalNameMapping[globalName].add(self.identifier.name) self._isOnGlobalProtoChain = True elif identifier == "PrimaryGlobal": if not attr.noArguments(): raise WebIDLError("[PrimaryGlobal] must take no arguments", [attr.location]) if self.parentScope.primaryGlobalAttr is not None: raise WebIDLError( "[PrimaryGlobal] specified twice", [attr.location, self.parentScope.primaryGlobalAttr.location]) self.parentScope.primaryGlobalAttr = attr self.parentScope.primaryGlobalName = self.identifier.name self.parentScope.globalNames.add(self.identifier.name) self.parentScope.globalNameMapping[self.identifier.name].add(self.identifier.name) self._isOnGlobalProtoChain = True elif (identifier == "NeedResolve" or identifier == "OverrideBuiltins" or identifier == "ChromeOnly" or identifier == "Unforgeable" or identifier == "UnsafeInPrerendering" or identifier == "LegacyEventInit" or identifier == "Abstract"): # Known extended attributes that do not take values if not attr.noArguments(): raise WebIDLError("[%s] must take no arguments" % identifier, [attr.location]) elif identifier == "Exposed": convertExposedAttrToGlobalNameSet(attr, self._exposureGlobalNames) elif (identifier == "Pref" or identifier == "JSImplementation" or identifier == "HeaderFile" or identifier == "NavigatorProperty" or identifier == "AvailableIn" or identifier == "Func" or identifier == "CheckAnyPermissions" or identifier == "CheckAllPermissions"): # Known extended attributes that take a string value if not attr.hasValue(): raise WebIDLError("[%s] must have a value" % identifier, [attr.location]) else: raise WebIDLError("Unknown extended attribute %s on interface" % identifier, [attr.location]) attrlist = attr.listValue() self._extendedAttrDict[identifier] = attrlist if len(attrlist) else True def addImplementedInterface(self, implementedInterface): assert(isinstance(implementedInterface, IDLInterface)) self.implementedInterfaces.add(implementedInterface) def getInheritedInterfaces(self): """ Returns a list of the interfaces this interface inherits from (not including this interface itself). The list is in order from most derived to least derived. """ assert(self._finished) if not self.parent: return [] parentInterfaces = self.parent.getInheritedInterfaces() parentInterfaces.insert(0, self.parent) return parentInterfaces def getConsequentialInterfaces(self): assert(self._finished) # The interfaces we implement directly consequentialInterfaces = set(self.implementedInterfaces) # And their inherited interfaces for iface in self.implementedInterfaces: consequentialInterfaces |= set(iface.getInheritedInterfaces()) # And now collect up the consequential interfaces of all of those temp = set() for iface in consequentialInterfaces: temp |= iface.getConsequentialInterfaces() return consequentialInterfaces | temp def findInterfaceLoopPoint(self, otherInterface): """ Finds an interface, amongst our ancestors and consequential interfaces, that inherits from otherInterface or implements otherInterface directly. If there is no such interface, returns None. """ if self.parent: if self.parent == otherInterface: return self loopPoint = self.parent.findInterfaceLoopPoint(otherInterface) if loopPoint: return loopPoint if otherInterface in self.implementedInterfaces: return self for iface in self.implementedInterfaces: loopPoint = iface.findInterfaceLoopPoint(otherInterface) if loopPoint: return loopPoint return None def getExtendedAttribute(self, name): return self._extendedAttrDict.get(name, None) def setNonPartial(self, location, parent, members): assert not parent or isinstance(parent, IDLIdentifierPlaceholder) if self._isKnownNonPartial: raise WebIDLError("Two non-partial definitions for the " "same interface", [location, self.location]) self._isKnownNonPartial = True # Now make it look like we were parsed at this new location, since # that's the place where the interface is "really" defined self.location = location assert not self.parent self.parent = parent # Put the new members at the beginning self.members = members + self.members def addPartialInterface(self, partial): assert self.identifier.name == partial.identifier.name self._partialInterfaces.append(partial) def getJSImplementation(self): classId = self.getExtendedAttribute("JSImplementation") if not classId: return classId assert isinstance(classId, list) assert len(classId) == 1 return classId[0] def isJSImplemented(self): return bool(self.getJSImplementation()) def getNavigatorProperty(self): naviProp = self.getExtendedAttribute("NavigatorProperty") if not naviProp: return None assert len(naviProp) == 1 assert isinstance(naviProp, list) assert len(naviProp[0]) != 0 return naviProp[0] def hasChildInterfaces(self): return self._hasChildInterfaces def isOnGlobalProtoChain(self): return self._isOnGlobalProtoChain def _getDependentObjects(self): deps = set(self.members) deps.update(self.implementedInterfaces) if self.parent: deps.add(self.parent) return deps def hasMembersInSlots(self): return self._ownMembersInSlots != 0 def isExposedConditionally(self): return (self.getExtendedAttribute("Pref") or self.getExtendedAttribute("ChromeOnly") or self.getExtendedAttribute("Func") or self.getExtendedAttribute("AvailableIn") or self.getExtendedAttribute("CheckAnyPermissions") or self.getExtendedAttribute("CheckAllPermissions")) class IDLDictionary(IDLObjectWithScope): def __init__(self, location, parentScope, name, parent, members): assert isinstance(parentScope, IDLScope) assert isinstance(name, IDLUnresolvedIdentifier) assert not parent or isinstance(parent, IDLIdentifierPlaceholder) self.parent = parent self._finished = False self.members = list(members) IDLObjectWithScope.__init__(self, location, parentScope, name) def __str__(self): return "Dictionary '%s'" % self.identifier.name def isDictionary(self): return True def canBeEmpty(self): """ Returns true if this dictionary can be empty (that is, it has no required members and neither do any of its ancestors). """ return (all(member.optional for member in self.members) and (not self.parent or self.parent.canBeEmpty())) def finish(self, scope): if self._finished: return self._finished = True if self.parent: assert isinstance(self.parent, IDLIdentifierPlaceholder) oldParent = self.parent self.parent = self.parent.finish(scope) if not isinstance(self.parent, IDLDictionary): raise WebIDLError("Dictionary %s has parent that is not a dictionary" % self.identifier.name, [oldParent.location, self.parent.location]) # Make sure the parent resolves all its members before we start # looking at them. self.parent.finish(scope) for member in self.members: member.resolve(self) if not member.isComplete(): member.complete(scope) assert member.type.isComplete() # Members of a dictionary are sorted in lexicographic order self.members.sort(cmp=cmp, key=lambda x: x.identifier.name) inheritedMembers = [] ancestor = self.parent while ancestor: if ancestor == self: raise WebIDLError("Dictionary %s has itself as an ancestor" % self.identifier.name, [self.identifier.location]) inheritedMembers.extend(ancestor.members) ancestor = ancestor.parent # Catch name duplication for inheritedMember in inheritedMembers: for member in self.members: if member.identifier.name == inheritedMember.identifier.name: raise WebIDLError("Dictionary %s has two members with name %s" % (self.identifier.name, member.identifier.name), [member.location, inheritedMember.location]) def validate(self): def typeContainsDictionary(memberType, dictionary): """ Returns a tuple whose: - First element is a Boolean value indicating whether memberType contains dictionary. - Second element is: A list of locations that leads from the type that was passed in the memberType argument, to the dictionary being validated, if the boolean value in the first element is True. None, if the boolean value in the first element is False. """ if (memberType.nullable() or memberType.isArray() or memberType.isSequence() or memberType.isMozMap()): return typeContainsDictionary(memberType.inner, dictionary) if memberType.isDictionary(): if memberType.inner == dictionary: return (True, [memberType.location]) (contains, locations) = dictionaryContainsDictionary(memberType.inner, dictionary) if contains: return (True, [memberType.location] + locations) if memberType.isUnion(): for member in memberType.flatMemberTypes: (contains, locations) = typeContainsDictionary(member, dictionary) if contains: return (True, locations) return (False, None) def dictionaryContainsDictionary(dictMember, dictionary): for member in dictMember.members: (contains, locations) = typeContainsDictionary(member.type, dictionary) if contains: return (True, [member.location] + locations) if dictMember.parent: if dictMember.parent == dictionary: return (True, [dictMember.location]) else: (contains, locations) = dictionaryContainsDictionary(dictMember.parent, dictionary) if contains: return (True, [dictMember.location] + locations) return (False, None) for member in self.members: if member.type.isDictionary() and member.type.nullable(): raise WebIDLError("Dictionary %s has member with nullable " "dictionary type" % self.identifier.name, [member.location]) (contains, locations) = typeContainsDictionary(member.type, self) if contains: raise WebIDLError("Dictionary %s has member with itself as type." % self.identifier.name, [member.location] + locations) def module(self): return self.location.filename().split('/')[-1].split('.webidl')[0] + 'Binding' def addExtendedAttributes(self, attrs): assert len(attrs) == 0 def _getDependentObjects(self): deps = set(self.members) if (self.parent): deps.add(self.parent) return deps class IDLEnum(IDLObjectWithIdentifier): def __init__(self, location, parentScope, name, values): assert isinstance(parentScope, IDLScope) assert isinstance(name, IDLUnresolvedIdentifier) if len(values) != len(set(values)): raise WebIDLError("Enum %s has multiple identical strings" % name.name, [location]) IDLObjectWithIdentifier.__init__(self, location, parentScope, name) self._values = values def values(self): return self._values def finish(self, scope): pass def validate(self): pass def isEnum(self): return True def addExtendedAttributes(self, attrs): assert len(attrs) == 0 def _getDependentObjects(self): return set() class IDLType(IDLObject): Tags = enum( # The integer types 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64', # Additional primitive types 'bool', 'unrestricted_float', 'float', 'unrestricted_double', # "double" last primitive type to match IDLBuiltinType 'double', # Other types 'any', 'domstring', 'bytestring', 'usvstring', 'object', 'date', 'void', # Funny stuff 'interface', 'dictionary', 'enum', 'callback', 'union', 'sequence', 'mozmap', 'array' ) def __init__(self, location, name): IDLObject.__init__(self, location) self.name = name self.builtin = False def __eq__(self, other): return other and self.builtin == other.builtin and self.name == other.name def __ne__(self, other): return not self == other def __str__(self): return str(self.name) def isType(self): return True def nullable(self): return False def isPrimitive(self): return False def isBoolean(self): return False def isNumeric(self): return False def isString(self): return False def isByteString(self): return False def isDOMString(self): return False def isUSVString(self): return False def isVoid(self): return self.name == "Void" def isSequence(self): return False def isMozMap(self): return False def isArray(self): return False def isArrayBuffer(self): return False def isArrayBufferView(self): return False def isSharedArrayBuffer(self): return False def isSharedArrayBufferView(self): return False def isTypedArray(self): return False def isSharedTypedArray(self): return False def isCallbackInterface(self): return False def isNonCallbackInterface(self): return False def isGeckoInterface(self): """ Returns a boolean indicating whether this type is an 'interface' type that is implemented in Gecko. At the moment, this returns true for all interface types that are not types from the TypedArray spec.""" return self.isInterface() and not self.isSpiderMonkeyInterface() def isSpiderMonkeyInterface(self): """ Returns a boolean indicating whether this type is an 'interface' type that is implemented in Spidermonkey. At the moment, this only returns true for the types from the TypedArray spec. """ return self.isInterface() and (self.isArrayBuffer() or self.isArrayBufferView() or self.isSharedArrayBuffer() or self.isSharedArrayBufferView() or self.isTypedArray() or self.isSharedTypedArray()) def isDictionary(self): return False def isInterface(self): return False def isAny(self): return self.tag() == IDLType.Tags.any def isDate(self): return self.tag() == IDLType.Tags.date def isObject(self): return self.tag() == IDLType.Tags.object def isPromise(self): return False def isComplete(self): return True def includesRestrictedFloat(self): return False def isFloat(self): return False def isUnrestricted(self): # Should only call this on float types assert self.isFloat() def isSerializable(self): return False def tag(self): assert False # Override me! def treatNonCallableAsNull(self): assert self.tag() == IDLType.Tags.callback return self.nullable() and self.inner.callback._treatNonCallableAsNull def treatNonObjectAsNull(self): assert self.tag() == IDLType.Tags.callback return self.nullable() and self.inner.callback._treatNonObjectAsNull def addExtendedAttributes(self, attrs): assert len(attrs) == 0 def resolveType(self, parentScope): pass def unroll(self): return self def isDistinguishableFrom(self, other): raise TypeError("Can't tell whether a generic type is or is not " "distinguishable from other things") def isExposedInAllOf(self, exposureSet): return True class IDLUnresolvedType(IDLType): """ Unresolved types are interface types """ def __init__(self, location, name, promiseInnerType=None): IDLType.__init__(self, location, name) self._promiseInnerType = promiseInnerType def isComplete(self): return False def complete(self, scope): obj = None try: obj = scope._lookupIdentifier(self.name) except: raise WebIDLError("Unresolved type '%s'." % self.name, [self.location]) assert obj if obj.isType(): print obj assert not obj.isType() if obj.isTypedef(): assert self.name.name == obj.identifier.name typedefType = IDLTypedefType(self.location, obj.innerType, obj.identifier) assert not typedefType.isComplete() return typedefType.complete(scope) elif obj.isCallback() and not obj.isInterface(): assert self.name.name == obj.identifier.name return IDLCallbackType(self.location, obj) if self._promiseInnerType and not self._promiseInnerType.isComplete(): self._promiseInnerType = self._promiseInnerType.complete(scope) name = self.name.resolve(scope, None) return IDLWrapperType(self.location, obj, self._promiseInnerType) def isDistinguishableFrom(self, other): raise TypeError("Can't tell whether an unresolved type is or is not " "distinguishable from other things") class IDLNullableType(IDLType): def __init__(self, location, innerType): assert not innerType.isVoid() assert not innerType == BuiltinTypes[IDLBuiltinType.Types.any] name = innerType.name if innerType.isComplete(): name += "OrNull" IDLType.__init__(self, location, name) self.inner = innerType self.builtin = False def __eq__(self, other): return isinstance(other, IDLNullableType) and self.inner == other.inner def __str__(self): return self.inner.__str__() + "OrNull" def nullable(self): return True def isCallback(self): return self.inner.isCallback() def isPrimitive(self): return self.inner.isPrimitive() def isBoolean(self): return self.inner.isBoolean() def isNumeric(self): return self.inner.isNumeric() def isString(self): return self.inner.isString() def isByteString(self): return self.inner.isByteString() def isDOMString(self): return self.inner.isDOMString() def isUSVString(self): return self.inner.isUSVString() def isFloat(self): return self.inner.isFloat() def isUnrestricted(self): return self.inner.isUnrestricted() def includesRestrictedFloat(self): return self.inner.includesRestrictedFloat() def isInteger(self): return self.inner.isInteger() def isVoid(self): return False def isSequence(self): return self.inner.isSequence() def isMozMap(self): return self.inner.isMozMap() def isArray(self): return self.inner.isArray() def isArrayBuffer(self): return self.inner.isArrayBuffer() def isArrayBufferView(self): return self.inner.isArrayBufferView() def isSharedArrayBuffer(self): return self.inner.isSharedArrayBuffer() def isSharedArrayBufferView(self): return self.inner.isSharedArrayBufferView() def isTypedArray(self): return self.inner.isTypedArray() def isSharedTypedArray(self): return self.inner.isSharedTypedArray() def isDictionary(self): return self.inner.isDictionary() def isInterface(self): return self.inner.isInterface() def isPromise(self): return self.inner.isPromise() def isCallbackInterface(self): return self.inner.isCallbackInterface() def isNonCallbackInterface(self): return self.inner.isNonCallbackInterface() def isEnum(self): return self.inner.isEnum() def isUnion(self): return self.inner.isUnion() def isSerializable(self): return self.inner.isSerializable() def tag(self): return self.inner.tag() def resolveType(self, parentScope): assert isinstance(parentScope, IDLScope) self.inner.resolveType(parentScope) def isComplete(self): return self.inner.isComplete() def complete(self, scope): self.inner = self.inner.complete(scope) if self.inner.nullable(): raise WebIDLError("The inner type of a nullable type must not be " "a nullable type", [self.location, self.inner.location]) if self.inner.isUnion(): if self.inner.hasNullableType: raise WebIDLError("The inner type of a nullable type must not " "be a union type that itself has a nullable " "type as a member type", [self.location]) self.name = self.inner.name + "OrNull" return self def unroll(self): return self.inner.unroll() def isDistinguishableFrom(self, other): if (other.nullable() or (other.isUnion() and other.hasNullableType) or other.isDictionary()): # Can't tell which type null should become return False return self.inner.isDistinguishableFrom(other) def _getDependentObjects(self): return self.inner._getDependentObjects() class IDLSequenceType(IDLType): def __init__(self, location, parameterType): assert not parameterType.isVoid() IDLType.__init__(self, location, parameterType.name) self.inner = parameterType self.builtin = False # Need to set self.name up front if our inner type is already complete, # since in that case our .complete() won't be called. if self.inner.isComplete(): self.name = self.inner.name + "Sequence" def __eq__(self, other): return isinstance(other, IDLSequenceType) and self.inner == other.inner def __str__(self): return self.inner.__str__() + "Sequence" def nullable(self): return False def isPrimitive(self): return False def isString(self): return False def isByteString(self): return False def isDOMString(self): return False def isUSVString(self): return False def isVoid(self): return False def isSequence(self): return True def isArray(self): return False def isDictionary(self): return False def isInterface(self): return False def isEnum(self): return False def isSerializable(self): return self.inner.isSerializable() def includesRestrictedFloat(self): return self.inner.includesRestrictedFloat() def tag(self): return IDLType.Tags.sequence def resolveType(self, parentScope): assert isinstance(parentScope, IDLScope) self.inner.resolveType(parentScope) def isComplete(self): return self.inner.isComplete() def complete(self, scope): self.inner = self.inner.complete(scope) self.name = self.inner.name + "Sequence" return self def unroll(self): return self.inner.unroll() def isDistinguishableFrom(self, other): if other.isPromise(): return False if other.isUnion(): # Just forward to the union; it'll deal return other.isDistinguishableFrom(self) return (other.isPrimitive() or other.isString() or other.isEnum() or other.isDate() or other.isInterface() or other.isDictionary() or other.isCallback() or other.isMozMap()) def _getDependentObjects(self): return self.inner._getDependentObjects() class IDLMozMapType(IDLType): # XXXbz This is pretty similar to IDLSequenceType in various ways. # And maybe to IDLNullableType. Should we have a superclass for # "type containing this other type"? Bug 1015318. def __init__(self, location, parameterType): assert not parameterType.isVoid() IDLType.__init__(self, location, parameterType.name) self.inner = parameterType self.builtin = False # Need to set self.name up front if our inner type is already complete, # since in that case our .complete() won't be called. if self.inner.isComplete(): self.name = self.inner.name + "MozMap" def __eq__(self, other): return isinstance(other, IDLMozMapType) and self.inner == other.inner def __str__(self): return self.inner.__str__() + "MozMap" def isMozMap(self): return True def includesRestrictedFloat(self): return self.inner.includesRestrictedFloat() def tag(self): return IDLType.Tags.mozmap def resolveType(self, parentScope): assert isinstance(parentScope, IDLScope) self.inner.resolveType(parentScope) def isComplete(self): return self.inner.isComplete() def complete(self, scope): self.inner = self.inner.complete(scope) self.name = self.inner.name + "MozMap" return self def unroll(self): # We do not unroll our inner. Just stop at ourselves. That # lets us add headers for both ourselves and our inner as # needed. return self def isDistinguishableFrom(self, other): if other.isPromise(): return False if other.isUnion(): # Just forward to the union; it'll deal return other.isDistinguishableFrom(self) return (other.isPrimitive() or other.isString() or other.isEnum() or other.isDate() or other.isNonCallbackInterface() or other.isSequence()) def isExposedInAllOf(self, exposureSet): return self.inner.unroll().isExposedInAllOf(exposureSet) def _getDependentObjects(self): return self.inner._getDependentObjects() class IDLUnionType(IDLType): def __init__(self, location, memberTypes): IDLType.__init__(self, location, "") self.memberTypes = memberTypes self.hasNullableType = False self._dictionaryType = None self.flatMemberTypes = None self.builtin = False def __eq__(self, other): return isinstance(other, IDLUnionType) and self.memberTypes == other.memberTypes def __hash__(self): assert self.isComplete() return self.name.__hash__() def isVoid(self): return False def isUnion(self): return True def isSerializable(self): return all(m.isSerializable() for m in self.memberTypes) def includesRestrictedFloat(self): return any(t.includesRestrictedFloat() for t in self.memberTypes) def tag(self): return IDLType.Tags.union def resolveType(self, parentScope): assert isinstance(parentScope, IDLScope) for t in self.memberTypes: t.resolveType(parentScope) def isComplete(self): return self.flatMemberTypes is not None def complete(self, scope): def typeName(type): if isinstance(type, IDLNullableType): return typeName(type.inner) + "OrNull" if isinstance(type, IDLWrapperType): return typeName(type._identifier.object()) if isinstance(type, IDLObjectWithIdentifier): return typeName(type.identifier) return type.name for (i, type) in enumerate(self.memberTypes): if not type.isComplete(): self.memberTypes[i] = type.complete(scope) self.name = "Or".join(typeName(type) for type in self.memberTypes) self.flatMemberTypes = list(self.memberTypes) i = 0 while i < len(self.flatMemberTypes): if self.flatMemberTypes[i].nullable(): if self.hasNullableType: raise WebIDLError("Can't have more than one nullable types in a union", [nullableType.location, self.flatMemberTypes[i].location]) if self.hasDictionaryType(): raise WebIDLError("Can't have a nullable type and a " "dictionary type in a union", [self._dictionaryType.location, self.flatMemberTypes[i].location]) self.hasNullableType = True nullableType = self.flatMemberTypes[i] self.flatMemberTypes[i] = self.flatMemberTypes[i].inner continue if self.flatMemberTypes[i].isDictionary(): if self.hasNullableType: raise WebIDLError("Can't have a nullable type and a " "dictionary type in a union", [nullableType.location, self.flatMemberTypes[i].location]) self._dictionaryType = self.flatMemberTypes[i] elif self.flatMemberTypes[i].isUnion(): self.flatMemberTypes[i:i + 1] = self.flatMemberTypes[i].memberTypes continue i += 1 for (i, t) in enumerate(self.flatMemberTypes[:-1]): for u in self.flatMemberTypes[i + 1:]: if not t.isDistinguishableFrom(u): raise WebIDLError("Flat member types of a union should be " "distinguishable, " + str(t) + " is not " "distinguishable from " + str(u), [self.location, t.location, u.location]) return self def isDistinguishableFrom(self, other): if self.hasNullableType and other.nullable(): # Can't tell which type null should become return False if other.isUnion(): otherTypes = other.unroll().memberTypes else: otherTypes = [other] # For every type in otherTypes, check that it's distinguishable from # every type in our types for u in otherTypes: if any(not t.isDistinguishableFrom(u) for t in self.memberTypes): return False return True def isExposedInAllOf(self, exposureSet): # We could have different member types in different globals. Just make sure that each thing in exposureSet has one of our member types exposed in it. for globalName in exposureSet: if not any(t.unroll().isExposedInAllOf(set([globalName])) for t in self.flatMemberTypes): return False return True def hasDictionaryType(self): return self._dictionaryType is not None def hasPossiblyEmptyDictionaryType(self): return (self._dictionaryType is not None and self._dictionaryType.inner.canBeEmpty()) def _getDependentObjects(self): return set(self.memberTypes) class IDLArrayType(IDLType): def __init__(self, location, parameterType): assert not parameterType.isVoid() if parameterType.isSequence(): raise WebIDLError("Array type cannot parameterize over a sequence type", [location]) if parameterType.isMozMap(): raise WebIDLError("Array type cannot parameterize over a MozMap type", [location]) if parameterType.isDictionary(): raise WebIDLError("Array type cannot parameterize over a dictionary type", [location]) IDLType.__init__(self, location, parameterType.name) self.inner = parameterType self.builtin = False def __eq__(self, other): return isinstance(other, IDLArrayType) and self.inner == other.inner def __str__(self): return self.inner.__str__() + "Array" def nullable(self): return False def isPrimitive(self): return False def isString(self): return False def isByteString(self): return False def isDOMString(self): return False def isUSVString(self): return False def isVoid(self): return False def isSequence(self): assert not self.inner.isSequence() return False def isArray(self): return True def isDictionary(self): assert not self.inner.isDictionary() return False def isInterface(self): return False def isEnum(self): return False def tag(self): return IDLType.Tags.array def resolveType(self, parentScope): assert isinstance(parentScope, IDLScope) self.inner.resolveType(parentScope) def isComplete(self): return self.inner.isComplete() def complete(self, scope): self.inner = self.inner.complete(scope) self.name = self.inner.name if self.inner.isDictionary(): raise WebIDLError("Array type must not contain " "dictionary as element type.", [self.inner.location]) assert not self.inner.isSequence() return self def unroll(self): return self.inner.unroll() def isDistinguishableFrom(self, other): if other.isPromise(): return False if other.isUnion(): # Just forward to the union; it'll deal return other.isDistinguishableFrom(self) return (other.isPrimitive() or other.isString() or other.isEnum() or other.isDate() or other.isNonCallbackInterface()) def _getDependentObjects(self): return self.inner._getDependentObjects() class IDLTypedefType(IDLType): def __init__(self, location, innerType, name): IDLType.__init__(self, location, name) self.inner = innerType self.builtin = False def __eq__(self, other): return isinstance(other, IDLTypedefType) and self.inner == other.inner def __str__(self): return self.name def nullable(self): return self.inner.nullable() def isPrimitive(self): return self.inner.isPrimitive() def isBoolean(self): return self.inner.isBoolean() def isNumeric(self): return self.inner.isNumeric() def isString(self): return self.inner.isString() def isByteString(self): return self.inner.isByteString() def isDOMString(self): return self.inner.isDOMString() def isUSVString(self): return self.inner.isUSVString() def isVoid(self): return self.inner.isVoid() def isSequence(self): return self.inner.isSequence() def isMozMap(self): return self.inner.isMozMap() def isArray(self): return self.inner.isArray() def isDictionary(self): return self.inner.isDictionary() def isArrayBuffer(self): return self.inner.isArrayBuffer() def isArrayBufferView(self): return self.inner.isArrayBufferView() def isSharedArrayBuffer(self): return self.inner.isSharedArrayBuffer() def isSharedArrayBufferView(self): return self.inner.isSharedArrayBufferView() def isTypedArray(self): return self.inner.isTypedArray() def isSharedTypedArray(self): return self.inner.isSharedTypedArray() def isInterface(self): return self.inner.isInterface() def isCallbackInterface(self): return self.inner.isCallbackInterface() def isNonCallbackInterface(self): return self.inner.isNonCallbackInterface() def isComplete(self): return False def complete(self, parentScope): if not self.inner.isComplete(): self.inner = self.inner.complete(parentScope) assert self.inner.isComplete() return self.inner # Do we need a resolveType impl? I don't think it's particularly useful.... def tag(self): return self.inner.tag() def unroll(self): return self.inner.unroll() def isDistinguishableFrom(self, other): return self.inner.isDistinguishableFrom(other) def _getDependentObjects(self): return self.inner._getDependentObjects() class IDLTypedef(IDLObjectWithIdentifier): def __init__(self, location, parentScope, innerType, name): identifier = IDLUnresolvedIdentifier(location, name) IDLObjectWithIdentifier.__init__(self, location, parentScope, identifier) self.innerType = innerType def __str__(self): return "Typedef %s %s" % (self.identifier.name, self.innerType) def finish(self, parentScope): if not self.innerType.isComplete(): self.innerType = self.innerType.complete(parentScope) def validate(self): pass def isTypedef(self): return True def addExtendedAttributes(self, attrs): assert len(attrs) == 0 def _getDependentObjects(self): return self.innerType._getDependentObjects() class IDLWrapperType(IDLType): def __init__(self, location, inner, promiseInnerType=None): IDLType.__init__(self, location, inner.identifier.name) self.inner = inner self._identifier = inner.identifier self.builtin = False assert not promiseInnerType or inner.identifier.name == "Promise" self._promiseInnerType = promiseInnerType def __eq__(self, other): return (isinstance(other, IDLWrapperType) and self._identifier == other._identifier and self.builtin == other.builtin) def __str__(self): return str(self.name) + " (Wrapper)" def nullable(self): return False def isPrimitive(self): return False def isString(self): return False def isByteString(self): return False def isDOMString(self): return False def isUSVString(self): return False def isVoid(self): return False def isSequence(self): return False def isArray(self): return False def isDictionary(self): return isinstance(self.inner, IDLDictionary) def isInterface(self): return (isinstance(self.inner, IDLInterface) or isinstance(self.inner, IDLExternalInterface)) def isCallbackInterface(self): return self.isInterface() and self.inner.isCallback() def isNonCallbackInterface(self): return self.isInterface() and not self.inner.isCallback() def isEnum(self): return isinstance(self.inner, IDLEnum) def isPromise(self): return (isinstance(self.inner, IDLInterface) and self.inner.identifier.name == "Promise") def promiseInnerType(self): assert self.isPromise() return self._promiseInnerType def isSerializable(self): if self.isInterface(): if self.inner.isExternal(): return False return any(m.isMethod() and m.isJsonifier() for m in self.inner.members) elif self.isEnum(): return True elif self.isDictionary(): return all(m.type.isSerializable() for m in self.inner.members) else: raise WebIDLError("IDLWrapperType wraps type %s that we don't know if " "is serializable" % type(self.inner), [self.location]) def resolveType(self, parentScope): assert isinstance(parentScope, IDLScope) self.inner.resolve(parentScope) def isComplete(self): return True def tag(self): if self.isInterface(): return IDLType.Tags.interface elif self.isEnum(): return IDLType.Tags.enum elif self.isDictionary(): return IDLType.Tags.dictionary else: assert False def isDistinguishableFrom(self, other): if self.isPromise(): return False if other.isPromise(): return False if other.isUnion(): # Just forward to the union; it'll deal return other.isDistinguishableFrom(self) assert self.isInterface() or self.isEnum() or self.isDictionary() if self.isEnum(): return (other.isPrimitive() or other.isInterface() or other.isObject() or other.isCallback() or other.isDictionary() or other.isSequence() or other.isMozMap() or other.isArray() or other.isDate()) if self.isDictionary() and other.nullable(): return False if (other.isPrimitive() or other.isString() or other.isEnum() or other.isDate() or other.isSequence()): return True if self.isDictionary(): return other.isNonCallbackInterface() assert self.isInterface() if other.isInterface(): if other.isSpiderMonkeyInterface(): # Just let |other| handle things return other.isDistinguishableFrom(self) assert self.isGeckoInterface() and other.isGeckoInterface() if self.inner.isExternal() or other.unroll().inner.isExternal(): return self != other return (len(self.inner.interfacesBasedOnSelf & other.unroll().inner.interfacesBasedOnSelf) == 0 and (self.isNonCallbackInterface() or other.isNonCallbackInterface())) if (other.isDictionary() or other.isCallback() or other.isMozMap() or other.isArray()): return self.isNonCallbackInterface() # Not much else |other| can be assert other.isObject() return False def isExposedInAllOf(self, exposureSet): if not self.isInterface(): return True iface = self.inner if iface.isExternal(): # Let's say true, though ideally we'd only do this when # exposureSet contains the primary global's name. return True if (self.isPromise() and # Check the internal type not self.promiseInnerType().unroll().isExposedInAllOf(exposureSet)): return False return iface.exposureSet.issuperset(exposureSet) def _getDependentObjects(self): # NB: The codegen for an interface type depends on # a) That the identifier is in fact an interface (as opposed to # a dictionary or something else). # b) The native type of the interface. # If we depend on the interface object we will also depend on # anything the interface depends on which is undesirable. We # considered implementing a dependency just on the interface type # file, but then every modification to an interface would cause this # to be regenerated which is still undesirable. We decided not to # depend on anything, reasoning that: # 1) Changing the concrete type of the interface requires modifying # Bindings.conf, which is still a global dependency. # 2) Changing an interface to a dictionary (or vice versa) with the # same identifier should be incredibly rare. # # On the other hand, if our type is a dictionary, we should # depend on it, because the member types of a dictionary # affect whether a method taking the dictionary as an argument # takes a JSContext* argument or not. if self.isDictionary(): return set([self.inner]) return set() class IDLBuiltinType(IDLType): Types = enum( # The integer types 'byte', 'octet', 'short', 'unsigned_short', 'long', 'unsigned_long', 'long_long', 'unsigned_long_long', # Additional primitive types 'boolean', 'unrestricted_float', 'float', 'unrestricted_double', # IMPORTANT: "double" must be the last primitive type listed 'double', # Other types 'any', 'domstring', 'bytestring', 'usvstring', 'object', 'date', 'void', # Funny stuff 'ArrayBuffer', 'ArrayBufferView', 'SharedArrayBuffer', 'SharedArrayBufferView', 'Int8Array', 'Uint8Array', 'Uint8ClampedArray', 'Int16Array', 'Uint16Array', 'Int32Array', 'Uint32Array', 'Float32Array', 'Float64Array', 'SharedInt8Array', 'SharedUint8Array', 'SharedUint8ClampedArray', 'SharedInt16Array', 'SharedUint16Array', 'SharedInt32Array', 'SharedUint32Array', 'SharedFloat32Array', 'SharedFloat64Array' ) TagLookup = { Types.byte: IDLType.Tags.int8, Types.octet: IDLType.Tags.uint8, Types.short: IDLType.Tags.int16, Types.unsigned_short: IDLType.Tags.uint16, Types.long: IDLType.Tags.int32, Types.unsigned_long: IDLType.Tags.uint32, Types.long_long: IDLType.Tags.int64, Types.unsigned_long_long: IDLType.Tags.uint64, Types.boolean: IDLType.Tags.bool, Types.unrestricted_float: IDLType.Tags.unrestricted_float, Types.float: IDLType.Tags.float, Types.unrestricted_double: IDLType.Tags.unrestricted_double, Types.double: IDLType.Tags.double, Types.any: IDLType.Tags.any, Types.domstring: IDLType.Tags.domstring, Types.bytestring: IDLType.Tags.bytestring, Types.usvstring: IDLType.Tags.usvstring, Types.object: IDLType.Tags.object, Types.date: IDLType.Tags.date, Types.void: IDLType.Tags.void, Types.ArrayBuffer: IDLType.Tags.interface, Types.ArrayBufferView: IDLType.Tags.interface, Types.SharedArrayBuffer: IDLType.Tags.interface, Types.SharedArrayBufferView: IDLType.Tags.interface, Types.Int8Array: IDLType.Tags.interface, Types.Uint8Array: IDLType.Tags.interface, Types.Uint8ClampedArray: IDLType.Tags.interface, Types.Int16Array: IDLType.Tags.interface, Types.Uint16Array: IDLType.Tags.interface, Types.Int32Array: IDLType.Tags.interface, Types.Uint32Array: IDLType.Tags.interface, Types.Float32Array: IDLType.Tags.interface, Types.Float64Array: IDLType.Tags.interface, Types.SharedInt8Array: IDLType.Tags.interface, Types.SharedUint8Array: IDLType.Tags.interface, Types.SharedUint8ClampedArray: IDLType.Tags.interface, Types.SharedInt16Array: IDLType.Tags.interface, Types.SharedUint16Array: IDLType.Tags.interface, Types.SharedInt32Array: IDLType.Tags.interface, Types.SharedUint32Array: IDLType.Tags.interface, Types.SharedFloat32Array: IDLType.Tags.interface, Types.SharedFloat64Array: IDLType.Tags.interface } def __init__(self, location, name, type): IDLType.__init__(self, location, name) self.builtin = True self._typeTag = type def isPrimitive(self): return self._typeTag <= IDLBuiltinType.Types.double def isBoolean(self): return self._typeTag == IDLBuiltinType.Types.boolean def isNumeric(self): return self.isPrimitive() and not self.isBoolean() def isString(self): return (self._typeTag == IDLBuiltinType.Types.domstring or self._typeTag == IDLBuiltinType.Types.bytestring or self._typeTag == IDLBuiltinType.Types.usvstring) def isByteString(self): return self._typeTag == IDLBuiltinType.Types.bytestring def isDOMString(self): return self._typeTag == IDLBuiltinType.Types.domstring def isUSVString(self): return self._typeTag == IDLBuiltinType.Types.usvstring def isInteger(self): return self._typeTag <= IDLBuiltinType.Types.unsigned_long_long def isArrayBuffer(self): return self._typeTag == IDLBuiltinType.Types.ArrayBuffer def isArrayBufferView(self): return self._typeTag == IDLBuiltinType.Types.ArrayBufferView def isSharedArrayBuffer(self): return self._typeTag == IDLBuiltinType.Types.SharedArrayBuffer def isSharedArrayBufferView(self): return self._typeTag == IDLBuiltinType.Types.SharedArrayBufferView def isTypedArray(self): return (self._typeTag >= IDLBuiltinType.Types.Int8Array and self._typeTag <= IDLBuiltinType.Types.Float64Array) def isSharedTypedArray(self): return (self._typeTag >= IDLBuiltinType.Types.SharedInt8Array and self._typeTag <= IDLBuiltinType.Types.SharedFloat64Array) def isInterface(self): # TypedArray things are interface types per the TypedArray spec, # but we handle them as builtins because SpiderMonkey implements # all of it internally. return (self.isArrayBuffer() or self.isArrayBufferView() or self.isSharedArrayBuffer() or self.isSharedArrayBufferView() or self.isTypedArray() or self.isSharedTypedArray()) def isNonCallbackInterface(self): # All the interfaces we can be are non-callback return self.isInterface() def isFloat(self): return (self._typeTag == IDLBuiltinType.Types.float or self._typeTag == IDLBuiltinType.Types.double or self._typeTag == IDLBuiltinType.Types.unrestricted_float or self._typeTag == IDLBuiltinType.Types.unrestricted_double) def isUnrestricted(self): assert self.isFloat() return (self._typeTag == IDLBuiltinType.Types.unrestricted_float or self._typeTag == IDLBuiltinType.Types.unrestricted_double) def isSerializable(self): return self.isPrimitive() or self.isString() or self.isDate() def includesRestrictedFloat(self): return self.isFloat() and not self.isUnrestricted() def tag(self): return IDLBuiltinType.TagLookup[self._typeTag] def isDistinguishableFrom(self, other): if other.isPromise(): return False if other.isUnion(): # Just forward to the union; it'll deal return other.isDistinguishableFrom(self) if self.isBoolean(): return (other.isNumeric() or other.isString() or other.isEnum() or other.isInterface() or other.isObject() or other.isCallback() or other.isDictionary() or other.isSequence() or other.isMozMap() or other.isArray() or other.isDate()) if self.isNumeric(): return (other.isBoolean() or other.isString() or other.isEnum() or other.isInterface() or other.isObject() or other.isCallback() or other.isDictionary() or other.isSequence() or other.isMozMap() or other.isArray() or other.isDate()) if self.isString(): return (other.isPrimitive() or other.isInterface() or other.isObject() or other.isCallback() or other.isDictionary() or other.isSequence() or other.isMozMap() or other.isArray() or other.isDate()) if self.isAny(): # Can't tell "any" apart from anything return False if self.isObject(): return other.isPrimitive() or other.isString() or other.isEnum() if self.isDate(): return (other.isPrimitive() or other.isString() or other.isEnum() or other.isInterface() or other.isCallback() or other.isDictionary() or other.isSequence() or other.isMozMap() or other.isArray()) if self.isVoid(): return not other.isVoid() # Not much else we could be! assert self.isSpiderMonkeyInterface() # Like interfaces, but we know we're not a callback return (other.isPrimitive() or other.isString() or other.isEnum() or other.isCallback() or other.isDictionary() or other.isSequence() or other.isMozMap() or other.isArray() or other.isDate() or (other.isInterface() and ( # ArrayBuffer is distinguishable from everything # that's not an ArrayBuffer or a callback interface (self.isArrayBuffer() and not other.isArrayBuffer()) or (self.isSharedArrayBuffer() and not other.isSharedArrayBuffer()) or # ArrayBufferView is distinguishable from everything # that's not an ArrayBufferView or typed array. (self.isArrayBufferView() and not other.isArrayBufferView() and not other.isTypedArray()) or (self.isSharedArrayBufferView() and not other.isSharedArrayBufferView() and not other.isSharedTypedArray()) or # Typed arrays are distinguishable from everything # except ArrayBufferView and the same type of typed # array (self.isTypedArray() and not other.isArrayBufferView() and not (other.isTypedArray() and other.name == self.name)) or (self.isSharedTypedArray() and not other.isSharedArrayBufferView() and not (other.isSharedTypedArray() and other.name == self.name))))) def _getDependentObjects(self): return set() BuiltinTypes = { IDLBuiltinType.Types.byte: IDLBuiltinType(BuiltinLocation("<builtin type>"), "Byte", IDLBuiltinType.Types.byte), IDLBuiltinType.Types.octet: IDLBuiltinType(BuiltinLocation("<builtin type>"), "Octet", IDLBuiltinType.Types.octet), IDLBuiltinType.Types.short: IDLBuiltinType(BuiltinLocation("<builtin type>"), "Short", IDLBuiltinType.Types.short), IDLBuiltinType.Types.unsigned_short: IDLBuiltinType(BuiltinLocation("<builtin type>"), "UnsignedShort", IDLBuiltinType.Types.unsigned_short), IDLBuiltinType.Types.long: IDLBuiltinType(BuiltinLocation("<builtin type>"), "Long", IDLBuiltinType.Types.long), IDLBuiltinType.Types.unsigned_long: IDLBuiltinType(BuiltinLocation("<builtin type>"), "UnsignedLong", IDLBuiltinType.Types.unsigned_long), IDLBuiltinType.Types.long_long: IDLBuiltinType(BuiltinLocation("<builtin type>"), "LongLong", IDLBuiltinType.Types.long_long), IDLBuiltinType.Types.unsigned_long_long: IDLBuiltinType(BuiltinLocation("<builtin type>"), "UnsignedLongLong", IDLBuiltinType.Types.unsigned_long_long), IDLBuiltinType.Types.boolean: IDLBuiltinType(BuiltinLocation("<builtin type>"), "Boolean", IDLBuiltinType.Types.boolean), IDLBuiltinType.Types.float: IDLBuiltinType(BuiltinLocation("<builtin type>"), "Float", IDLBuiltinType.Types.float), IDLBuiltinType.Types.unrestricted_float: IDLBuiltinType(BuiltinLocation("<builtin type>"), "UnrestrictedFloat", IDLBuiltinType.Types.unrestricted_float), IDLBuiltinType.Types.double: IDLBuiltinType(BuiltinLocation("<builtin type>"), "Double", IDLBuiltinType.Types.double), IDLBuiltinType.Types.unrestricted_double: IDLBuiltinType(BuiltinLocation("<builtin type>"), "UnrestrictedDouble", IDLBuiltinType.Types.unrestricted_double), IDLBuiltinType.Types.any: IDLBuiltinType(BuiltinLocation("<builtin type>"), "Any", IDLBuiltinType.Types.any), IDLBuiltinType.Types.domstring: IDLBuiltinType(BuiltinLocation("<builtin type>"), "String", IDLBuiltinType.Types.domstring), IDLBuiltinType.Types.bytestring: IDLBuiltinType(BuiltinLocation("<builtin type>"), "ByteString", IDLBuiltinType.Types.bytestring), IDLBuiltinType.Types.usvstring: IDLBuiltinType(BuiltinLocation("<builtin type>"), "USVString", IDLBuiltinType.Types.usvstring), IDLBuiltinType.Types.object: IDLBuiltinType(BuiltinLocation("<builtin type>"), "Object", IDLBuiltinType.Types.object), IDLBuiltinType.Types.date: IDLBuiltinType(BuiltinLocation("<builtin type>"), "Date", IDLBuiltinType.Types.date), IDLBuiltinType.Types.void: IDLBuiltinType(BuiltinLocation("<builtin type>"), "Void", IDLBuiltinType.Types.void), IDLBuiltinType.Types.ArrayBuffer: IDLBuiltinType(BuiltinLocation("<builtin type>"), "ArrayBuffer", IDLBuiltinType.Types.ArrayBuffer), IDLBuiltinType.Types.ArrayBufferView: IDLBuiltinType(BuiltinLocation("<builtin type>"), "ArrayBufferView", IDLBuiltinType.Types.ArrayBufferView), IDLBuiltinType.Types.SharedArrayBuffer: IDLBuiltinType(BuiltinLocation("<builtin type>"), "SharedArrayBuffer", IDLBuiltinType.Types.SharedArrayBuffer), IDLBuiltinType.Types.SharedArrayBufferView: IDLBuiltinType(BuiltinLocation("<builtin type>"), "SharedArrayBufferView", IDLBuiltinType.Types.SharedArrayBufferView), IDLBuiltinType.Types.Int8Array: IDLBuiltinType(BuiltinLocation("<builtin type>"), "Int8Array", IDLBuiltinType.Types.Int8Array), IDLBuiltinType.Types.Uint8Array: IDLBuiltinType(BuiltinLocation("<builtin type>"), "Uint8Array", IDLBuiltinType.Types.Uint8Array), IDLBuiltinType.Types.Uint8ClampedArray: IDLBuiltinType(BuiltinLocation("<builtin type>"), "Uint8ClampedArray", IDLBuiltinType.Types.Uint8ClampedArray), IDLBuiltinType.Types.Int16Array: IDLBuiltinType(BuiltinLocation("<builtin type>"), "Int16Array", IDLBuiltinType.Types.Int16Array), IDLBuiltinType.Types.Uint16Array: IDLBuiltinType(BuiltinLocation("<builtin type>"), "Uint16Array", IDLBuiltinType.Types.Uint16Array), IDLBuiltinType.Types.Int32Array: IDLBuiltinType(BuiltinLocation("<builtin type>"), "Int32Array", IDLBuiltinType.Types.Int32Array), IDLBuiltinType.Types.Uint32Array: IDLBuiltinType(BuiltinLocation("<builtin type>"), "Uint32Array", IDLBuiltinType.Types.Uint32Array), IDLBuiltinType.Types.Float32Array: IDLBuiltinType(BuiltinLocation("<builtin type>"), "Float32Array", IDLBuiltinType.Types.Float32Array), IDLBuiltinType.Types.Float64Array: IDLBuiltinType(BuiltinLocation("<builtin type>"), "Float64Array", IDLBuiltinType.Types.Float64Array), IDLBuiltinType.Types.SharedInt8Array: IDLBuiltinType(BuiltinLocation("<builtin type>"), "SharedInt8Array", IDLBuiltinType.Types.SharedInt8Array), IDLBuiltinType.Types.SharedUint8Array: IDLBuiltinType(BuiltinLocation("<builtin type>"), "SharedUint8Array", IDLBuiltinType.Types.SharedUint8Array), IDLBuiltinType.Types.SharedUint8ClampedArray: IDLBuiltinType(BuiltinLocation("<builtin type>"), "SharedUint8ClampedArray", IDLBuiltinType.Types.SharedUint8ClampedArray), IDLBuiltinType.Types.SharedInt16Array: IDLBuiltinType(BuiltinLocation("<builtin type>"), "SharedInt16Array", IDLBuiltinType.Types.SharedInt16Array), IDLBuiltinType.Types.SharedUint16Array: IDLBuiltinType(BuiltinLocation("<builtin type>"), "SharedUint16Array", IDLBuiltinType.Types.SharedUint16Array), IDLBuiltinType.Types.SharedInt32Array: IDLBuiltinType(BuiltinLocation("<builtin type>"), "SharedInt32Array", IDLBuiltinType.Types.SharedInt32Array), IDLBuiltinType.Types.SharedUint32Array: IDLBuiltinType(BuiltinLocation("<builtin type>"), "SharedUint32Array", IDLBuiltinType.Types.SharedUint32Array), IDLBuiltinType.Types.SharedFloat32Array: IDLBuiltinType(BuiltinLocation("<builtin type>"), "SharedFloat32Array", IDLBuiltinType.Types.SharedFloat32Array), IDLBuiltinType.Types.SharedFloat64Array: IDLBuiltinType(BuiltinLocation("<builtin type>"), "SharedFloat64Array", IDLBuiltinType.Types.SharedFloat64Array) } integerTypeSizes = { IDLBuiltinType.Types.byte: (-128, 127), IDLBuiltinType.Types.octet: (0, 255), IDLBuiltinType.Types.short: (-32768, 32767), IDLBuiltinType.Types.unsigned_short: (0, 65535), IDLBuiltinType.Types.long: (-2147483648, 2147483647), IDLBuiltinType.Types.unsigned_long: (0, 4294967295), IDLBuiltinType.Types.long_long: (-9223372036854775808, 9223372036854775807), IDLBuiltinType.Types.unsigned_long_long: (0, 18446744073709551615) } def matchIntegerValueToType(value): for type, extremes in integerTypeSizes.items(): (min, max) = extremes if value <= max and value >= min: return BuiltinTypes[type] return None class IDLValue(IDLObject): def __init__(self, location, type, value): IDLObject.__init__(self, location) self.type = type assert isinstance(type, IDLType) self.value = value def coerceToType(self, type, location): if type == self.type: return self # Nothing to do # We first check for unions to ensure that even if the union is nullable # we end up with the right flat member type, not the union's type. if type.isUnion(): # We use the flat member types here, because if we have a nullable # member type, or a nested union, we want the type the value # actually coerces to, not the nullable or nested union type. for subtype in type.unroll().flatMemberTypes: try: coercedValue = self.coerceToType(subtype, location) # Create a new IDLValue to make sure that we have the # correct float/double type. This is necessary because we # use the value's type when it is a default value of a # union, and the union cares about the exact float type. return IDLValue(self.location, subtype, coercedValue.value) except: pass # If the type allows null, rerun this matching on the inner type, except # nullable enums. We handle those specially, because we want our # default string values to stay strings even when assigned to a nullable # enum. elif type.nullable() and not type.isEnum(): innerValue = self.coerceToType(type.inner, location) return IDLValue(self.location, type, innerValue.value) elif self.type.isInteger() and type.isInteger(): # We're both integer types. See if we fit. (min, max) = integerTypeSizes[type._typeTag] if self.value <= max and self.value >= min: # Promote return IDLValue(self.location, type, self.value) else: raise WebIDLError("Value %s is out of range for type %s." % (self.value, type), [location]) elif self.type.isInteger() and type.isFloat(): # Convert an integer literal into float if -2**24 <= self.value <= 2**24: return IDLValue(self.location, type, float(self.value)) else: raise WebIDLError("Converting value %s to %s will lose precision." % (self.value, type), [location]) elif self.type.isString() and type.isEnum(): # Just keep our string, but make sure it's a valid value for this enum enum = type.unroll().inner if self.value not in enum.values(): raise WebIDLError("'%s' is not a valid default value for enum %s" % (self.value, enum.identifier.name), [location, enum.location]) return self elif self.type.isFloat() and type.isFloat(): if (not type.isUnrestricted() and (self.value == float("inf") or self.value == float("-inf") or math.isnan(self.value))): raise WebIDLError("Trying to convert unrestricted value %s to non-unrestricted" % self.value, [location]); return IDLValue(self.location, type, self.value) elif self.type.isString() and type.isUSVString(): # Allow USVStrings to use default value just like # DOMString. No coercion is required in this case as Codegen.py # treats USVString just like DOMString, but with an # extra normalization step. assert self.type.isDOMString() return self raise WebIDLError("Cannot coerce type %s to type %s." % (self.type, type), [location]) def _getDependentObjects(self): return set() class IDLNullValue(IDLObject): def __init__(self, location): IDLObject.__init__(self, location) self.type = None self.value = None def coerceToType(self, type, location): if (not isinstance(type, IDLNullableType) and not (type.isUnion() and type.hasNullableType) and not (type.isUnion() and type.hasDictionaryType()) and not type.isDictionary() and not type.isAny()): raise WebIDLError("Cannot coerce null value to type %s." % type, [location]) nullValue = IDLNullValue(self.location) if type.isUnion() and not type.nullable() and type.hasDictionaryType(): # We're actually a default value for the union's dictionary member. # Use its type. for t in type.flatMemberTypes: if t.isDictionary(): nullValue.type = t return nullValue nullValue.type = type return nullValue def _getDependentObjects(self): return set() class IDLEmptySequenceValue(IDLObject): def __init__(self, location): IDLObject.__init__(self, location) self.type = None self.value = None def coerceToType(self, type, location): if type.isUnion(): # We use the flat member types here, because if we have a nullable # member type, or a nested union, we want the type the value # actually coerces to, not the nullable or nested union type. for subtype in type.unroll().flatMemberTypes: try: return self.coerceToType(subtype, location) except: pass if not type.isSequence(): raise WebIDLError("Cannot coerce empty sequence value to type %s." % type, [location]) emptySequenceValue = IDLEmptySequenceValue(self.location) emptySequenceValue.type = type return emptySequenceValue def _getDependentObjects(self): return set() class IDLUndefinedValue(IDLObject): def __init__(self, location): IDLObject.__init__(self, location) self.type = None self.value = None def coerceToType(self, type, location): if not type.isAny(): raise WebIDLError("Cannot coerce undefined value to type %s." % type, [location]) undefinedValue = IDLUndefinedValue(self.location) undefinedValue.type = type return undefinedValue def _getDependentObjects(self): return set() class IDLInterfaceMember(IDLObjectWithIdentifier, IDLExposureMixins): Tags = enum( 'Const', 'Attr', 'Method', 'MaplikeOrSetlike' ) Special = enum( 'Static', 'Stringifier' ) AffectsValues = ("Nothing", "Everything") DependsOnValues = ("Nothing", "DOMState", "DeviceState", "Everything") def __init__(self, location, identifier, tag): IDLObjectWithIdentifier.__init__(self, location, None, identifier) IDLExposureMixins.__init__(self, location) self.tag = tag self._extendedAttrDict = {} def isMethod(self): return self.tag == IDLInterfaceMember.Tags.Method def isAttr(self): return self.tag == IDLInterfaceMember.Tags.Attr def isConst(self): return self.tag == IDLInterfaceMember.Tags.Const def isMaplikeOrSetlike(self): return self.tag == IDLInterfaceMember.Tags.MaplikeOrSetlike def addExtendedAttributes(self, attrs): for attr in attrs: self.handleExtendedAttribute(attr) attrlist = attr.listValue() self._extendedAttrDict[attr.identifier()] = attrlist if len(attrlist) else True def handleExtendedAttribute(self, attr): pass def getExtendedAttribute(self, name): return self._extendedAttrDict.get(name, None) def finish(self, scope): # We better be exposed _somewhere_. if (len(self._exposureGlobalNames) == 0): print self.identifier.name assert len(self._exposureGlobalNames) != 0 IDLExposureMixins.finish(self, scope) def validate(self): if (self.getExtendedAttribute("Pref") and self.exposureSet != set([self._globalScope.primaryGlobalName])): raise WebIDLError("[Pref] used on an interface member that is not " "%s-only" % self._globalScope.primaryGlobalName, [self.location]) for attribute in ["CheckAnyPermissions", "CheckAllPermissions"]: if (self.getExtendedAttribute(attribute) and self.exposureSet != set([self._globalScope.primaryGlobalName])): raise WebIDLError("[%s] used on an interface member that is " "not %s-only" % (attribute, self.parentScope.primaryGlobalName), [self.location]) if self.isAttr() or self.isMethod(): if self.affects == "Everything" and self.dependsOn != "Everything": raise WebIDLError("Interface member is flagged as affecting " "everything but not depending on everything. " "That seems rather unlikely.", [self.location]) if self.getExtendedAttribute("NewObject"): if self.dependsOn == "Nothing" or self.dependsOn == "DOMState": raise WebIDLError("A [NewObject] method is not idempotent, " "so it has to depend on something other than DOM state.", [self.location]) def _setDependsOn(self, dependsOn): if self.dependsOn != "Everything": raise WebIDLError("Trying to specify multiple different DependsOn, " "Pure, or Constant extended attributes for " "attribute", [self.location]) if dependsOn not in IDLInterfaceMember.DependsOnValues: raise WebIDLError("Invalid [DependsOn=%s] on attribute" % dependsOn, [self.location]) self.dependsOn = dependsOn def _setAffects(self, affects): if self.affects != "Everything": raise WebIDLError("Trying to specify multiple different Affects, " "Pure, or Constant extended attributes for " "attribute", [self.location]) if affects not in IDLInterfaceMember.AffectsValues: raise WebIDLError("Invalid [Affects=%s] on attribute" % dependsOn, [self.location]) self.affects = affects def _addAlias(self, alias): if alias in self.aliases: raise WebIDLError("Duplicate [Alias=%s] on attribute" % alias, [self.location]) self.aliases.append(alias) # MaplikeOrSetlike adds a trait to an interface, like map or iteration # functions. To handle them while still getting all of the generated binding # code taken care of, we treat them as macros that are expanded into members # based on parsed values. class IDLMaplikeOrSetlike(IDLInterfaceMember): MaplikeOrSetlikeTypes = enum( 'maplike', 'setlike' ) def __init__(self, location, identifier, maplikeOrSetlikeType, readonly, keyType, valueType): IDLInterfaceMember.__init__(self, location, identifier, IDLInterfaceMember.Tags.MaplikeOrSetlike) assert isinstance(keyType, IDLType) assert isinstance(valueType, IDLType) self.maplikeOrSetlikeType = maplikeOrSetlikeType self.readonly = readonly self.keyType = keyType self.valueType = valueType self.slotIndex = None self.disallowedMemberNames = [] self.disallowedNonMethodNames = [] # When generating JSAPI access code, we need to know the backing object # type prefix to create the correct function. Generate here for reuse. if self.isMaplike(): self.prefix = 'Map' elif self.isSetlike(): self.prefix = 'Set' def __str__(self): return "declared '%s' with key '%s'" % (self.maplikeOrSetlikeType, self.keyType) def isMaplike(self): return self.maplikeOrSetlikeType == "maplike" def isSetlike(self): return self.maplikeOrSetlikeType == "setlike" def checkCollisions(self, members, isAncestor): for member in members: # Check that there are no disallowed members if (member.identifier.name in self.disallowedMemberNames and not ((member.isMethod() and member.isMaplikeOrSetlikeMethod()) or (member.isAttr() and member.isMaplikeOrSetlikeAttr()))): raise WebIDLError("Member '%s' conflicts " "with reserved %s name." % (member.identifier.name, self.maplikeOrSetlikeType), [self.location, member.location]) # Check that there are no disallowed non-method members if (isAncestor or (member.isAttr() or member.isConst()) and member.identifier.name in self.disallowedNonMethodNames): raise WebIDLError("Member '%s' conflicts " "with reserved %s method." % (member.identifier.name, self.maplikeOrSetlikeType), [self.location, member.location]) def expand(self, members, isJSImplemented): """ In order to take advantage of all of the method machinery in Codegen, we generate our functions as if they were part of the interface specification during parsing. """ def addMethod(name, allowExistingOperations, returnType, args=[], chromeOnly=False, isPure=False, affectsNothing=False): """ Create an IDLMethod based on the parameters passed in. chromeOnly is only True for read-only js implemented classes, to implement underscore prefixed convenience functions would otherwise not be available, unlike the case of C++ bindings. isPure is only True for idempotent functions, so it is not valid for things like keys, values, etc. that return a new object every time. """ # Only add name to lists for collision checks if it's not chrome # only. if chromeOnly: name = "__" + name else: if not allowExistingOperations: self.disallowedMemberNames.append(name) else: self.disallowedNonMethodNames.append(name) # If allowExistingOperations is True, and another operation exists # with the same name as the one we're trying to add, don't add the # maplike/setlike operation. However, if the operation is static, # then fail by way of creating the function, which will cause a # naming conflict, per the spec. if allowExistingOperations: for m in members: if m.identifier.name == name and m.isMethod() and not m.isStatic(): return method = IDLMethod(self.location, IDLUnresolvedIdentifier(self.location, name, allowDoubleUnderscore=chromeOnly), returnType, args, maplikeOrSetlike=self) # We need to be able to throw from declaration methods method.addExtendedAttributes( [IDLExtendedAttribute(self.location, ("Throws",))]) if chromeOnly: method.addExtendedAttributes( [IDLExtendedAttribute(self.location, ("ChromeOnly",))]) if isPure: method.addExtendedAttributes( [IDLExtendedAttribute(self.location, ("Pure",))]) # Following attributes are used for keys/values/entries. Can't mark # them pure, since they return a new object each time they are run. if affectsNothing: method.addExtendedAttributes( [IDLExtendedAttribute(self.location, ("DependsOn", "Everything")), IDLExtendedAttribute(self.location, ("Affects", "Nothing"))]) members.append(method) # Both maplike and setlike have a size attribute members.append(IDLAttribute(self.location, IDLUnresolvedIdentifier(BuiltinLocation("<auto-generated-identifier>"), "size"), BuiltinTypes[IDLBuiltinType.Types.unsigned_long], True, maplikeOrSetlike=self)) self.reserved_ro_names = ["size"] # object entries() addMethod("entries", False, BuiltinTypes[IDLBuiltinType.Types.object], affectsNothing=True) # object keys() addMethod("keys", False, BuiltinTypes[IDLBuiltinType.Types.object], affectsNothing=True) # object values() addMethod("values", False, BuiltinTypes[IDLBuiltinType.Types.object], affectsNothing=True) # void forEach(callback(valueType, keyType), thisVal) foreachArguments = [IDLArgument(self.location, IDLUnresolvedIdentifier(BuiltinLocation("<auto-generated-identifier>"), "callback"), BuiltinTypes[IDLBuiltinType.Types.object]), IDLArgument(self.location, IDLUnresolvedIdentifier(BuiltinLocation("<auto-generated-identifier>"), "thisArg"), BuiltinTypes[IDLBuiltinType.Types.any], optional=True)] addMethod("forEach", False, BuiltinTypes[IDLBuiltinType.Types.void], foreachArguments) def getKeyArg(): return IDLArgument(self.location, IDLUnresolvedIdentifier(self.location, "key"), self.keyType) # boolean has(keyType key) addMethod("has", False, BuiltinTypes[IDLBuiltinType.Types.boolean], [getKeyArg()], isPure=True) if not self.readonly: # void clear() addMethod("clear", True, BuiltinTypes[IDLBuiltinType.Types.void], []) # boolean delete(keyType key) addMethod("delete", True, BuiltinTypes[IDLBuiltinType.Types.boolean], [getKeyArg()]) # Always generate underscored functions (e.g. __add, __clear) for js # implemented interfaces as convenience functions. if isJSImplemented: # void clear() addMethod("clear", True, BuiltinTypes[IDLBuiltinType.Types.void], [], chromeOnly=True) # boolean delete(keyType key) addMethod("delete", True, BuiltinTypes[IDLBuiltinType.Types.boolean], [getKeyArg()], chromeOnly=True) if self.isSetlike(): if not self.readonly: # Add returns the set object it just added to. # object add(keyType key) addMethod("add", True, BuiltinTypes[IDLBuiltinType.Types.object], [getKeyArg()]) if isJSImplemented: addMethod("add", True, BuiltinTypes[IDLBuiltinType.Types.object], [getKeyArg()], chromeOnly=True) return # If we get this far, we're a maplike declaration. # valueType get(keyType key) # # Note that instead of the value type, we're using any here. The # validity checks should happen as things are inserted into the map, # and using any as the return type makes code generation much simpler. # # TODO: Bug 1155340 may change this to use specific type to provide # more info to JIT. addMethod("get", False, BuiltinTypes[IDLBuiltinType.Types.any], [getKeyArg()], isPure=True) def getValueArg(): return IDLArgument(self.location, IDLUnresolvedIdentifier(self.location, "value"), self.valueType) if not self.readonly: addMethod("set", True, BuiltinTypes[IDLBuiltinType.Types.object], [getKeyArg(), getValueArg()]) if isJSImplemented: addMethod("set", True, BuiltinTypes[IDLBuiltinType.Types.object], [getKeyArg(), getValueArg()], chromeOnly=True) def resolve(self, parentScope): self.keyType.resolveType(parentScope) self.valueType.resolveType(parentScope) def finish(self, scope): IDLInterfaceMember.finish(self, scope) if not self.keyType.isComplete(): t = self.keyType.complete(scope) assert not isinstance(t, IDLUnresolvedType) assert not isinstance(t, IDLTypedefType) assert not isinstance(t.name, IDLUnresolvedIdentifier) self.keyType = t if not self.valueType.isComplete(): t = self.valueType.complete(scope) assert not isinstance(t, IDLUnresolvedType) assert not isinstance(t, IDLTypedefType) assert not isinstance(t.name, IDLUnresolvedIdentifier) self.valueType = t def validate(self): IDLInterfaceMember.validate(self) def handleExtendedAttribute(self, attr): IDLInterfaceMember.handleExtendedAttribute(self, attr) def _getDependentObjects(self): return set([self.keyType, self.valueType]) class IDLConst(IDLInterfaceMember): def __init__(self, location, identifier, type, value): IDLInterfaceMember.__init__(self, location, identifier, IDLInterfaceMember.Tags.Const) assert isinstance(type, IDLType) if type.isDictionary(): raise WebIDLError("A constant cannot be of a dictionary type", [self.location]) self.type = type self.value = value if identifier.name == "prototype": raise WebIDLError("The identifier of a constant must not be 'prototype'", [location]) def __str__(self): return "'%s' const '%s'" % (self.type, self.identifier) def finish(self, scope): IDLInterfaceMember.finish(self, scope) if not self.type.isComplete(): type = self.type.complete(scope) if not type.isPrimitive() and not type.isString(): locations = [self.type.location, type.location] try: locations.append(type.inner.location) except: pass raise WebIDLError("Incorrect type for constant", locations) self.type = type # The value might not match the type coercedValue = self.value.coerceToType(self.type, self.location) assert coercedValue self.value = coercedValue def validate(self): IDLInterfaceMember.validate(self) def handleExtendedAttribute(self, attr): identifier = attr.identifier() if identifier == "Exposed": convertExposedAttrToGlobalNameSet(attr, self._exposureGlobalNames) elif (identifier == "Pref" or identifier == "ChromeOnly" or identifier == "Func" or identifier == "AvailableIn" or identifier == "CheckAnyPermissions" or identifier == "CheckAllPermissions"): # Known attributes that we don't need to do anything with here pass else: raise WebIDLError("Unknown extended attribute %s on constant" % identifier, [attr.location]) IDLInterfaceMember.handleExtendedAttribute(self, attr) def _getDependentObjects(self): return set([self.type, self.value]) class IDLAttribute(IDLInterfaceMember): def __init__(self, location, identifier, type, readonly, inherit=False, static=False, stringifier=False, maplikeOrSetlike=None): IDLInterfaceMember.__init__(self, location, identifier, IDLInterfaceMember.Tags.Attr) assert isinstance(type, IDLType) self.type = type self.readonly = readonly self.inherit = inherit self.static = static self.lenientThis = False self._unforgeable = False self.stringifier = stringifier self.enforceRange = False self.clamp = False self.slotIndex = None assert maplikeOrSetlike is None or isinstance(maplikeOrSetlike, IDLMaplikeOrSetlike) self.maplikeOrSetlike = maplikeOrSetlike self.dependsOn = "Everything" self.affects = "Everything" if static and identifier.name == "prototype": raise WebIDLError("The identifier of a static attribute must not be 'prototype'", [location]) if readonly and inherit: raise WebIDLError("An attribute cannot be both 'readonly' and 'inherit'", [self.location]) def isStatic(self): return self.static def __str__(self): return "'%s' attribute '%s'" % (self.type, self.identifier) def finish(self, scope): IDLInterfaceMember.finish(self, scope) if not self.type.isComplete(): t = self.type.complete(scope) assert not isinstance(t, IDLUnresolvedType) assert not isinstance(t, IDLTypedefType) assert not isinstance(t.name, IDLUnresolvedIdentifier) self.type = t if self.type.isDictionary() and not self.getExtendedAttribute("Cached"): raise WebIDLError("An attribute cannot be of a dictionary type", [self.location]) if self.type.isSequence() and not self.getExtendedAttribute("Cached"): raise WebIDLError("A non-cached attribute cannot be of a sequence " "type", [self.location]) if self.type.isMozMap() and not self.getExtendedAttribute("Cached"): raise WebIDLError("A non-cached attribute cannot be of a MozMap " "type", [self.location]) if self.type.isUnion(): for f in self.type.unroll().flatMemberTypes: if f.isDictionary(): raise WebIDLError("An attribute cannot be of a union " "type if one of its member types (or " "one of its member types's member " "types, and so on) is a dictionary " "type", [self.location, f.location]) if f.isSequence(): raise WebIDLError("An attribute cannot be of a union " "type if one of its member types (or " "one of its member types's member " "types, and so on) is a sequence " "type", [self.location, f.location]) if f.isMozMap(): raise WebIDLError("An attribute cannot be of a union " "type if one of its member types (or " "one of its member types's member " "types, and so on) is a MozMap " "type", [self.location, f.location]) if not self.type.isInterface() and self.getExtendedAttribute("PutForwards"): raise WebIDLError("An attribute with [PutForwards] must have an " "interface type as its type", [self.location]) if not self.type.isInterface() and self.getExtendedAttribute("SameObject"): raise WebIDLError("An attribute with [SameObject] must have an " "interface type as its type", [self.location]) def validate(self): IDLInterfaceMember.validate(self) if ((self.getExtendedAttribute("Cached") or self.getExtendedAttribute("StoreInSlot")) and not self.affects == "Nothing"): raise WebIDLError("Cached attributes and attributes stored in " "slots must be Constant or Pure or " "Affects=Nothing, since the getter won't always " "be called.", [self.location]) if self.getExtendedAttribute("Frozen"): if (not self.type.isSequence() and not self.type.isDictionary() and not self.type.isMozMap()): raise WebIDLError("[Frozen] is only allowed on " "sequence-valued, dictionary-valued, and " "MozMap-valued attributes", [self.location]) if not self.type.unroll().isExposedInAllOf(self.exposureSet): raise WebIDLError("Attribute returns a type that is not exposed " "everywhere where the attribute is exposed", [self.location]) def handleExtendedAttribute(self, attr): identifier = attr.identifier() if identifier == "SetterThrows" and self.readonly: raise WebIDLError("Readonly attributes must not be flagged as " "[SetterThrows]", [self.location]) elif (((identifier == "Throws" or identifier == "GetterThrows") and self.getExtendedAttribute("StoreInSlot")) or (identifier == "StoreInSlot" and (self.getExtendedAttribute("Throws") or self.getExtendedAttribute("GetterThrows")))): raise WebIDLError("Throwing things can't be [StoreInSlot]", [attr.location]) elif identifier == "LenientThis": if not attr.noArguments(): raise WebIDLError("[LenientThis] must take no arguments", [attr.location]) if self.isStatic(): raise WebIDLError("[LenientThis] is only allowed on non-static " "attributes", [attr.location, self.location]) if self.getExtendedAttribute("CrossOriginReadable"): raise WebIDLError("[LenientThis] is not allowed in combination " "with [CrossOriginReadable]", [attr.location, self.location]) if self.getExtendedAttribute("CrossOriginWritable"): raise WebIDLError("[LenientThis] is not allowed in combination " "with [CrossOriginWritable]", [attr.location, self.location]) self.lenientThis = True elif identifier == "Unforgeable": if self.isStatic(): raise WebIDLError("[Unforgeable] is only allowed on non-static " "attributes", [attr.location, self.location]) self._unforgeable = True elif identifier == "SameObject" and not self.readonly: raise WebIDLError("[SameObject] only allowed on readonly attributes", [attr.location, self.location]) elif identifier == "Constant" and not self.readonly: raise WebIDLError("[Constant] only allowed on readonly attributes", [attr.location, self.location]) elif identifier == "PutForwards": if not self.readonly: raise WebIDLError("[PutForwards] is only allowed on readonly " "attributes", [attr.location, self.location]) if self.isStatic(): raise WebIDLError("[PutForwards] is only allowed on non-static " "attributes", [attr.location, self.location]) if self.getExtendedAttribute("Replaceable") is not None: raise WebIDLError("[PutForwards] and [Replaceable] can't both " "appear on the same attribute", [attr.location, self.location]) if not attr.hasValue(): raise WebIDLError("[PutForwards] takes an identifier", [attr.location, self.location]) elif identifier == "Replaceable": if not attr.noArguments(): raise WebIDLError("[Replaceable] must take no arguments", [attr.location]) if not self.readonly: raise WebIDLError("[Replaceable] is only allowed on readonly " "attributes", [attr.location, self.location]) if self.isStatic(): raise WebIDLError("[Replaceable] is only allowed on non-static " "attributes", [attr.location, self.location]) if self.getExtendedAttribute("PutForwards") is not None: raise WebIDLError("[PutForwards] and [Replaceable] can't both " "appear on the same attribute", [attr.location, self.location]) elif identifier == "LenientFloat": if self.readonly: raise WebIDLError("[LenientFloat] used on a readonly attribute", [attr.location, self.location]) if not self.type.includesRestrictedFloat(): raise WebIDLError("[LenientFloat] used on an attribute with a " "non-restricted-float type", [attr.location, self.location]) elif identifier == "EnforceRange": if self.readonly: raise WebIDLError("[EnforceRange] used on a readonly attribute", [attr.location, self.location]) self.enforceRange = True elif identifier == "Clamp": if self.readonly: raise WebIDLError("[Clamp] used on a readonly attribute", [attr.location, self.location]) self.clamp = True elif identifier == "StoreInSlot": if self.getExtendedAttribute("Cached"): raise WebIDLError("[StoreInSlot] and [Cached] must not be " "specified on the same attribute", [attr.location, self.location]) elif identifier == "Cached": if self.getExtendedAttribute("StoreInSlot"): raise WebIDLError("[Cached] and [StoreInSlot] must not be " "specified on the same attribute", [attr.location, self.location]) elif (identifier == "CrossOriginReadable" or identifier == "CrossOriginWritable"): if not attr.noArguments() and identifier == "CrossOriginReadable": raise WebIDLError("[%s] must take no arguments" % identifier, [attr.location]) if self.isStatic(): raise WebIDLError("[%s] is only allowed on non-static " "attributes" % identifier, [attr.location, self.location]) if self.getExtendedAttribute("LenientThis"): raise WebIDLError("[LenientThis] is not allowed in combination " "with [%s]" % identifier, [attr.location, self.location]) elif identifier == "Exposed": convertExposedAttrToGlobalNameSet(attr, self._exposureGlobalNames) elif identifier == "Pure": if not attr.noArguments(): raise WebIDLError("[Pure] must take no arguments", [attr.location]) self._setDependsOn("DOMState") self._setAffects("Nothing") elif identifier == "Constant" or identifier == "SameObject": if not attr.noArguments(): raise WebIDLError("[%s] must take no arguments" % identifier, [attr.location]) self._setDependsOn("Nothing") self._setAffects("Nothing") elif identifier == "Affects": if not attr.hasValue(): raise WebIDLError("[Affects] takes an identifier", [attr.location]) self._setAffects(attr.value()) elif identifier == "DependsOn": if not attr.hasValue(): raise WebIDLError("[DependsOn] takes an identifier", [attr.location]) if (attr.value() != "Everything" and attr.value() != "DOMState" and not self.readonly): raise WebIDLError("[DependsOn=%s] only allowed on " "readonly attributes" % attr.value(), [attr.location, self.location]) self._setDependsOn(attr.value()) elif (identifier == "Pref" or identifier == "Deprecated" or identifier == "SetterThrows" or identifier == "Throws" or identifier == "GetterThrows" or identifier == "ChromeOnly" or identifier == "Func" or identifier == "Frozen" or identifier == "AvailableIn" or identifier == "NewObject" or identifier == "UnsafeInPrerendering" or identifier == "CheckAnyPermissions" or identifier == "CheckAllPermissions" or identifier == "BinaryName"): # Known attributes that we don't need to do anything with here pass else: raise WebIDLError("Unknown extended attribute %s on attribute" % identifier, [attr.location]) IDLInterfaceMember.handleExtendedAttribute(self, attr) def resolve(self, parentScope): assert isinstance(parentScope, IDLScope) self.type.resolveType(parentScope) IDLObjectWithIdentifier.resolve(self, parentScope) def addExtendedAttributes(self, attrs): attrs = self.checkForStringHandlingExtendedAttributes(attrs) IDLInterfaceMember.addExtendedAttributes(self, attrs) def hasLenientThis(self): return self.lenientThis def isMaplikeOrSetlikeAttr(self): """ True if this attribute was generated from an interface with maplike/setlike (e.g. this is the size attribute for maplike/setlike) """ return self.maplikeOrSetlike is not None def isUnforgeable(self): return self._unforgeable def _getDependentObjects(self): return set([self.type]) class IDLArgument(IDLObjectWithIdentifier): def __init__(self, location, identifier, type, optional=False, defaultValue=None, variadic=False, dictionaryMember=False): IDLObjectWithIdentifier.__init__(self, location, None, identifier) assert isinstance(type, IDLType) self.type = type self.optional = optional self.defaultValue = defaultValue self.variadic = variadic self.dictionaryMember = dictionaryMember self._isComplete = False self.enforceRange = False self.clamp = False self._allowTreatNonCallableAsNull = False assert not variadic or optional assert not variadic or not defaultValue def addExtendedAttributes(self, attrs): attrs = self.checkForStringHandlingExtendedAttributes( attrs, isDictionaryMember=self.dictionaryMember, isOptional=self.optional) for attribute in attrs: identifier = attribute.identifier() if identifier == "Clamp": if not attribute.noArguments(): raise WebIDLError("[Clamp] must take no arguments", [attribute.location]) if self.enforceRange: raise WebIDLError("[EnforceRange] and [Clamp] are mutually exclusive", [self.location]) self.clamp = True elif identifier == "EnforceRange": if not attribute.noArguments(): raise WebIDLError("[EnforceRange] must take no arguments", [attribute.location]) if self.clamp: raise WebIDLError("[EnforceRange] and [Clamp] are mutually exclusive", [self.location]) self.enforceRange = True elif identifier == "TreatNonCallableAsNull": self._allowTreatNonCallableAsNull = True else: raise WebIDLError("Unhandled extended attribute on %s" % ("a dictionary member" if self.dictionaryMember else "an argument"), [attribute.location]) def isComplete(self): return self._isComplete def complete(self, scope): if self._isComplete: return self._isComplete = True if not self.type.isComplete(): type = self.type.complete(scope) assert not isinstance(type, IDLUnresolvedType) assert not isinstance(type, IDLTypedefType) assert not isinstance(type.name, IDLUnresolvedIdentifier) self.type = type if ((self.type.isDictionary() or self.type.isUnion() and self.type.unroll().hasDictionaryType()) and self.optional and not self.defaultValue and not self.variadic): # Default optional non-variadic dictionaries to null, # for simplicity, so the codegen doesn't have to special-case this. self.defaultValue = IDLNullValue(self.location) elif self.type.isAny(): assert (self.defaultValue is None or isinstance(self.defaultValue, IDLNullValue)) # optional 'any' values always have a default value if self.optional and not self.defaultValue and not self.variadic: # Set the default value to undefined, for simplicity, so the # codegen doesn't have to special-case this. self.defaultValue = IDLUndefinedValue(self.location) # Now do the coercing thing; this needs to happen after the # above creation of a default value. if self.defaultValue: self.defaultValue = self.defaultValue.coerceToType(self.type, self.location) assert self.defaultValue def allowTreatNonCallableAsNull(self): return self._allowTreatNonCallableAsNull def _getDependentObjects(self): deps = set([self.type]) if self.defaultValue: deps.add(self.defaultValue) return deps def canHaveMissingValue(self): return self.optional and not self.defaultValue class IDLCallback(IDLObjectWithScope): def __init__(self, location, parentScope, identifier, returnType, arguments): assert isinstance(returnType, IDLType) self._returnType = returnType # Clone the list self._arguments = list(arguments) IDLObjectWithScope.__init__(self, location, parentScope, identifier) for (returnType, arguments) in self.signatures(): for argument in arguments: argument.resolve(self) self._treatNonCallableAsNull = False self._treatNonObjectAsNull = False def module(self): return self.location.filename().split('/')[-1].split('.webidl')[0] + 'Binding' def isCallback(self): return True def signatures(self): return [(self._returnType, self._arguments)] def finish(self, scope): if not self._returnType.isComplete(): type = self._returnType.complete(scope) assert not isinstance(type, IDLUnresolvedType) assert not isinstance(type, IDLTypedefType) assert not isinstance(type.name, IDLUnresolvedIdentifier) self._returnType = type for argument in self._arguments: if argument.type.isComplete(): continue type = argument.type.complete(scope) assert not isinstance(type, IDLUnresolvedType) assert not isinstance(type, IDLTypedefType) assert not isinstance(type.name, IDLUnresolvedIdentifier) argument.type = type def validate(self): pass def addExtendedAttributes(self, attrs): unhandledAttrs = [] for attr in attrs: if attr.identifier() == "TreatNonCallableAsNull": self._treatNonCallableAsNull = True elif attr.identifier() == "TreatNonObjectAsNull": self._treatNonObjectAsNull = True else: unhandledAttrs.append(attr) if self._treatNonCallableAsNull and self._treatNonObjectAsNull: raise WebIDLError("Cannot specify both [TreatNonCallableAsNull] " "and [TreatNonObjectAsNull]", [self.location]) if len(unhandledAttrs) != 0: IDLType.addExtendedAttributes(self, unhandledAttrs) def _getDependentObjects(self): return set([self._returnType] + self._arguments) class IDLCallbackType(IDLType): def __init__(self, location, callback): IDLType.__init__(self, location, callback.identifier.name) self.callback = callback def isCallback(self): return True def tag(self): return IDLType.Tags.callback def isDistinguishableFrom(self, other): if other.isPromise(): return False if other.isUnion(): # Just forward to the union; it'll deal return other.isDistinguishableFrom(self) return (other.isPrimitive() or other.isString() or other.isEnum() or other.isNonCallbackInterface() or other.isDate() or other.isSequence()) def _getDependentObjects(self): return self.callback._getDependentObjects() class IDLMethodOverload: """ A class that represents a single overload of a WebIDL method. This is not quite the same as an element of the "effective overload set" in the spec, because separate IDLMethodOverloads are not created based on arguments being optional. Rather, when multiple methods have the same name, there is an IDLMethodOverload for each one, all hanging off an IDLMethod representing the full set of overloads. """ def __init__(self, returnType, arguments, location): self.returnType = returnType # Clone the list of arguments, just in case self.arguments = list(arguments) self.location = location def _getDependentObjects(self): deps = set(self.arguments) deps.add(self.returnType) return deps class IDLMethod(IDLInterfaceMember, IDLScope): Special = enum( 'Getter', 'Setter', 'Creator', 'Deleter', 'LegacyCaller', base=IDLInterfaceMember.Special ) TypeSuffixModifier = enum( 'None', 'QMark', 'Brackets' ) NamedOrIndexed = enum( 'Neither', 'Named', 'Indexed' ) def __init__(self, location, identifier, returnType, arguments, static=False, getter=False, setter=False, creator=False, deleter=False, specialType=NamedOrIndexed.Neither, legacycaller=False, stringifier=False, jsonifier=False, maplikeOrSetlike=None): # REVIEW: specialType is NamedOrIndexed -- wow, this is messed up. IDLInterfaceMember.__init__(self, location, identifier, IDLInterfaceMember.Tags.Method) self._hasOverloads = False assert isinstance(returnType, IDLType) # self._overloads is a list of IDLMethodOverloads self._overloads = [IDLMethodOverload(returnType, arguments, location)] assert isinstance(static, bool) self._static = static assert isinstance(getter, bool) self._getter = getter assert isinstance(setter, bool) self._setter = setter assert isinstance(creator, bool) self._creator = creator assert isinstance(deleter, bool) self._deleter = deleter assert isinstance(legacycaller, bool) self._legacycaller = legacycaller assert isinstance(stringifier, bool) self._stringifier = stringifier assert isinstance(jsonifier, bool) self._jsonifier = jsonifier assert maplikeOrSetlike is None or isinstance(maplikeOrSetlike, IDLMaplikeOrSetlike) self.maplikeOrSetlike = maplikeOrSetlike self._specialType = specialType self._unforgeable = False self.dependsOn = "Everything" self.affects = "Everything" self.aliases = [] if static and identifier.name == "prototype": raise WebIDLError("The identifier of a static operation must not be 'prototype'", [location]) self.assertSignatureConstraints() def __str__(self): return "Method '%s'" % self.identifier def assertSignatureConstraints(self): if self._getter or self._deleter: assert len(self._overloads) == 1 overload = self._overloads[0] arguments = overload.arguments assert len(arguments) == 1 assert (arguments[0].type == BuiltinTypes[IDLBuiltinType.Types.domstring] or arguments[0].type == BuiltinTypes[IDLBuiltinType.Types.unsigned_long]) assert not arguments[0].optional and not arguments[0].variadic assert not self._getter or not overload.returnType.isVoid() if self._setter or self._creator: assert len(self._overloads) == 1 arguments = self._overloads[0].arguments assert len(arguments) == 2 assert (arguments[0].type == BuiltinTypes[IDLBuiltinType.Types.domstring] or arguments[0].type == BuiltinTypes[IDLBuiltinType.Types.unsigned_long]) assert not arguments[0].optional and not arguments[0].variadic assert not arguments[1].optional and not arguments[1].variadic if self._stringifier: assert len(self._overloads) == 1 overload = self._overloads[0] assert len(overload.arguments) == 0 assert overload.returnType == BuiltinTypes[IDLBuiltinType.Types.domstring] if self._jsonifier: assert len(self._overloads) == 1 overload = self._overloads[0] assert len(overload.arguments) == 0 assert overload.returnType == BuiltinTypes[IDLBuiltinType.Types.object] def isStatic(self): return self._static def isGetter(self): return self._getter def isSetter(self): return self._setter def isCreator(self): return self._creator def isDeleter(self): return self._deleter def isNamed(self): assert (self._specialType == IDLMethod.NamedOrIndexed.Named or self._specialType == IDLMethod.NamedOrIndexed.Indexed) return self._specialType == IDLMethod.NamedOrIndexed.Named def isIndexed(self): assert (self._specialType == IDLMethod.NamedOrIndexed.Named or self._specialType == IDLMethod.NamedOrIndexed.Indexed) return self._specialType == IDLMethod.NamedOrIndexed.Indexed def isLegacycaller(self): return self._legacycaller def isStringifier(self): return self._stringifier def isJsonifier(self): return self._jsonifier def isMaplikeOrSetlikeMethod(self): """ True if this method was generated as part of a maplike/setlike/etc interface (e.g. has/get methods) """ return self.maplikeOrSetlike is not None def hasOverloads(self): return self._hasOverloads def isIdentifierLess(self): """ True if the method name started with __, and if the method is not a maplike/setlike method. Interfaces with maplike/setlike will generate methods starting with __ for chrome only backing object access in JS implemented interfaces, so while these functions use what is considered an non-identifier name, they actually DO have an identifier. """ return (self.identifier.name[:2] == "__" and not self.isMaplikeOrSetlikeMethod()) def resolve(self, parentScope): assert isinstance(parentScope, IDLScope) IDLObjectWithIdentifier.resolve(self, parentScope) IDLScope.__init__(self, self.location, parentScope, self.identifier) for (returnType, arguments) in self.signatures(): for argument in arguments: argument.resolve(self) def addOverload(self, method): assert len(method._overloads) == 1 if self._extendedAttrDict != method ._extendedAttrDict: raise WebIDLError("Extended attributes differ on different " "overloads of %s" % method.identifier, [self.location, method.location]) self._overloads.extend(method._overloads) self._hasOverloads = True if self.isStatic() != method.isStatic(): raise WebIDLError("Overloaded identifier %s appears with different values of the 'static' attribute" % method.identifier, [method.location]) if self.isLegacycaller() != method.isLegacycaller(): raise WebIDLError("Overloaded identifier %s appears with different values of the 'legacycaller' attribute" % method.identifier, [method.location]) # Can't overload special things! assert not self.isGetter() assert not method.isGetter() assert not self.isSetter() assert not method.isSetter() assert not self.isCreator() assert not method.isCreator() assert not self.isDeleter() assert not method.isDeleter() assert not self.isStringifier() assert not method.isStringifier() assert not self.isJsonifier() assert not method.isJsonifier() return self def signatures(self): return [(overload.returnType, overload.arguments) for overload in self._overloads] def finish(self, scope): IDLInterfaceMember.finish(self, scope) for overload in self._overloads: returnType = overload.returnType if not returnType.isComplete(): returnType = returnType.complete(scope) assert not isinstance(returnType, IDLUnresolvedType) assert not isinstance(returnType, IDLTypedefType) assert not isinstance(returnType.name, IDLUnresolvedIdentifier) overload.returnType = returnType for argument in overload.arguments: if not argument.isComplete(): argument.complete(scope) assert argument.type.isComplete() # Now compute various information that will be used by the # WebIDL overload resolution algorithm. self.maxArgCount = max(len(s[1]) for s in self.signatures()) self.allowedArgCounts = [i for i in range(self.maxArgCount+1) if len(self.signaturesForArgCount(i)) != 0] def validate(self): IDLInterfaceMember.validate(self) # Make sure our overloads are properly distinguishable and don't have # different argument types before the distinguishing args. for argCount in self.allowedArgCounts: possibleOverloads = self.overloadsForArgCount(argCount) if len(possibleOverloads) == 1: continue distinguishingIndex = self.distinguishingIndexForArgCount(argCount) for idx in range(distinguishingIndex): firstSigType = possibleOverloads[0].arguments[idx].type for overload in possibleOverloads[1:]: if overload.arguments[idx].type != firstSigType: raise WebIDLError( "Signatures for method '%s' with %d arguments have " "different types of arguments at index %d, which " "is before distinguishing index %d" % (self.identifier.name, argCount, idx, distinguishingIndex), [self.location, overload.location]) overloadWithPromiseReturnType = None overloadWithoutPromiseReturnType = None for overload in self._overloads: returnType = overload.returnType if not returnType.unroll().isExposedInAllOf(self.exposureSet): raise WebIDLError("Overload returns a type that is not exposed " "everywhere where the method is exposed", [overload.location]) variadicArgument = None arguments = overload.arguments for (idx, argument) in enumerate(arguments): assert argument.type.isComplete() if ((argument.type.isDictionary() and argument.type.inner.canBeEmpty())or (argument.type.isUnion() and argument.type.unroll().hasPossiblyEmptyDictionaryType())): # Optional dictionaries and unions containing optional # dictionaries at the end of the list or followed by # optional arguments must be optional. if (not argument.optional and all(arg.optional for arg in arguments[idx+1:])): raise WebIDLError("Dictionary argument or union " "argument containing a dictionary " "not followed by a required argument " "must be optional", [argument.location]) # An argument cannot be a Nullable Dictionary if argument.type.nullable(): raise WebIDLError("An argument cannot be a nullable " "dictionary or nullable union " "containing a dictionary", [argument.location]) # Only the last argument can be variadic if variadicArgument: raise WebIDLError("Variadic argument is not last argument", [variadicArgument.location]) if argument.variadic: variadicArgument = argument if returnType.isPromise(): overloadWithPromiseReturnType = overload else: overloadWithoutPromiseReturnType = overload # Make sure either all our overloads return Promises or none do if overloadWithPromiseReturnType and overloadWithoutPromiseReturnType: raise WebIDLError("We have overloads with both Promise and " "non-Promise return types", [overloadWithPromiseReturnType.location, overloadWithoutPromiseReturnType.location]) if overloadWithPromiseReturnType and self._legacycaller: raise WebIDLError("May not have a Promise return type for a " "legacycaller.", [overloadWithPromiseReturnType.location]) if self.getExtendedAttribute("StaticClassOverride") and not \ (self.identifier.scope.isJSImplemented() and self.isStatic()): raise WebIDLError("StaticClassOverride can be applied to static" " methods on JS-implemented classes only.", [self.location]) def overloadsForArgCount(self, argc): return [overload for overload in self._overloads if len(overload.arguments) == argc or (len(overload.arguments) > argc and all(arg.optional for arg in overload.arguments[argc:])) or (len(overload.arguments) < argc and len(overload.arguments) > 0 and overload.arguments[-1].variadic)] def signaturesForArgCount(self, argc): return [(overload.returnType, overload.arguments) for overload in self.overloadsForArgCount(argc)] def locationsForArgCount(self, argc): return [overload.location for overload in self.overloadsForArgCount(argc)] def distinguishingIndexForArgCount(self, argc): def isValidDistinguishingIndex(idx, signatures): for (firstSigIndex, (firstRetval, firstArgs)) in enumerate(signatures[:-1]): for (secondRetval, secondArgs) in signatures[firstSigIndex+1:]: if idx < len(firstArgs): firstType = firstArgs[idx].type else: assert(firstArgs[-1].variadic) firstType = firstArgs[-1].type if idx < len(secondArgs): secondType = secondArgs[idx].type else: assert(secondArgs[-1].variadic) secondType = secondArgs[-1].type if not firstType.isDistinguishableFrom(secondType): return False return True signatures = self.signaturesForArgCount(argc) for idx in range(argc): if isValidDistinguishingIndex(idx, signatures): return idx # No valid distinguishing index. Time to throw locations = self.locationsForArgCount(argc) raise WebIDLError("Signatures with %d arguments for method '%s' are not " "distinguishable" % (argc, self.identifier.name), locations) def handleExtendedAttribute(self, attr): identifier = attr.identifier() if identifier == "GetterThrows": raise WebIDLError("Methods must not be flagged as " "[GetterThrows]", [attr.location, self.location]) elif identifier == "SetterThrows": raise WebIDLError("Methods must not be flagged as " "[SetterThrows]", [attr.location, self.location]) elif identifier == "Unforgeable": if self.isStatic(): raise WebIDLError("[Unforgeable] is only allowed on non-static " "methods", [attr.location, self.location]) self._unforgeable = True elif identifier == "SameObject": raise WebIDLError("Methods must not be flagged as [SameObject]", [attr.location, self.location]) elif identifier == "Constant": raise WebIDLError("Methods must not be flagged as [Constant]", [attr.location, self.location]) elif identifier == "PutForwards": raise WebIDLError("Only attributes support [PutForwards]", [attr.location, self.location]) elif identifier == "LenientFloat": # This is called before we've done overload resolution assert len(self.signatures()) == 1 sig = self.signatures()[0] if not sig[0].isVoid(): raise WebIDLError("[LenientFloat] used on a non-void method", [attr.location, self.location]) if not any(arg.type.includesRestrictedFloat() for arg in sig[1]): raise WebIDLError("[LenientFloat] used on an operation with no " "restricted float type arguments", [attr.location, self.location]) elif identifier == "Exposed": convertExposedAttrToGlobalNameSet(attr, self._exposureGlobalNames) elif (identifier == "CrossOriginCallable" or identifier == "WebGLHandlesContextLoss"): # Known no-argument attributes. if not attr.noArguments(): raise WebIDLError("[%s] must take no arguments" % identifier, [attr.location]) elif identifier == "Pure": if not attr.noArguments(): raise WebIDLError("[Pure] must take no arguments", [attr.location]) self._setDependsOn("DOMState") self._setAffects("Nothing") elif identifier == "Affects": if not attr.hasValue(): raise WebIDLError("[Affects] takes an identifier", [attr.location]) self._setAffects(attr.value()) elif identifier == "DependsOn": if not attr.hasValue(): raise WebIDLError("[DependsOn] takes an identifier", [attr.location]) self._setDependsOn(attr.value()) elif identifier == "Alias": if not attr.hasValue(): raise WebIDLError("[Alias] takes an identifier or string", [attr.location]) self._addAlias(attr.value()) elif (identifier == "Throws" or identifier == "NewObject" or identifier == "ChromeOnly" or identifier == "UnsafeInPrerendering" or identifier == "Pref" or identifier == "Deprecated" or identifier == "Func" or identifier == "AvailableIn" or identifier == "CheckAnyPermissions" or identifier == "CheckAllPermissions" or identifier == "BinaryName" or identifier == "MethodIdentityTestable" or identifier == "StaticClassOverride"): # Known attributes that we don't need to do anything with here pass else: raise WebIDLError("Unknown extended attribute %s on method" % identifier, [attr.location]) IDLInterfaceMember.handleExtendedAttribute(self, attr) def returnsPromise(self): return self._overloads[0].returnType.isPromise() def isUnforgeable(self): return self._unforgeable def _getDependentObjects(self): deps = set() for overload in self._overloads: deps.update(overload._getDependentObjects()) return deps class IDLImplementsStatement(IDLObject): def __init__(self, location, implementor, implementee): IDLObject.__init__(self, location) self.implementor = implementor self.implementee = implementee self._finished = False def finish(self, scope): if self._finished: return assert(isinstance(self.implementor, IDLIdentifierPlaceholder)) assert(isinstance(self.implementee, IDLIdentifierPlaceholder)) implementor = self.implementor.finish(scope) implementee = self.implementee.finish(scope) # NOTE: we depend on not setting self.implementor and # self.implementee here to keep track of the original # locations. if not isinstance(implementor, IDLInterface): raise WebIDLError("Left-hand side of 'implements' is not an " "interface", [self.implementor.location]) if implementor.isCallback(): raise WebIDLError("Left-hand side of 'implements' is a callback " "interface", [self.implementor.location]) if not isinstance(implementee, IDLInterface): raise WebIDLError("Right-hand side of 'implements' is not an " "interface", [self.implementee.location]) if implementee.isCallback(): raise WebIDLError("Right-hand side of 'implements' is a callback " "interface", [self.implementee.location]) implementor.addImplementedInterface(implementee) self.implementor = implementor self.implementee = implementee def validate(self): pass def addExtendedAttributes(self, attrs): assert len(attrs) == 0 class IDLExtendedAttribute(IDLObject): """ A class to represent IDL extended attributes so we can give them locations """ def __init__(self, location, tuple): IDLObject.__init__(self, location) self._tuple = tuple def identifier(self): return self._tuple[0] def noArguments(self): return len(self._tuple) == 1 def hasValue(self): return len(self._tuple) >= 2 and isinstance(self._tuple[1], str) def value(self): assert(self.hasValue()) return self._tuple[1] def hasArgs(self): return (len(self._tuple) == 2 and isinstance(self._tuple[1], list) or len(self._tuple) == 3) def args(self): assert(self.hasArgs()) # Our args are our last element return self._tuple[-1] def listValue(self): """ Backdoor for storing random data in _extendedAttrDict """ return list(self._tuple)[1:] # Parser class Tokenizer(object): tokens = [ "INTEGER", "FLOATLITERAL", "IDENTIFIER", "STRING", "WHITESPACE", "OTHER" ] def t_FLOATLITERAL(self, t): r'(-?(([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)([Ee][+-]?[0-9]+)?|[0-9]+[Ee][+-]?[0-9]+|Infinity))|NaN' t.value = float(t.value) return t def t_INTEGER(self, t): r'-?(0([0-7]+|[Xx][0-9A-Fa-f]+)?|[1-9][0-9]*)' try: # Can't use int(), because that doesn't handle octal properly. t.value = parseInt(t.value) except: raise WebIDLError("Invalid integer literal", [Location(lexer=self.lexer, lineno=self.lexer.lineno, lexpos=self.lexer.lexpos, filename=self._filename)]) return t def t_IDENTIFIER(self, t): r'[A-Z_a-z][0-9A-Z_a-z-]*' t.type = self.keywords.get(t.value, 'IDENTIFIER') return t def t_STRING(self, t): r'"[^"]*"' t.value = t.value[1:-1] return t def t_WHITESPACE(self, t): r'[\t\n\r ]+|[\t\n\r ]*((//[^\n]*|/\*.*?\*/)[\t\n\r ]*)+' pass def t_ELLIPSIS(self, t): r'\.\.\.' t.type = self.keywords.get(t.value) return t def t_OTHER(self, t): r'[^\t\n\r 0-9A-Z_a-z]' t.type = self.keywords.get(t.value, 'OTHER') return t keywords = { "module": "MODULE", "interface": "INTERFACE", "partial": "PARTIAL", "dictionary": "DICTIONARY", "exception": "EXCEPTION", "enum": "ENUM", "callback": "CALLBACK", "typedef": "TYPEDEF", "implements": "IMPLEMENTS", "const": "CONST", "null": "NULL", "true": "TRUE", "false": "FALSE", "serializer": "SERIALIZER", "stringifier": "STRINGIFIER", "jsonifier": "JSONIFIER", "unrestricted": "UNRESTRICTED", "attribute": "ATTRIBUTE", "readonly": "READONLY", "inherit": "INHERIT", "static": "STATIC", "getter": "GETTER", "setter": "SETTER", "creator": "CREATOR", "deleter": "DELETER", "legacycaller": "LEGACYCALLER", "optional": "OPTIONAL", "...": "ELLIPSIS", "::": "SCOPE", "Date": "DATE", "DOMString": "DOMSTRING", "ByteString": "BYTESTRING", "USVString": "USVSTRING", "any": "ANY", "boolean": "BOOLEAN", "byte": "BYTE", "double": "DOUBLE", "float": "FLOAT", "long": "LONG", "object": "OBJECT", "octet": "OCTET", "Promise": "PROMISE", "required": "REQUIRED", "sequence": "SEQUENCE", "MozMap": "MOZMAP", "short": "SHORT", "unsigned": "UNSIGNED", "void": "VOID", ":": "COLON", ";": "SEMICOLON", "{": "LBRACE", "}": "RBRACE", "(": "LPAREN", ")": "RPAREN", "[": "LBRACKET", "]": "RBRACKET", "?": "QUESTIONMARK", ",": "COMMA", "=": "EQUALS", "<": "LT", ">": "GT", "ArrayBuffer": "ARRAYBUFFER", "SharedArrayBuffer": "SHAREDARRAYBUFFER", "or": "OR", "maplike": "MAPLIKE", "setlike": "SETLIKE" } tokens.extend(keywords.values()) def t_error(self, t): raise WebIDLError("Unrecognized Input", [Location(lexer=self.lexer, lineno=self.lexer.lineno, lexpos=self.lexer.lexpos, filename=self.filename)]) def __init__(self, outputdir, lexer=None): if lexer: self.lexer = lexer else: self.lexer = lex.lex(object=self, outputdir=outputdir, lextab='webidllex', reflags=re.DOTALL) class SqueakyCleanLogger(object): errorWhitelist = [ # Web IDL defines the WHITESPACE token, but doesn't actually # use it ... so far. "Token 'WHITESPACE' defined, but not used", # And that means we have an unused token "There is 1 unused token", # Web IDL defines a OtherOrComma rule that's only used in # ExtendedAttributeInner, which we don't use yet. "Rule 'OtherOrComma' defined, but not used", # And an unused rule "There is 1 unused rule", # And the OtherOrComma grammar symbol is unreachable. "Symbol 'OtherOrComma' is unreachable", # Which means the Other symbol is unreachable. "Symbol 'Other' is unreachable", ] def __init__(self): self.errors = [] def debug(self, msg, *args, **kwargs): pass info = debug def warning(self, msg, *args, **kwargs): if msg == "%s:%d: Rule '%s' defined, but not used": # Munge things so we don't have to hardcode filenames and # line numbers in our whitelist. whitelistmsg = "Rule '%s' defined, but not used" whitelistargs = args[2:] else: whitelistmsg = msg whitelistargs = args if (whitelistmsg % whitelistargs) not in SqueakyCleanLogger.errorWhitelist: self.errors.append(msg % args) error = warning def reportGrammarErrors(self): if self.errors: raise WebIDLError("\n".join(self.errors), []) class Parser(Tokenizer): def getLocation(self, p, i): return Location(self.lexer, p.lineno(i), p.lexpos(i), self._filename) def globalScope(self): return self._globalScope # The p_Foo functions here must match the WebIDL spec's grammar. # It's acceptable to split things at '|' boundaries. def p_Definitions(self, p): """ Definitions : ExtendedAttributeList Definition Definitions """ if p[2]: p[0] = [p[2]] p[2].addExtendedAttributes(p[1]) else: assert not p[1] p[0] = [] p[0].extend(p[3]) def p_DefinitionsEmpty(self, p): """ Definitions : """ p[0] = [] def p_Definition(self, p): """ Definition : CallbackOrInterface | PartialInterface | Dictionary | Exception | Enum | Typedef | ImplementsStatement """ p[0] = p[1] assert p[1] # We might not have implemented something ... def p_CallbackOrInterfaceCallback(self, p): """ CallbackOrInterface : CALLBACK CallbackRestOrInterface """ if p[2].isInterface(): assert isinstance(p[2], IDLInterface) p[2].setCallback(True) p[0] = p[2] def p_CallbackOrInterfaceInterface(self, p): """ CallbackOrInterface : Interface """ p[0] = p[1] def p_CallbackRestOrInterface(self, p): """ CallbackRestOrInterface : CallbackRest | Interface """ assert p[1] p[0] = p[1] def p_Interface(self, p): """ Interface : INTERFACE IDENTIFIER Inheritance LBRACE InterfaceMembers RBRACE SEMICOLON """ location = self.getLocation(p, 1) identifier = IDLUnresolvedIdentifier(self.getLocation(p, 2), p[2]) members = p[5] parent = p[3] try: existingObj = self.globalScope()._lookupIdentifier(identifier) if existingObj: p[0] = existingObj if not isinstance(p[0], IDLInterface): raise WebIDLError("Interface has the same name as " "non-interface object", [location, p[0].location]) p[0].setNonPartial(location, parent, members) return except Exception, ex: if isinstance(ex, WebIDLError): raise ex pass p[0] = IDLInterface(location, self.globalScope(), identifier, parent, members, isKnownNonPartial=True) def p_InterfaceForwardDecl(self, p): """ Interface : INTERFACE IDENTIFIER SEMICOLON """ location = self.getLocation(p, 1) identifier = IDLUnresolvedIdentifier(self.getLocation(p, 2), p[2]) try: if self.globalScope()._lookupIdentifier(identifier): p[0] = self.globalScope()._lookupIdentifier(identifier) if not isinstance(p[0], IDLExternalInterface): raise WebIDLError("Name collision between external " "interface declaration for identifier " "%s and %s" % (identifier.name, p[0]), [location, p[0].location]) return except Exception, ex: if isinstance(ex, WebIDLError): raise ex pass p[0] = IDLExternalInterface(location, self.globalScope(), identifier) def p_PartialInterface(self, p): """ PartialInterface : PARTIAL INTERFACE IDENTIFIER LBRACE InterfaceMembers RBRACE SEMICOLON """ location = self.getLocation(p, 2) identifier = IDLUnresolvedIdentifier(self.getLocation(p, 3), p[3]) members = p[5] nonPartialInterface = None try: nonPartialInterface = self.globalScope()._lookupIdentifier(identifier) if nonPartialInterface: if not isinstance(nonPartialInterface, IDLInterface): raise WebIDLError("Partial interface has the same name as " "non-interface object", [location, nonPartialInterface.location]) except Exception, ex: if isinstance(ex, WebIDLError): raise ex pass if not nonPartialInterface: nonPartialInterface = IDLInterface(location, self.globalScope(), identifier, None, [], isKnownNonPartial=False) partialInterface = IDLPartialInterface(location, identifier, members, nonPartialInterface) p[0] = partialInterface def p_Inheritance(self, p): """ Inheritance : COLON ScopedName """ p[0] = IDLIdentifierPlaceholder(self.getLocation(p, 2), p[2]) def p_InheritanceEmpty(self, p): """ Inheritance : """ pass def p_InterfaceMembers(self, p): """ InterfaceMembers : ExtendedAttributeList InterfaceMember InterfaceMembers """ p[0] = [p[2]] if p[2] else [] assert not p[1] or p[2] p[2].addExtendedAttributes(p[1]) p[0].extend(p[3]) def p_InterfaceMembersEmpty(self, p): """ InterfaceMembers : """ p[0] = [] def p_InterfaceMember(self, p): """ InterfaceMember : Const | AttributeOrOperationOrMaplikeOrSetlike """ p[0] = p[1] def p_Dictionary(self, p): """ Dictionary : DICTIONARY IDENTIFIER Inheritance LBRACE DictionaryMembers RBRACE SEMICOLON """ location = self.getLocation(p, 1) identifier = IDLUnresolvedIdentifier(self.getLocation(p, 2), p[2]) members = p[5] p[0] = IDLDictionary(location, self.globalScope(), identifier, p[3], members) def p_DictionaryMembers(self, p): """ DictionaryMembers : ExtendedAttributeList DictionaryMember DictionaryMembers | """ if len(p) == 1: # We're at the end of the list p[0] = [] return # Add our extended attributes p[2].addExtendedAttributes(p[1]) p[0] = [p[2]] p[0].extend(p[3]) def p_DictionaryMember(self, p): """ DictionaryMember : Required Type IDENTIFIER Default SEMICOLON """ # These quack a lot like optional arguments, so just treat them that way. t = p[2] assert isinstance(t, IDLType) identifier = IDLUnresolvedIdentifier(self.getLocation(p, 3), p[3]) defaultValue = p[4] optional = not p[1] if not optional and defaultValue: raise WebIDLError("Required dictionary members can't have a default value.", [self.getLocation(p, 4)]) p[0] = IDLArgument(self.getLocation(p, 3), identifier, t, optional=optional, defaultValue=defaultValue, variadic=False, dictionaryMember=True) def p_Default(self, p): """ Default : EQUALS DefaultValue | """ if len(p) > 1: p[0] = p[2] else: p[0] = None def p_DefaultValue(self, p): """ DefaultValue : ConstValue | LBRACKET RBRACKET """ if len(p) == 2: p[0] = p[1] else: assert len(p) == 3 # Must be [] p[0] = IDLEmptySequenceValue(self.getLocation(p, 1)) def p_Exception(self, p): """ Exception : EXCEPTION IDENTIFIER Inheritance LBRACE ExceptionMembers RBRACE SEMICOLON """ pass def p_Enum(self, p): """ Enum : ENUM IDENTIFIER LBRACE EnumValueList RBRACE SEMICOLON """ location = self.getLocation(p, 1) identifier = IDLUnresolvedIdentifier(self.getLocation(p, 2), p[2]) values = p[4] assert values p[0] = IDLEnum(location, self.globalScope(), identifier, values) def p_EnumValueList(self, p): """ EnumValueList : STRING EnumValueListComma """ p[0] = [p[1]] p[0].extend(p[2]) def p_EnumValueListComma(self, p): """ EnumValueListComma : COMMA EnumValueListString """ p[0] = p[2] def p_EnumValueListCommaEmpty(self, p): """ EnumValueListComma : """ p[0] = [] def p_EnumValueListString(self, p): """ EnumValueListString : STRING EnumValueListComma """ p[0] = [p[1]] p[0].extend(p[2]) def p_EnumValueListStringEmpty(self, p): """ EnumValueListString : """ p[0] = [] def p_CallbackRest(self, p): """ CallbackRest : IDENTIFIER EQUALS ReturnType LPAREN ArgumentList RPAREN SEMICOLON """ identifier = IDLUnresolvedIdentifier(self.getLocation(p, 1), p[1]) p[0] = IDLCallback(self.getLocation(p, 1), self.globalScope(), identifier, p[3], p[5]) def p_ExceptionMembers(self, p): """ ExceptionMembers : ExtendedAttributeList ExceptionMember ExceptionMembers | """ pass def p_Typedef(self, p): """ Typedef : TYPEDEF Type IDENTIFIER SEMICOLON """ typedef = IDLTypedef(self.getLocation(p, 1), self.globalScope(), p[2], p[3]) p[0] = typedef def p_ImplementsStatement(self, p): """ ImplementsStatement : ScopedName IMPLEMENTS ScopedName SEMICOLON """ assert(p[2] == "implements") implementor = IDLIdentifierPlaceholder(self.getLocation(p, 1), p[1]) implementee = IDLIdentifierPlaceholder(self.getLocation(p, 3), p[3]) p[0] = IDLImplementsStatement(self.getLocation(p, 1), implementor, implementee) def p_Const(self, p): """ Const : CONST ConstType IDENTIFIER EQUALS ConstValue SEMICOLON """ location = self.getLocation(p, 1) type = p[2] identifier = IDLUnresolvedIdentifier(self.getLocation(p, 3), p[3]) value = p[5] p[0] = IDLConst(location, identifier, type, value) def p_ConstValueBoolean(self, p): """ ConstValue : BooleanLiteral """ location = self.getLocation(p, 1) booleanType = BuiltinTypes[IDLBuiltinType.Types.boolean] p[0] = IDLValue(location, booleanType, p[1]) def p_ConstValueInteger(self, p): """ ConstValue : INTEGER """ location = self.getLocation(p, 1) # We don't know ahead of time what type the integer literal is. # Determine the smallest type it could possibly fit in and use that. integerType = matchIntegerValueToType(p[1]) if integerType is None: raise WebIDLError("Integer literal out of range", [location]) p[0] = IDLValue(location, integerType, p[1]) def p_ConstValueFloat(self, p): """ ConstValue : FLOATLITERAL """ location = self.getLocation(p, 1) p[0] = IDLValue(location, BuiltinTypes[IDLBuiltinType.Types.unrestricted_float], p[1]) def p_ConstValueString(self, p): """ ConstValue : STRING """ location = self.getLocation(p, 1) stringType = BuiltinTypes[IDLBuiltinType.Types.domstring] p[0] = IDLValue(location, stringType, p[1]) def p_ConstValueNull(self, p): """ ConstValue : NULL """ p[0] = IDLNullValue(self.getLocation(p, 1)) def p_BooleanLiteralTrue(self, p): """ BooleanLiteral : TRUE """ p[0] = True def p_BooleanLiteralFalse(self, p): """ BooleanLiteral : FALSE """ p[0] = False def p_AttributeOrOperationOrMaplikeOrSetlike(self, p): """ AttributeOrOperationOrMaplikeOrSetlike : Attribute | Maplike | Setlike | Operation """ p[0] = p[1] def p_Setlike(self, p): """ Setlike : ReadOnly SETLIKE LT Type GT SEMICOLON """ readonly = p[1] maplikeOrSetlikeType = p[2] location = self.getLocation(p, 2) identifier = IDLUnresolvedIdentifier(location, "__setlike", allowDoubleUnderscore=True) keyType = p[4] valueType = keyType p[0] = IDLMaplikeOrSetlike(location, identifier, maplikeOrSetlikeType, readonly, keyType, valueType) def p_Maplike(self, p): """ Maplike : ReadOnly MAPLIKE LT Type COMMA Type GT SEMICOLON """ readonly = p[1] maplikeOrSetlikeType = p[2] location = self.getLocation(p, 2) identifier = IDLUnresolvedIdentifier(location, "__maplike", allowDoubleUnderscore=True) keyType = p[4] valueType = p[6] p[0] = IDLMaplikeOrSetlike(location, identifier, maplikeOrSetlikeType, readonly, keyType, valueType) def p_AttributeWithQualifier(self, p): """ Attribute : Qualifier AttributeRest """ static = IDLInterfaceMember.Special.Static in p[1] stringifier = IDLInterfaceMember.Special.Stringifier in p[1] (location, identifier, type, readonly) = p[2] p[0] = IDLAttribute(location, identifier, type, readonly, static=static, stringifier=stringifier) def p_AttributeInherited(self, p): """ Attribute : INHERIT AttributeRest """ (location, identifier, type, readonly) = p[2] p[0] = IDLAttribute(location, identifier, type, readonly, inherit=True) def p_Attribute(self, p): """ Attribute : AttributeRest """ (location, identifier, type, readonly) = p[1] p[0] = IDLAttribute(location, identifier, type, readonly, inherit=False) def p_AttributeRest(self, p): """ AttributeRest : ReadOnly ATTRIBUTE Type AttributeName SEMICOLON """ location = self.getLocation(p, 2) readonly = p[1] t = p[3] identifier = IDLUnresolvedIdentifier(self.getLocation(p, 4), p[4]) p[0] = (location, identifier, t, readonly) def p_ReadOnly(self, p): """ ReadOnly : READONLY """ p[0] = True def p_ReadOnlyEmpty(self, p): """ ReadOnly : """ p[0] = False def p_Operation(self, p): """ Operation : Qualifiers OperationRest """ qualifiers = p[1] # Disallow duplicates in the qualifier set if not len(set(qualifiers)) == len(qualifiers): raise WebIDLError("Duplicate qualifiers are not allowed", [self.getLocation(p, 1)]) static = IDLInterfaceMember.Special.Static in p[1] # If static is there that's all that's allowed. This is disallowed # by the parser, so we can assert here. assert not static or len(qualifiers) == 1 stringifier = IDLInterfaceMember.Special.Stringifier in p[1] # If stringifier is there that's all that's allowed. This is disallowed # by the parser, so we can assert here. assert not stringifier or len(qualifiers) == 1 getter = True if IDLMethod.Special.Getter in p[1] else False setter = True if IDLMethod.Special.Setter in p[1] else False creator = True if IDLMethod.Special.Creator in p[1] else False deleter = True if IDLMethod.Special.Deleter in p[1] else False legacycaller = True if IDLMethod.Special.LegacyCaller in p[1] else False if getter or deleter: if setter or creator: raise WebIDLError("getter and deleter are incompatible with setter and creator", [self.getLocation(p, 1)]) (returnType, identifier, arguments) = p[2] assert isinstance(returnType, IDLType) specialType = IDLMethod.NamedOrIndexed.Neither if getter or deleter: if len(arguments) != 1: raise WebIDLError("%s has wrong number of arguments" % ("getter" if getter else "deleter"), [self.getLocation(p, 2)]) argType = arguments[0].type if argType == BuiltinTypes[IDLBuiltinType.Types.domstring]: specialType = IDLMethod.NamedOrIndexed.Named elif argType == BuiltinTypes[IDLBuiltinType.Types.unsigned_long]: specialType = IDLMethod.NamedOrIndexed.Indexed else: raise WebIDLError("%s has wrong argument type (must be DOMString or UnsignedLong)" % ("getter" if getter else "deleter"), [arguments[0].location]) if arguments[0].optional or arguments[0].variadic: raise WebIDLError("%s cannot have %s argument" % ("getter" if getter else "deleter", "optional" if arguments[0].optional else "variadic"), [arguments[0].location]) if getter: if returnType.isVoid(): raise WebIDLError("getter cannot have void return type", [self.getLocation(p, 2)]) if setter or creator: if len(arguments) != 2: raise WebIDLError("%s has wrong number of arguments" % ("setter" if setter else "creator"), [self.getLocation(p, 2)]) argType = arguments[0].type if argType == BuiltinTypes[IDLBuiltinType.Types.domstring]: specialType = IDLMethod.NamedOrIndexed.Named elif argType == BuiltinTypes[IDLBuiltinType.Types.unsigned_long]: specialType = IDLMethod.NamedOrIndexed.Indexed else: raise WebIDLError("%s has wrong argument type (must be DOMString or UnsignedLong)" % ("setter" if setter else "creator"), [arguments[0].location]) if arguments[0].optional or arguments[0].variadic: raise WebIDLError("%s cannot have %s argument" % ("setter" if setter else "creator", "optional" if arguments[0].optional else "variadic"), [arguments[0].location]) if arguments[1].optional or arguments[1].variadic: raise WebIDLError("%s cannot have %s argument" % ("setter" if setter else "creator", "optional" if arguments[1].optional else "variadic"), [arguments[1].location]) if stringifier: if len(arguments) != 0: raise WebIDLError("stringifier has wrong number of arguments", [self.getLocation(p, 2)]) if not returnType.isDOMString(): raise WebIDLError("stringifier must have DOMString return type", [self.getLocation(p, 2)]) # identifier might be None. This is only permitted for special methods. if not identifier: if (not getter and not setter and not creator and not deleter and not legacycaller and not stringifier): raise WebIDLError("Identifier required for non-special methods", [self.getLocation(p, 2)]) location = BuiltinLocation("<auto-generated-identifier>") identifier = IDLUnresolvedIdentifier( location, "__%s%s%s%s%s%s%s" % ("named" if specialType == IDLMethod.NamedOrIndexed.Named else "indexed" if specialType == IDLMethod.NamedOrIndexed.Indexed else "", "getter" if getter else "", "setter" if setter else "", "deleter" if deleter else "", "creator" if creator else "", "legacycaller" if legacycaller else "", "stringifier" if stringifier else ""), allowDoubleUnderscore=True) method = IDLMethod(self.getLocation(p, 2), identifier, returnType, arguments, static=static, getter=getter, setter=setter, creator=creator, deleter=deleter, specialType=specialType, legacycaller=legacycaller, stringifier=stringifier) p[0] = method def p_Stringifier(self, p): """ Operation : STRINGIFIER SEMICOLON """ identifier = IDLUnresolvedIdentifier(BuiltinLocation("<auto-generated-identifier>"), "__stringifier", allowDoubleUnderscore=True) method = IDLMethod(self.getLocation(p, 1), identifier, returnType=BuiltinTypes[IDLBuiltinType.Types.domstring], arguments=[], stringifier=True) p[0] = method def p_Jsonifier(self, p): """ Operation : JSONIFIER SEMICOLON """ identifier = IDLUnresolvedIdentifier(BuiltinLocation("<auto-generated-identifier>"), "__jsonifier", allowDoubleUnderscore=True) method = IDLMethod(self.getLocation(p, 1), identifier, returnType=BuiltinTypes[IDLBuiltinType.Types.object], arguments=[], jsonifier=True) p[0] = method def p_QualifierStatic(self, p): """ Qualifier : STATIC """ p[0] = [IDLInterfaceMember.Special.Static] def p_QualifierStringifier(self, p): """ Qualifier : STRINGIFIER """ p[0] = [IDLInterfaceMember.Special.Stringifier] def p_Qualifiers(self, p): """ Qualifiers : Qualifier | Specials """ p[0] = p[1] def p_Specials(self, p): """ Specials : Special Specials """ p[0] = [p[1]] p[0].extend(p[2]) def p_SpecialsEmpty(self, p): """ Specials : """ p[0] = [] def p_SpecialGetter(self, p): """ Special : GETTER """ p[0] = IDLMethod.Special.Getter def p_SpecialSetter(self, p): """ Special : SETTER """ p[0] = IDLMethod.Special.Setter def p_SpecialCreator(self, p): """ Special : CREATOR """ p[0] = IDLMethod.Special.Creator def p_SpecialDeleter(self, p): """ Special : DELETER """ p[0] = IDLMethod.Special.Deleter def p_SpecialLegacyCaller(self, p): """ Special : LEGACYCALLER """ p[0] = IDLMethod.Special.LegacyCaller def p_OperationRest(self, p): """ OperationRest : ReturnType OptionalIdentifier LPAREN ArgumentList RPAREN SEMICOLON """ p[0] = (p[1], p[2], p[4]) def p_OptionalIdentifier(self, p): """ OptionalIdentifier : IDENTIFIER """ p[0] = IDLUnresolvedIdentifier(self.getLocation(p, 1), p[1]) def p_OptionalIdentifierEmpty(self, p): """ OptionalIdentifier : """ pass def p_ArgumentList(self, p): """ ArgumentList : Argument Arguments """ p[0] = [p[1]] if p[1] else [] p[0].extend(p[2]) def p_ArgumentListEmpty(self, p): """ ArgumentList : """ p[0] = [] def p_Arguments(self, p): """ Arguments : COMMA Argument Arguments """ p[0] = [p[2]] if p[2] else [] p[0].extend(p[3]) def p_ArgumentsEmpty(self, p): """ Arguments : """ p[0] = [] def p_Argument(self, p): """ Argument : ExtendedAttributeList Optional Type Ellipsis ArgumentName Default """ t = p[3] assert isinstance(t, IDLType) identifier = IDLUnresolvedIdentifier(self.getLocation(p, 5), p[5]) optional = p[2] variadic = p[4] defaultValue = p[6] if not optional and defaultValue: raise WebIDLError("Mandatory arguments can't have a default value.", [self.getLocation(p, 6)]) # We can't test t.isAny() here and give it a default value as needed, # since at this point t is not a fully resolved type yet (e.g. it might # be a typedef). We'll handle the 'any' case in IDLArgument.complete. if variadic: if optional: raise WebIDLError("Variadic arguments should not be marked optional.", [self.getLocation(p, 2)]) optional = variadic p[0] = IDLArgument(self.getLocation(p, 5), identifier, t, optional, defaultValue, variadic) p[0].addExtendedAttributes(p[1]) def p_ArgumentName(self, p): """ ArgumentName : IDENTIFIER | ATTRIBUTE | CALLBACK | CONST | CREATOR | DELETER | DICTIONARY | ENUM | EXCEPTION | GETTER | IMPLEMENTS | INHERIT | INTERFACE | LEGACYCALLER | MAPLIKE | PARTIAL | REQUIRED | SERIALIZER | SETLIKE | SETTER | STATIC | STRINGIFIER | JSONIFIER | TYPEDEF | UNRESTRICTED """ p[0] = p[1] def p_AttributeName(self, p): """ AttributeName : IDENTIFIER | REQUIRED """ p[0] = p[1] def p_Optional(self, p): """ Optional : OPTIONAL """ p[0] = True def p_OptionalEmpty(self, p): """ Optional : """ p[0] = False def p_Required(self, p): """ Required : REQUIRED """ p[0] = True def p_RequiredEmpty(self, p): """ Required : """ p[0] = False def p_Ellipsis(self, p): """ Ellipsis : ELLIPSIS """ p[0] = True def p_EllipsisEmpty(self, p): """ Ellipsis : """ p[0] = False def p_ExceptionMember(self, p): """ ExceptionMember : Const | ExceptionField """ pass def p_ExceptionField(self, p): """ ExceptionField : Type IDENTIFIER SEMICOLON """ pass def p_ExtendedAttributeList(self, p): """ ExtendedAttributeList : LBRACKET ExtendedAttribute ExtendedAttributes RBRACKET """ p[0] = [p[2]] if p[3]: p[0].extend(p[3]) def p_ExtendedAttributeListEmpty(self, p): """ ExtendedAttributeList : """ p[0] = [] def p_ExtendedAttribute(self, p): """ ExtendedAttribute : ExtendedAttributeNoArgs | ExtendedAttributeArgList | ExtendedAttributeIdent | ExtendedAttributeNamedArgList | ExtendedAttributeIdentList """ p[0] = IDLExtendedAttribute(self.getLocation(p, 1), p[1]) def p_ExtendedAttributeEmpty(self, p): """ ExtendedAttribute : """ pass def p_ExtendedAttributes(self, p): """ ExtendedAttributes : COMMA ExtendedAttribute ExtendedAttributes """ p[0] = [p[2]] if p[2] else [] p[0].extend(p[3]) def p_ExtendedAttributesEmpty(self, p): """ ExtendedAttributes : """ p[0] = [] def p_Other(self, p): """ Other : INTEGER | FLOATLITERAL | IDENTIFIER | STRING | OTHER | ELLIPSIS | COLON | SCOPE | SEMICOLON | LT | EQUALS | GT | QUESTIONMARK | DATE | DOMSTRING | BYTESTRING | USVSTRING | ANY | ATTRIBUTE | BOOLEAN | BYTE | LEGACYCALLER | CONST | CREATOR | DELETER | DOUBLE | EXCEPTION | FALSE | FLOAT | GETTER | IMPLEMENTS | INHERIT | INTERFACE | LONG | MODULE | NULL | OBJECT | OCTET | OPTIONAL | SEQUENCE | MOZMAP | SETTER | SHORT | STATIC | STRINGIFIER | JSONIFIER | TRUE | TYPEDEF | UNSIGNED | VOID """ pass def p_OtherOrComma(self, p): """ OtherOrComma : Other | COMMA """ pass def p_TypeSingleType(self, p): """ Type : SingleType """ p[0] = p[1] def p_TypeUnionType(self, p): """ Type : UnionType TypeSuffix """ p[0] = self.handleModifiers(p[1], p[2]) def p_SingleTypeNonAnyType(self, p): """ SingleType : NonAnyType """ p[0] = p[1] def p_SingleTypeAnyType(self, p): """ SingleType : ANY TypeSuffixStartingWithArray """ p[0] = self.handleModifiers(BuiltinTypes[IDLBuiltinType.Types.any], p[2]) def p_UnionType(self, p): """ UnionType : LPAREN UnionMemberType OR UnionMemberType UnionMemberTypes RPAREN """ types = [p[2], p[4]] types.extend(p[5]) p[0] = IDLUnionType(self.getLocation(p, 1), types) def p_UnionMemberTypeNonAnyType(self, p): """ UnionMemberType : NonAnyType """ p[0] = p[1] def p_UnionMemberTypeArrayOfAny(self, p): """ UnionMemberTypeArrayOfAny : ANY LBRACKET RBRACKET """ p[0] = IDLArrayType(self.getLocation(p, 2), BuiltinTypes[IDLBuiltinType.Types.any]) def p_UnionMemberType(self, p): """ UnionMemberType : UnionType TypeSuffix | UnionMemberTypeArrayOfAny TypeSuffix """ p[0] = self.handleModifiers(p[1], p[2]) def p_UnionMemberTypes(self, p): """ UnionMemberTypes : OR UnionMemberType UnionMemberTypes """ p[0] = [p[2]] p[0].extend(p[3]) def p_UnionMemberTypesEmpty(self, p): """ UnionMemberTypes : """ p[0] = [] def p_NonAnyType(self, p): """ NonAnyType : PrimitiveOrStringType TypeSuffix | ARRAYBUFFER TypeSuffix | SHAREDARRAYBUFFER TypeSuffix | OBJECT TypeSuffix """ if p[1] == "object": type = BuiltinTypes[IDLBuiltinType.Types.object] elif p[1] == "ArrayBuffer": type = BuiltinTypes[IDLBuiltinType.Types.ArrayBuffer] elif p[1] == "SharedArrayBuffer": type = BuiltinTypes[IDLBuiltinType.Types.SharedArrayBuffer] else: type = BuiltinTypes[p[1]] p[0] = self.handleModifiers(type, p[2]) def p_NonAnyTypeSequenceType(self, p): """ NonAnyType : SEQUENCE LT Type GT Null """ innerType = p[3] type = IDLSequenceType(self.getLocation(p, 1), innerType) if p[5]: type = IDLNullableType(self.getLocation(p, 5), type) p[0] = type # Note: Promise<void> is allowed, so we want to parametrize on # ReturnType, not Type. Also, we want this to end up picking up # the Promise interface for now, hence the games with IDLUnresolvedType. def p_NonAnyTypePromiseType(self, p): """ NonAnyType : PROMISE LT ReturnType GT Null """ innerType = p[3] promiseIdent = IDLUnresolvedIdentifier(self.getLocation(p, 1), "Promise") type = IDLUnresolvedType(self.getLocation(p, 1), promiseIdent, p[3]) if p[5]: type = IDLNullableType(self.getLocation(p, 5), type) p[0] = type def p_NonAnyTypeMozMapType(self, p): """ NonAnyType : MOZMAP LT Type GT Null """ innerType = p[3] type = IDLMozMapType(self.getLocation(p, 1), innerType) if p[5]: type = IDLNullableType(self.getLocation(p, 5), type) p[0] = type def p_NonAnyTypeScopedName(self, p): """ NonAnyType : ScopedName TypeSuffix """ assert isinstance(p[1], IDLUnresolvedIdentifier) if p[1].name == "Promise": raise WebIDLError("Promise used without saying what it's " "parametrized over", [self.getLocation(p, 1)]) type = None try: if self.globalScope()._lookupIdentifier(p[1]): obj = self.globalScope()._lookupIdentifier(p[1]) assert not obj.isType() if obj.isTypedef(): type = IDLTypedefType(self.getLocation(p, 1), obj.innerType, obj.identifier.name) elif obj.isCallback() and not obj.isInterface(): type = IDLCallbackType(self.getLocation(p, 1), obj) else: type = IDLWrapperType(self.getLocation(p, 1), p[1]) p[0] = self.handleModifiers(type, p[2]) return except: pass type = IDLUnresolvedType(self.getLocation(p, 1), p[1]) p[0] = self.handleModifiers(type, p[2]) def p_NonAnyTypeDate(self, p): """ NonAnyType : DATE TypeSuffix """ p[0] = self.handleModifiers(BuiltinTypes[IDLBuiltinType.Types.date], p[2]) def p_ConstType(self, p): """ ConstType : PrimitiveOrStringType Null """ type = BuiltinTypes[p[1]] if p[2]: type = IDLNullableType(self.getLocation(p, 1), type) p[0] = type def p_ConstTypeIdentifier(self, p): """ ConstType : IDENTIFIER Null """ identifier = IDLUnresolvedIdentifier(self.getLocation(p, 1), p[1]) type = IDLUnresolvedType(self.getLocation(p, 1), identifier) if p[2]: type = IDLNullableType(self.getLocation(p, 1), type) p[0] = type def p_PrimitiveOrStringTypeUint(self, p): """ PrimitiveOrStringType : UnsignedIntegerType """ p[0] = p[1] def p_PrimitiveOrStringTypeBoolean(self, p): """ PrimitiveOrStringType : BOOLEAN """ p[0] = IDLBuiltinType.Types.boolean def p_PrimitiveOrStringTypeByte(self, p): """ PrimitiveOrStringType : BYTE """ p[0] = IDLBuiltinType.Types.byte def p_PrimitiveOrStringTypeOctet(self, p): """ PrimitiveOrStringType : OCTET """ p[0] = IDLBuiltinType.Types.octet def p_PrimitiveOrStringTypeFloat(self, p): """ PrimitiveOrStringType : FLOAT """ p[0] = IDLBuiltinType.Types.float def p_PrimitiveOrStringTypeUnrestictedFloat(self, p): """ PrimitiveOrStringType : UNRESTRICTED FLOAT """ p[0] = IDLBuiltinType.Types.unrestricted_float def p_PrimitiveOrStringTypeDouble(self, p): """ PrimitiveOrStringType : DOUBLE """ p[0] = IDLBuiltinType.Types.double def p_PrimitiveOrStringTypeUnrestictedDouble(self, p): """ PrimitiveOrStringType : UNRESTRICTED DOUBLE """ p[0] = IDLBuiltinType.Types.unrestricted_double def p_PrimitiveOrStringTypeDOMString(self, p): """ PrimitiveOrStringType : DOMSTRING """ p[0] = IDLBuiltinType.Types.domstring def p_PrimitiveOrStringTypeBytestring(self, p): """ PrimitiveOrStringType : BYTESTRING """ p[0] = IDLBuiltinType.Types.bytestring def p_PrimitiveOrStringTypeUSVString(self, p): """ PrimitiveOrStringType : USVSTRING """ p[0] = IDLBuiltinType.Types.usvstring def p_UnsignedIntegerTypeUnsigned(self, p): """ UnsignedIntegerType : UNSIGNED IntegerType """ # Adding one to a given signed integer type gets you the unsigned type: p[0] = p[2] + 1 def p_UnsignedIntegerType(self, p): """ UnsignedIntegerType : IntegerType """ p[0] = p[1] def p_IntegerTypeShort(self, p): """ IntegerType : SHORT """ p[0] = IDLBuiltinType.Types.short def p_IntegerTypeLong(self, p): """ IntegerType : LONG OptionalLong """ if p[2]: p[0] = IDLBuiltinType.Types.long_long else: p[0] = IDLBuiltinType.Types.long def p_OptionalLong(self, p): """ OptionalLong : LONG """ p[0] = True def p_OptionalLongEmpty(self, p): """ OptionalLong : """ p[0] = False def p_TypeSuffixBrackets(self, p): """ TypeSuffix : LBRACKET RBRACKET TypeSuffix """ p[0] = [(IDLMethod.TypeSuffixModifier.Brackets, self.getLocation(p, 1))] p[0].extend(p[3]) def p_TypeSuffixQMark(self, p): """ TypeSuffix : QUESTIONMARK TypeSuffixStartingWithArray """ p[0] = [(IDLMethod.TypeSuffixModifier.QMark, self.getLocation(p, 1))] p[0].extend(p[2]) def p_TypeSuffixEmpty(self, p): """ TypeSuffix : """ p[0] = [] def p_TypeSuffixStartingWithArray(self, p): """ TypeSuffixStartingWithArray : LBRACKET RBRACKET TypeSuffix """ p[0] = [(IDLMethod.TypeSuffixModifier.Brackets, self.getLocation(p, 1))] p[0].extend(p[3]) def p_TypeSuffixStartingWithArrayEmpty(self, p): """ TypeSuffixStartingWithArray : """ p[0] = [] def p_Null(self, p): """ Null : QUESTIONMARK | """ if len(p) > 1: p[0] = True else: p[0] = False def p_ReturnTypeType(self, p): """ ReturnType : Type """ p[0] = p[1] def p_ReturnTypeVoid(self, p): """ ReturnType : VOID """ p[0] = BuiltinTypes[IDLBuiltinType.Types.void] def p_ScopedName(self, p): """ ScopedName : AbsoluteScopedName | RelativeScopedName """ p[0] = p[1] def p_AbsoluteScopedName(self, p): """ AbsoluteScopedName : SCOPE IDENTIFIER ScopedNameParts """ assert False pass def p_RelativeScopedName(self, p): """ RelativeScopedName : IDENTIFIER ScopedNameParts """ assert not p[2] # Not implemented! p[0] = IDLUnresolvedIdentifier(self.getLocation(p, 1), p[1]) def p_ScopedNameParts(self, p): """ ScopedNameParts : SCOPE IDENTIFIER ScopedNameParts """ assert False pass def p_ScopedNamePartsEmpty(self, p): """ ScopedNameParts : """ p[0] = None def p_ExtendedAttributeNoArgs(self, p): """ ExtendedAttributeNoArgs : IDENTIFIER """ p[0] = (p[1],) def p_ExtendedAttributeArgList(self, p): """ ExtendedAttributeArgList : IDENTIFIER LPAREN ArgumentList RPAREN """ p[0] = (p[1], p[3]) def p_ExtendedAttributeIdent(self, p): """ ExtendedAttributeIdent : IDENTIFIER EQUALS STRING | IDENTIFIER EQUALS IDENTIFIER """ p[0] = (p[1], p[3]) def p_ExtendedAttributeNamedArgList(self, p): """ ExtendedAttributeNamedArgList : IDENTIFIER EQUALS IDENTIFIER LPAREN ArgumentList RPAREN """ p[0] = (p[1], p[3], p[5]) def p_ExtendedAttributeIdentList(self, p): """ ExtendedAttributeIdentList : IDENTIFIER EQUALS LPAREN IdentifierList RPAREN """ p[0] = (p[1], p[4]) def p_IdentifierList(self, p): """ IdentifierList : IDENTIFIER Identifiers """ idents = list(p[2]) idents.insert(0, p[1]) p[0] = idents def p_IdentifiersList(self, p): """ Identifiers : COMMA IDENTIFIER Identifiers """ idents = list(p[3]) idents.insert(0, p[2]) p[0] = idents def p_IdentifiersEmpty(self, p): """ Identifiers : """ p[0] = [] def p_error(self, p): if not p: raise WebIDLError("Syntax Error at end of file. Possibly due to missing semicolon(;), braces(}) or both", [self._filename]) else: raise WebIDLError("invalid syntax", [Location(self.lexer, p.lineno, p.lexpos, self._filename)]) def __init__(self, outputdir='', lexer=None): Tokenizer.__init__(self, outputdir, lexer) logger = SqueakyCleanLogger() self.parser = yacc.yacc(module=self, outputdir=outputdir, tabmodule='webidlyacc', errorlog=logger # Pickling the grammar is a speedup in # some cases (older Python?) but a # significant slowdown in others. # We're not pickling for now, until it # becomes a speedup again. # , picklefile='WebIDLGrammar.pkl' ) logger.reportGrammarErrors() self._globalScope = IDLScope(BuiltinLocation("<Global Scope>"), None, None) # To make our test harness work, pretend like we have a primary global already. # Note that we _don't_ set _globalScope.primaryGlobalAttr, # so we'll still be able to detect multiple PrimaryGlobal extended attributes. self._globalScope.primaryGlobalName = "FakeTestPrimaryGlobal" self._globalScope.globalNames.add("FakeTestPrimaryGlobal") self._globalScope.globalNameMapping["FakeTestPrimaryGlobal"].add("FakeTestPrimaryGlobal") # And we add the special-cased "System" global name, which # doesn't have any corresponding interfaces. self._globalScope.globalNames.add("System") self._globalScope.globalNameMapping["System"].add("BackstagePass") self._installBuiltins(self._globalScope) self._productions = [] self._filename = "<builtin>" self.lexer.input(Parser._builtins) self._filename = None self.parser.parse(lexer=self.lexer, tracking=True) def _installBuiltins(self, scope): assert isinstance(scope, IDLScope) # xrange omits the last value. for x in xrange(IDLBuiltinType.Types.ArrayBuffer, IDLBuiltinType.Types.SharedFloat64Array + 1): builtin = BuiltinTypes[x] name = builtin.name typedef = IDLTypedef(BuiltinLocation("<builtin type>"), scope, builtin, name) @ staticmethod def handleModifiers(type, modifiers): for (modifier, modifierLocation) in modifiers: assert (modifier == IDLMethod.TypeSuffixModifier.QMark or modifier == IDLMethod.TypeSuffixModifier.Brackets) if modifier == IDLMethod.TypeSuffixModifier.QMark: type = IDLNullableType(modifierLocation, type) elif modifier == IDLMethod.TypeSuffixModifier.Brackets: type = IDLArrayType(modifierLocation, type) return type def parse(self, t, filename=None): self.lexer.input(t) # for tok in iter(self.lexer.token, None): # print tok self._filename = filename self._productions.extend(self.parser.parse(lexer=self.lexer, tracking=True)) self._filename = None def finish(self): # First, finish all the IDLImplementsStatements. In particular, we # have to make sure we do those before we do the IDLInterfaces. # XXX khuey hates this bit and wants to nuke it from orbit. implementsStatements = [p for p in self._productions if isinstance(p, IDLImplementsStatement)] otherStatements = [p for p in self._productions if not isinstance(p, IDLImplementsStatement)] for production in implementsStatements: production.finish(self.globalScope()) for production in otherStatements: production.finish(self.globalScope()) # Do any post-finish validation we need to do for production in self._productions: production.validate() # De-duplicate self._productions, without modifying its order. seen = set() result = [] for p in self._productions: if p not in seen: seen.add(p) result.append(p) return result def reset(self): return Parser(lexer=self.lexer) # Builtin IDL defined by WebIDL _builtins = """ typedef unsigned long long DOMTimeStamp; typedef (ArrayBufferView or ArrayBuffer) BufferSource; typedef (SharedArrayBufferView or SharedArrayBuffer) SharedBufferSource; """ def main(): # Parse arguments. from optparse import OptionParser usageString = "usage: %prog [options] files" o = OptionParser(usage=usageString) o.add_option("--cachedir", dest='cachedir', default=None, help="Directory in which to cache lex/parse tables.") o.add_option("--verbose-errors", action='store_true', default=False, help="When an error happens, display the Python traceback.") (options, args) = o.parse_args() if len(args) < 1: o.error(usageString) fileList = args baseDir = os.getcwd() # Parse the WebIDL. parser = Parser(options.cachedir) try: for filename in fileList: fullPath = os.path.normpath(os.path.join(baseDir, filename)) f = open(fullPath, 'rb') lines = f.readlines() f.close() print fullPath parser.parse(''.join(lines), fullPath) parser.finish() except WebIDLError, e: if options.verbose_errors: traceback.print_exc() else: print e if __name__ == '__main__': main()
mpl-2.0
jolevq/odoopub
openerp/pooler.py
374
2561
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## """ Functions kept for backward compatibility. They are simple wrappers around a global RegistryManager methods. """ import logging import openerp.conf.deprecation from openerp.modules.registry import RegistryManager _logger = logging.getLogger(__name__) def get_db_and_pool(db_name, force_demo=False, status=None, update_module=False): """Create and return a database connection and a newly initialized registry.""" assert openerp.conf.deprecation.openerp_pooler _logger.warning('openerp.pooler.get_db_and_pool() is deprecated.') registry = RegistryManager.get(db_name, force_demo, status, update_module) return registry._db, registry def restart_pool(db_name, force_demo=False, status=None, update_module=False): """Delete an existing registry and return a database connection and a newly initialized registry.""" _logger.warning('openerp.pooler.restart_pool() is deprecated.') assert openerp.conf.deprecation.openerp_pooler registry = RegistryManager.new(db_name, force_demo, status, update_module) return registry._db, registry def get_db(db_name): """Return a database connection. The corresponding registry is initialized.""" assert openerp.conf.deprecation.openerp_pooler return get_db_and_pool(db_name)[0] def get_pool(db_name, force_demo=False, status=None, update_module=False): """Return a model registry.""" assert openerp.conf.deprecation.openerp_pooler return get_db_and_pool(db_name, force_demo, status, update_module)[1] # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
ovresko/erpnext
erpnext/patches/v8_0/set_sales_invoice_serial_number_from_delivery_note.py
22
1393
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from erpnext.stock.stock_balance import update_bin_qty, get_reserved_qty def execute(): """ Set the Serial Numbers in Sales Invoice Item from Delivery Note Item """ frappe.reload_doc("stock", "doctype", "serial_no") frappe.db.sql(""" update `tabSales Invoice Item` sii inner join `tabDelivery Note Item` dni on sii.dn_detail=dni.name and sii.qty=dni.qty set sii.serial_no=dni.serial_no where sii.parent IN (select si.name from `tabSales Invoice` si where si.update_stock=0 and si.docstatus=1)""") items = frappe.db.sql(""" select sii.parent, sii.serial_no from `tabSales Invoice Item` sii left join `tabSales Invoice` si on sii.parent=si.name where si.docstatus=1 and si.update_stock=0""", as_dict=True) for item in items: sales_invoice = item.get("parent", None) serial_nos = item.get("serial_no", "") if not sales_invoice or not serial_nos: continue serial_nos = ["'%s'"%frappe.db.escape(no) for no in serial_nos.split("\n")] frappe.db.sql(""" UPDATE `tabSerial No` SET sales_invoice='{sales_invoice}' WHERE name in ({serial_nos}) """.format( sales_invoice=frappe.db.escape(sales_invoice), serial_nos=",".join(serial_nos) ) )
gpl-3.0
hsaputra/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
pwaldo2/AWPUG-Plone-Demo
src/awpug.content/Paste-1.7.5.1-py2.7.egg/paste/debug/watchthreads.py
28
10863
""" Watches the key ``paste.httpserver.thread_pool`` to see how many threads there are and report on any wedged threads. """ import sys import cgi import time import traceback from cStringIO import StringIO from thread import get_ident from paste import httpexceptions from paste.request import construct_url, parse_formvars from paste.util.template import HTMLTemplate, bunch page_template = HTMLTemplate(''' <html> <head> <style type="text/css"> body { font-family: sans-serif; } table.environ tr td { border-bottom: #bbb 1px solid; } table.environ tr td.bottom { border-bottom: none; } table.thread { border: 1px solid #000; margin-bottom: 1em; } table.thread tr td { border-bottom: #999 1px solid; padding-right: 1em; } table.thread tr td.bottom { border-bottom: none; } table.thread tr.this_thread td { background-color: #006; color: #fff; } a.button { background-color: #ddd; border: #aaa outset 2px; text-decoration: none; margin-top: 10px; font-size: 80%; color: #000; } a.button:hover { background-color: #eee; border: #bbb outset 2px; } a.button:active { border: #bbb inset 2px; } </style> <title>{{title}}</title> </head> <body> <h1>{{title}}</h1> {{if kill_thread_id}} <div style="background-color: #060; color: #fff; border: 2px solid #000;"> Thread {{kill_thread_id}} killed </div> {{endif}} <div>Pool size: {{nworkers}} {{if actual_workers > nworkers}} + {{actual_workers-nworkers}} extra {{endif}} ({{nworkers_used}} used including current request)<br> idle: {{len(track_threads["idle"])}}, busy: {{len(track_threads["busy"])}}, hung: {{len(track_threads["hung"])}}, dying: {{len(track_threads["dying"])}}, zombie: {{len(track_threads["zombie"])}}</div> {{for thread in threads}} <table class="thread"> <tr {{if thread.thread_id == this_thread_id}}class="this_thread"{{endif}}> <td> <b>Thread</b> {{if thread.thread_id == this_thread_id}} (<i>this</i> request) {{endif}}</td> <td> <b>{{thread.thread_id}} {{if allow_kill}} <form action="{{script_name}}/kill" method="POST" style="display: inline"> <input type="hidden" name="thread_id" value="{{thread.thread_id}}"> <input type="submit" value="kill"> </form> {{endif}} </b> </td> </tr> <tr> <td>Time processing request</td> <td>{{thread.time_html|html}}</td> </tr> <tr> <td>URI</td> <td>{{if thread.uri == 'unknown'}} unknown {{else}}<a href="{{thread.uri}}">{{thread.uri_short}}</a> {{endif}} </td> <tr> <td colspan="2" class="bottom"> <a href="#" class="button" style="width: 9em; display: block" onclick=" var el = document.getElementById('environ-{{thread.thread_id}}'); if (el.style.display) { el.style.display = ''; this.innerHTML = \'&#9662; Hide environ\'; } else { el.style.display = 'none'; this.innerHTML = \'&#9656; Show environ\'; } return false ">&#9656; Show environ</a> <div id="environ-{{thread.thread_id}}" style="display: none"> {{if thread.environ:}} <table class="environ"> {{for loop, item in looper(sorted(thread.environ.items()))}} {{py:key, value=item}} <tr> <td {{if loop.last}}class="bottom"{{endif}}>{{key}}</td> <td {{if loop.last}}class="bottom"{{endif}}>{{value}}</td> </tr> {{endfor}} </table> {{else}} Thread is in process of starting {{endif}} </div> {{if thread.traceback}} <a href="#" class="button" style="width: 9em; display: block" onclick=" var el = document.getElementById('traceback-{{thread.thread_id}}'); if (el.style.display) { el.style.display = ''; this.innerHTML = \'&#9662; Hide traceback\'; } else { el.style.display = 'none'; this.innerHTML = \'&#9656; Show traceback\'; } return false ">&#9656; Show traceback</a> <div id="traceback-{{thread.thread_id}}" style="display: none"> <pre class="traceback">{{thread.traceback}}</pre> </div> {{endif}} </td> </tr> </table> {{endfor}} </body> </html> ''', name='watchthreads.page_template') class WatchThreads(object): """ Application that watches the threads in ``paste.httpserver``, showing the length each thread has been working on a request. If allow_kill is true, then you can kill errant threads through this application. This application can expose private information (specifically in the environment, like cookies), so it should be protected. """ def __init__(self, allow_kill=False): self.allow_kill = allow_kill def __call__(self, environ, start_response): if 'paste.httpserver.thread_pool' not in environ: start_response('403 Forbidden', [('Content-type', 'text/plain')]) return ['You must use the threaded Paste HTTP server to use this application'] if environ.get('PATH_INFO') == '/kill': return self.kill(environ, start_response) else: return self.show(environ, start_response) def show(self, environ, start_response): start_response('200 OK', [('Content-type', 'text/html')]) form = parse_formvars(environ) if form.get('kill'): kill_thread_id = form['kill'] else: kill_thread_id = None thread_pool = environ['paste.httpserver.thread_pool'] nworkers = thread_pool.nworkers now = time.time() workers = thread_pool.worker_tracker.items() workers.sort(key=lambda v: v[1][0]) threads = [] for thread_id, (time_started, worker_environ) in workers: thread = bunch() threads.append(thread) if worker_environ: thread.uri = construct_url(worker_environ) else: thread.uri = 'unknown' thread.thread_id = thread_id thread.time_html = format_time(now-time_started) thread.uri_short = shorten(thread.uri) thread.environ = worker_environ thread.traceback = traceback_thread(thread_id) page = page_template.substitute( title="Thread Pool Worker Tracker", nworkers=nworkers, actual_workers=len(thread_pool.workers), nworkers_used=len(workers), script_name=environ['SCRIPT_NAME'], kill_thread_id=kill_thread_id, allow_kill=self.allow_kill, threads=threads, this_thread_id=get_ident(), track_threads=thread_pool.track_threads()) return [page] def kill(self, environ, start_response): if not self.allow_kill: exc = httpexceptions.HTTPForbidden( 'Killing threads has not been enabled. Shame on you ' 'for trying!') return exc(environ, start_response) vars = parse_formvars(environ) thread_id = int(vars['thread_id']) thread_pool = environ['paste.httpserver.thread_pool'] if thread_id not in thread_pool.worker_tracker: exc = httpexceptions.PreconditionFailed( 'You tried to kill thread %s, but it is not working on ' 'any requests' % thread_id) return exc(environ, start_response) thread_pool.kill_worker(thread_id) script_name = environ['SCRIPT_NAME'] or '/' exc = httpexceptions.HTTPFound( headers=[('Location', script_name+'?kill=%s' % thread_id)]) return exc(environ, start_response) def traceback_thread(thread_id): """ Returns a plain-text traceback of the given thread, or None if it can't get a traceback. """ if not hasattr(sys, '_current_frames'): # Only 2.5 has support for this, with this special function return None frames = sys._current_frames() if not thread_id in frames: return None frame = frames[thread_id] out = StringIO() traceback.print_stack(frame, file=out) return out.getvalue() hide_keys = ['paste.httpserver.thread_pool'] def format_environ(environ): if environ is None: return environ_template.substitute( key='---', value='No environment registered for this thread yet') environ_rows = [] for key, value in sorted(environ.items()): if key in hide_keys: continue try: if key.upper() != key: value = repr(value) environ_rows.append( environ_template.substitute( key=cgi.escape(str(key)), value=cgi.escape(str(value)))) except Exception, e: environ_rows.append( environ_template.substitute( key=cgi.escape(str(key)), value='Error in <code>repr()</code>: %s' % e)) return ''.join(environ_rows) def format_time(time_length): if time_length >= 60*60: # More than an hour time_string = '%i:%02i:%02i' % (int(time_length/60/60), int(time_length/60) % 60, time_length % 60) elif time_length >= 120: time_string = '%i:%02i' % (int(time_length/60), time_length % 60) elif time_length > 60: time_string = '%i sec' % time_length elif time_length > 1: time_string = '%0.1f sec' % time_length else: time_string = '%0.2f sec' % time_length if time_length < 5: return time_string elif time_length < 120: return '<span style="color: #900">%s</span>' % time_string else: return '<span style="background-color: #600; color: #fff">%s</span>' % time_string def shorten(s): if len(s) > 60: return s[:40]+'...'+s[-10:] else: return s def make_watch_threads(global_conf, allow_kill=False): from paste.deploy.converters import asbool return WatchThreads(allow_kill=asbool(allow_kill)) make_watch_threads.__doc__ = WatchThreads.__doc__ def make_bad_app(global_conf, pause=0): pause = int(pause) def bad_app(environ, start_response): import thread if pause: time.sleep(pause) else: count = 0 while 1: print "I'm alive %s (%s)" % (count, thread.get_ident()) time.sleep(10) count += 1 start_response('200 OK', [('content-type', 'text/plain')]) return ['OK, paused %s seconds' % pause] return bad_app
gpl-2.0
citrusleaf/dd-agent
tests/checks/integration/test_mysql.py
6
4221
# stdlib from nose.plugins.attrib import attr # project from checks import AgentCheck from tests.checks.common import AgentCheckTest @attr(requires='mysql') class TestMySql(AgentCheckTest): CHECK_NAME = 'mysql' METRIC_TAGS = ['tag1', 'tag2'] SC_TAGS = ['host:localhost', 'port:0'] MYSQL_CONFIG = [{ 'server': 'localhost', 'user': 'dog', 'pass': 'dog', 'options': {'replication': True}, 'tags': METRIC_TAGS }] CONNECTION_FAILURE = [{ 'server': 'localhost', 'user': 'unknown', 'pass': 'dog', }] # Available by default on MySQL > 5.5 INNODB_METRICS = [ 'mysql.innodb.buffer_pool_free', 'mysql.innodb.buffer_pool_used', 'mysql.innodb.buffer_pool_total', 'mysql.innodb.buffer_pool_utilization' ] REPLICATION_METRICS = [ 'mysql.replication.slave_running' ] KEY_CACHE = [ 'mysql.performance.key_cache_utilization' ] # Available on Linux SYSTEM_METRICS = [ 'mysql.performance.user_time', 'mysql.performance.kernel_time' ] COMMON_GAUGES = [ 'mysql.net.max_connections', 'mysql.performance.open_files', 'mysql.performance.table_locks_waited', 'mysql.performance.threads_connected', 'mysql.performance.threads_running', # 'mysql.innodb.current_row_locks', MariaDB status 'mysql.performance.open_tables', ] COMMON_RATES = [ 'mysql.net.connections', 'mysql.innodb.data_reads', 'mysql.innodb.data_writes', 'mysql.innodb.os_log_fsyncs', 'mysql.performance.slow_queries', 'mysql.performance.questions', 'mysql.performance.queries', 'mysql.performance.com_select', 'mysql.performance.com_insert', 'mysql.performance.com_update', 'mysql.performance.com_delete', 'mysql.performance.com_insert_select', 'mysql.performance.com_update_multi', 'mysql.performance.com_delete_multi', 'mysql.performance.com_replace_select', 'mysql.performance.qcache_hits', # 'mysql.innodb.mutex_spin_waits', MariaDB status # 'mysql.innodb.mutex_spin_rounds', MariaDB status # 'mysql.innodb.mutex_os_waits', MariaDB status 'mysql.performance.created_tmp_tables', 'mysql.performance.created_tmp_disk_tables', 'mysql.performance.created_tmp_files', 'mysql.innodb.row_lock_waits', 'mysql.innodb.row_lock_time', ] def _test_optional_metrics(self, optional_metrics, at_least): """ Check optional metrics - there should be at least `at_least` matches """ before = len(filter(lambda m: m[3].get('tested'), self.metrics)) for mname in optional_metrics: self.assertMetric(mname, tags=self.METRIC_TAGS, at_least=0) # Compute match rate after = len(filter(lambda m: m[3].get('tested'), self.metrics)) self.assertTrue(after - before > at_least) def test_check(self): config = {'instances': self.MYSQL_CONFIG} self.run_check_twice(config) # Test service check self.assertServiceCheck('mysql.can_connect', status=AgentCheck.OK, tags=self.SC_TAGS, count=1) # Test metrics for mname in (self.INNODB_METRICS + self.SYSTEM_METRICS + self.REPLICATION_METRICS + self.KEY_CACHE + self.COMMON_GAUGES + self.COMMON_RATES): self.assertMetric(mname, tags=self.METRIC_TAGS, count=1) # Assert service metadata self.assertServiceMetadata(['version'], count=1) # Raises when COVERAGE=true and coverage < 100% self.coverage_report() def test_connection_failure(self): """ Service check reports connection failure """ config = {'instances': self.CONNECTION_FAILURE} self.assertRaises( Exception, lambda: self.run_check(config) ) self.assertServiceCheck('mysql.can_connect', status=AgentCheck.CRITICAL, tags=self.SC_TAGS, count=1) self.coverage_report()
bsd-3-clause