repo_name
stringlengths
5
100
ref
stringlengths
12
67
path
stringlengths
4
244
copies
stringlengths
1
8
content
stringlengths
0
1.05M
bigswitch/neutron
refs/heads/master
neutron/objects/qos/rule.py
1
# Copyright 2015 Huawei Technologies India Pvt Ltd, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import abc import sys from neutron_lib import constants from oslo_versionedobjects import base as obj_base from oslo_versionedobjects import fields as obj_fields import six from neutron.common import utils from neutron.db import api as db_api from neutron.db.qos import models as qos_db_model from neutron.objects import base from neutron.objects import common_types from neutron.services.qos import qos_consts DSCP_MARK = 'dscp_mark' def get_rules(context, qos_policy_id): all_rules = [] with db_api.autonested_transaction(context.session): for rule_type in qos_consts.VALID_RULE_TYPES: rule_cls_name = 'Qos%sRule' % utils.camelize(rule_type) rule_cls = getattr(sys.modules[__name__], rule_cls_name) rules = rule_cls.get_objects(context, qos_policy_id=qos_policy_id) all_rules.extend(rules) return all_rules @six.add_metaclass(abc.ABCMeta) class QosRule(base.NeutronDbObject): # Version 1.0: Initial version, only BandwidthLimitRule # 1.1: Added DscpMarkingRule # #NOTE(mangelajo): versions need to be handled from the top QosRule object # because it's the only reference QosPolicy can make # to them via obj_relationships version map VERSION = '1.1' fields = { 'id': obj_fields.UUIDField(), 'qos_policy_id': obj_fields.UUIDField() } fields_no_update = ['id', 'qos_policy_id'] # should be redefined in subclasses rule_type = None def to_dict(self): dict_ = super(QosRule, self).to_dict() dict_['type'] = self.rule_type return dict_ def should_apply_to_port(self, port): """Check whether a rule can be applied to a specific port. This function has the logic to decide whether a rule should be applied to a port or not, depending on the source of the policy (network, or port). Eventually rules could override this method, or we could make it abstract to allow different rule behaviour. """ is_network_rule = self.qos_policy_id != port[qos_consts.QOS_POLICY_ID] is_network_device_port = any(port['device_owner'].startswith(prefix) for prefix in constants.DEVICE_OWNER_PREFIXES) return not (is_network_rule and is_network_device_port) @obj_base.VersionedObjectRegistry.register class QosBandwidthLimitRule(QosRule): db_model = qos_db_model.QosBandwidthLimitRule fields = { 'max_kbps': obj_fields.IntegerField(nullable=True), 'max_burst_kbps': obj_fields.IntegerField(nullable=True) } rule_type = qos_consts.RULE_TYPE_BANDWIDTH_LIMIT @obj_base.VersionedObjectRegistry.register class QosDscpMarkingRule(QosRule): db_model = qos_db_model.QosDscpMarkingRule fields = { DSCP_MARK: common_types.DscpMarkField(), } rule_type = qos_consts.RULE_TYPE_DSCP_MARK
chenc10/Spark-PAF
refs/heads/master
ec2/lib/boto-2.34.0/boto/file/bucket.py
153
# Copyright 2010 Google Inc. # Copyright (c) 2011, Nexenta Systems 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, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # File representation of bucket, for use with "file://" URIs. import os from boto.file.key import Key from boto.file.simpleresultset import SimpleResultSet from boto.s3.bucketlistresultset import BucketListResultSet class Bucket(object): def __init__(self, name, contained_key): """Instantiate an anonymous file-based Bucket around a single key. """ self.name = name self.contained_key = contained_key def __iter__(self): return iter(BucketListResultSet(self)) def __str__(self): return 'anonymous bucket for file://' + self.contained_key def delete_key(self, key_name, headers=None, version_id=None, mfa_token=None): """ Deletes a key from the bucket. :type key_name: string :param key_name: The key name to delete :type version_id: string :param version_id: Unused in this subclass. :type mfa_token: tuple or list of strings :param mfa_token: Unused in this subclass. """ os.remove(key_name) def get_all_keys(self, headers=None, **params): """ This method returns the single key around which this anonymous Bucket was instantiated. :rtype: SimpleResultSet :return: The result from file system listing the keys requested """ key = Key(self.name, self.contained_key) return SimpleResultSet([key]) def get_key(self, key_name, headers=None, version_id=None, key_type=Key.KEY_REGULAR_FILE): """ Check to see if a particular key exists within the bucket. Returns: An instance of a Key object or None :type key_name: string :param key_name: The name of the key to retrieve :type version_id: string :param version_id: Unused in this subclass. :type stream_type: integer :param stream_type: Type of the Key - Regular File or input/output Stream :rtype: :class:`boto.file.key.Key` :returns: A Key object from this bucket. """ if key_name == '-': return Key(self.name, '-', key_type=Key.KEY_STREAM_READABLE) else: fp = open(key_name, 'rb') return Key(self.name, key_name, fp) def new_key(self, key_name=None, key_type=Key.KEY_REGULAR_FILE): """ Creates a new key :type key_name: string :param key_name: The name of the key to create :rtype: :class:`boto.file.key.Key` :returns: An instance of the newly created key object """ if key_name == '-': return Key(self.name, '-', key_type=Key.KEY_STREAM_WRITABLE) else: dir_name = os.path.dirname(key_name) if dir_name and not os.path.exists(dir_name): os.makedirs(dir_name) fp = open(key_name, 'wb') return Key(self.name, key_name, fp)
open2bizz/odoo-addons
refs/heads/12.0
project_view_with_messaging/models/__init__.py
1
from . import project
interline/xhtml2pdf
refs/heads/master
test/helloworld.py
154
# -*- coding: utf-8 -*- # Copyright 2010 Dirk Holtwick, holtwick.it # # 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. __version__ = "$Revision: 194 $" __author__ = "$Author: holtwick $" __date__ = "$Date: 2008-04-18 18:59:53 +0200 (Fr, 18 Apr 2008) $" import ho.pisa as pisa def helloWorld(): filename = __file__ + ".pdf" pdf = pisa.CreatePDF( u"Hello <strong>World</strong>", file(filename, "wb") ) if not pdf.err: pisa.startViewer(filename) if __name__=="__main__": pisa.showLogging() helloWorld()
pimier15/PyGUI
refs/heads/master
Kivy/Kivy/Bk_Interractive/My/C4/style_decorating/gestures.py
19
# Code 4.6 line45_str = 'eNq1VktuI0cM3fdFrM0I/LN4AWUbwAcI/BFsYwa2IGmSmduHxZa77bGTziKtjQ3W42MXH4vk5unr058/tw/70/n7cT/8dvl7gGFzf8Dh+up0Pr583Z+uhgMNm28HHjafelwXbDhI99P0O7w8PZ+7m3U3/we33ztqOLTuFen1Mx0Qht0X2KowMIZ7C2zkbThdX/3ox1jHEtpUHN3JAE2G0+3Nv8ZAqivx8PAaAEJcgiEQwzADPLxyc2vgzt4MSMR4mbzujTqRC6tJCLmqkTrJzM7WmD04CEjJVJfZrdh9JfbKPsbEztTIrGVmCazZm8QwIWumhlMbR5HlxFAVEuE65CUp8TrkJSnNkpJlPQhGJtWCGs/kKYFGWBO0FhbLKacSlHwV7pKTZjkxMhcUTQyY2N8WOkpmCYUikyNIsszOpSfjSuwlKPNK7KUoz4pmORAzE2C+dXCayaExQvafaM5mvtxduBRlX4W7FOVYg1tKT5n1BCA3VkJFjZZv6B199hQzJEfCyHK08OUIpanwihFKV9EVI5S6clG3lyU2c84JYk5M9kqfJ5oxMeLShv+DACWuxArUWtoqrkFdoiqvQT2uELoGdcmoa8ioJaNOMubsJQdg1dwvIt/kRJ1VqSrZ7ym3F+57zQK1lYyGa1CXjDbJyJDLlBoYAOTe1WbmCBGnyOlkDWg5H1Yqmq7AXCLaJCIbA+SMSHZRabOGLJYbEtplUCxPfCsNLf5/Zi8JfZIwh7lFXlnHRp4jaaL2yGlH0ESa5P/L1CWhTxLmuhoAAQ1yNmK2upk6WMCzNZKAVLHf3uROfbo77vfP07qeM6Pv6zpsdrlEZbd88+Nhh5624XxwG246Qj5B4Dbe/rzDveDs6bzD9oE3Ea0Q2joid9cxSpTRqYwsZWxQxsAyKn3katgR3D8uEa6jG5VRuBvz5bz/SOkILoTVRzLje2LrCOkIQf7VecctxihaCK4vznSPxkqWaBELjXdrlZJ8qGUU+CRapUQyW79GE7WRI0aEfETYeOuAEVFpzXIdjfiZMfMzVsRfT/fnxyyFSDWpTtN4fvm2P9483+37gVSP7OZLUf5xOL7cf78790NNzm1r3l8ONm1ZhN6hj/unh8dCWPJG8d5u/wZiksYp' circle_str = 'eNq1WMtuGzkQvM+P2JcI/Sb5A9rrAv6AhWMLtpHAFixlN/n75XTPDDmxdscX6SKgRFZ3VzXJtm9fvr38/Wv3dDidf7wfhj+m7yMMt49HHO5uTuf3t2+H081wpOH2+5GH24s77nzZcJRxn9Z9x7eX1/O4zcZt6T+2/TmuGo553FXqrl91A8Kwhx2xctKMVgqLCQ6nu5uf46847L/ADhEVi0HKwsiJh9PX+/8NgeQV8fA08QPAwg6KeTg9TdyESaCRZ9km97JRZ3JUBqI858/WyJkVpCz0YNvk5uRpJoeSkaCgApOlkrkj16yTIqRScJvblccS3JUBEC0zgClrkZRLz54yZqMkWlMALpvs5F1EuLDXvDAxARkKpwLSkWdC6HLfJndDiRdylpptJc1SrAbhntxIoftsO0ruKOmV2N1SSgu7oBqIJkVjLjmlvmEQm+a07Sm5p9Q8VRMjwdnWrtOxcHa1p36kTXJ2SxmvQ+6WcrPUWAkbe3eMcH2MtlVhN5SboWZkLrYVyti3YvUYrGv0TyTufnLqyE2nThmbfT5EY95omEwSaM71jtumdje5XIFa3EtpXkpJZenBKstCXTu8dGJvN7i4k8LXoHYjRa9B7TZKs7G2Xx6vwRRNiAt1fXuyUhEMwdM2tdso5QrU6jZqs5HWHSKNOkHm7rNN7TZqsxGzUHd/Z1u4Day/prapY1JoNkK1amIdc6fmY+3qXC8+jTP5iadB3UddXswqZWqvsVhqioCgtc92i6j7qOUK1OY+Gi7UllN75hO1k14fiv6tzNtGmhtpbfqRhHXqmWaUljRDBr88ogHlE1m7j6ZXYHYXbXGRNJeF2Eqjrl3DjdnGUW6L2l20xUVKYMsoWCM06rWJaTvr5C6mxcU6CIJQ9cgMkCF1bxiQUnvX9RMPZHIb02LjOJ1Cwlx0CrHxiNUZ+vTwfji8LtN5rWgcz3W43XOqu4a9INev87Fmel9ByyswBWgrMAeoK7AESD2YwUFNAUKAGCA6CGlX+o+MK8hXCMcKiW3sIHlULiVAcdDDVZACVAfBo9YhNsAoD2KlYYBRHnjSLOVCKnm1YtoWtYJXUOe1XT8N1gn/fCzQr8BIoUTh4GKS8cdoJQpH8RVi6xVpXBEqSPEVUNaheVwRkphzYImMS0iSXJJ6qQcYkhQNMMQrLokwBcgXArgkIvJ72TVa2F5cH/HYeyL7yIHgAil4bOJwE8EVUsZZoUBdFZVQJeuEuhKqYaiLOqISqIU1MKHar5WZ1+tXij7JM+oCKE59ph9dQshd8nN/IkTVyX7fUTt/yg69apnPQ55QDMnlwsZ8ITy6HhInQYgmFtdDoAQ6JYXRDSWO5awH9u1Qb9MJjX5IskanKyB4eY423QFpzVv6m4Gm+igOg+Gc2ceSKI6GwSp5ootoLTTutn9eHs/P4/8I6l9ve9IxakXPb98P7/evDwf/Rf1aH/Hpiv3r+P72+OPh7L/Wps11lKmlV8MBVcdJ5u7m+fDy9Bwr0sg8Zn76uvsXN95aCg==' cross_str = 'eNq1V9tuIzcMfZ8fSV5qiHfpB9LXAvmAIpsYSbCLxIi9bffvS5ETaxJ76zUK+2WAI/JI5KEo+vr56/NfP1aP6+3u+9t6+n3+bsp0/bCB6fZqu3t7/breXk0bnK6/bWi6PupxG2bThrufuN/m9fll1920u9lP3P7oVtOmdq/mXj/cAcp0U1Zi3IyMGjexVnXa3l7901dhuvmtrNgqq1JVEVZEkGn75e4/9wCMkGh6zA0YCWotKAilVAaeto8zOaEznkcecbvhRcg1yO2dnNiwCWgtaojaaJCjyPuehUiJT5NH7qG9kxdBFT99acikrckgL8IkCRuby6In2THqCOFC7CEp0oXYQ1OUC7GHqDiLmhzcSq8JqFzN15PeV7gSNEKz2LycFhVDVGx7ciTz06MWKYwFkPbkAKWeR06hKcFlyENSoj05EaANcpZBXtUgk9W7BJ6+SBSKkgzyRrYgxz03mrRmtTWQ5m1GT+tJoScNPRm0NNPaiolSKePgVNAqKRCzkFU4zR1y0pCTUQoeTYo3F0ZlK1IrEtfTGeeQk4ecVAtViv7RjzjKUBXsPOoQkxdicgMa1Lhoi97L7LzOxaEmy4XYQ08eehJqBej3O8pCF+xghSmbcZfb6DR7KMqLC9pE9Dg7jlewtwE5fXYJSWVxQ7XasUvUwwLC6kUoEMt2+hZJqCq0uP8e/Dh71QX7eAN/Me+SE8RQtdiHvC/ZPSzl8zITqopdiD1UlaGq3/rlVSr+zA56KFrGmwGni0ZDVt0/pkiiY8ighot6B4Y6KlJ+hT1kVboQe8iqciH2kFXHhAQuZeltSrAxkCyaGJz5aGiIqvsBiV1TGtz1f7xHFoLaXlBmKHxksOu1aEXPekgt5LQx7vp4QUcm0v4cGfLnt86n7e3923r9sp/jjWOQl+n6hghXTioF/LPb+LRz5yAHyLWu2vLH3cLCQi0s4uNgDbCmm5QEWwf9CftM4oYcFrWERdg7Zbr5I9pBpUM3aH4NFz/t5hjmtRyYY6tJSN0iI7zBvvUBB6dFxITW0k0SrAnOXPoBzOirfXCfwZrnqofnerfI/AjnuezwXC3zg2nRMmkt8zOH0/KwDVMAjUwWTZBSqhYgYIIRqxd8ghlWkw/gkTS3LIw8LGFK1eZayF1p3iBrwXJXkQQjVu8NARocbuClHHGRfl6LBBzUIZTMg1DUHOfmUH5aDr2ijuwaOeJI4w0bzCy8kJmNZzQrAjgvR5nRLAmQtG0zmjUBmrbvDPUo6snJe/r388PuKf4Z+zrEuqO712/rt7uX+3WsZIPq+Nwt/ty8vT58v9/FKjrvSsnrwntY9T+l7POJ2z6tnx+f0oS8bKKktl9W/wK0bSEG'
opengeogroep/inasafe
refs/heads/master
third_party/raven/utils/urlparse.py
30
from __future__ import absolute_import import urlparse as _urlparse def register_scheme(scheme): for method in filter(lambda s: s.startswith('uses_'), dir(_urlparse)): uses = getattr(_urlparse, method) if scheme not in uses: uses.append(scheme) urlparse = _urlparse.urlparse
JamesMGreene/phantomjs
refs/heads/master
src/qt/qtwebkit/Tools/Scripts/webkitpy/tool/commands/analyzechangelog.py
122
# Copyright (c) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import json import re import time from webkitpy.common.checkout.scm.detection import SCMDetector from webkitpy.common.checkout.changelog import ChangeLog from webkitpy.common.config.contributionareas import ContributionAreas from webkitpy.common.system.filesystem import FileSystem from webkitpy.common.system.executive import Executive from webkitpy.tool.multicommandtool import Command from webkitpy.tool import steps class AnalyzeChangeLog(Command): name = "analyze-changelog" help_text = "Experimental command for analyzing change logs." long_help = "This command parses changelogs in a specified directory and summarizes the result as JSON files." def __init__(self): options = [ steps.Options.changelog_count, ] Command.__init__(self, options=options) @staticmethod def _enumerate_changelogs(filesystem, dirname, changelog_count): changelogs = [filesystem.join(dirname, filename) for filename in filesystem.listdir(dirname) if re.match('^ChangeLog(-(\d{4}-\d{2}-\d{2}))?$', filename)] # Make sure ChangeLog shows up before ChangeLog-2011-01-01 changelogs = sorted(changelogs, key=lambda filename: filename + 'X', reverse=True) return changelogs[:changelog_count] @staticmethod def _generate_jsons(filesystem, jsons, output_dir): for filename in jsons: print ' Generating', filename filesystem.write_text_file(filesystem.join(output_dir, filename), json.dumps(jsons[filename], indent=2)) def execute(self, options, args, tool): filesystem = self._tool.filesystem if len(args) < 1 or not filesystem.exists(args[0]): print "Need the directory name to look for changelog as the first argument" return changelog_dir = filesystem.abspath(args[0]) if len(args) < 2 or not filesystem.exists(args[1]): print "Need the output directory name as the second argument" return output_dir = args[1] startTime = time.time() print 'Enumerating ChangeLog files...' changelogs = AnalyzeChangeLog._enumerate_changelogs(filesystem, changelog_dir, options.changelog_count) analyzer = ChangeLogAnalyzer(tool, changelogs) analyzer.analyze() print 'Generating json files...' json_files = { 'summary.json': analyzer.summary(), 'contributors.json': analyzer.contributors_statistics(), 'areas.json': analyzer.areas_statistics(), } AnalyzeChangeLog._generate_jsons(filesystem, json_files, output_dir) commands_dir = filesystem.dirname(filesystem.path_to_module(self.__module__)) print commands_dir filesystem.copyfile(filesystem.join(commands_dir, 'data/summary.html'), filesystem.join(output_dir, 'summary.html')) tick = time.time() - startTime print 'Finished in %02dm:%02ds' % (int(tick / 60), int(tick % 60)) class ChangeLogAnalyzer(object): def __init__(self, host, changelog_paths): self._changelog_paths = changelog_paths self._filesystem = host.filesystem self._contribution_areas = ContributionAreas(host.filesystem) self._scm = host.scm() self._parsed_revisions = {} self._contributors_statistics = {} self._areas_statistics = dict([(area, {'reviewed': 0, 'unreviewed': 0, 'contributors': {}}) for area in self._contribution_areas.names()]) self._summary = {'reviewed': 0, 'unreviewed': 0} self._longest_filename = max([len(path) - len(self._scm.checkout_root) for path in changelog_paths]) self._filename = '' self._length_of_previous_output = 0 def contributors_statistics(self): return self._contributors_statistics def areas_statistics(self): return self._areas_statistics def summary(self): return self._summary def _print_status(self, status): if self._length_of_previous_output: print "\r" + " " * self._length_of_previous_output, new_output = ('%' + str(self._longest_filename) + 's: %s') % (self._filename, status) print "\r" + new_output, self._length_of_previous_output = len(new_output) def _set_filename(self, filename): if self._filename: print self._filename = filename def analyze(self): for path in self._changelog_paths: self._set_filename(self._filesystem.relpath(path, self._scm.checkout_root)) with self._filesystem.open_text_file_for_reading(path) as changelog: self._print_status('Parsing entries...') number_of_parsed_entries = self._analyze_entries(ChangeLog.parse_entries_from_file(changelog), path) self._print_status('Done (%d entries)' % number_of_parsed_entries) print self._summary['contributors'] = len(self._contributors_statistics) self._summary['contributors_with_reviews'] = sum([1 for contributor in self._contributors_statistics.values() if contributor['reviews']['total']]) self._summary['contributors_without_reviews'] = self._summary['contributors'] - self._summary['contributors_with_reviews'] def _collect_statistics_for_contributor_area(self, area, contributor, contribution_type, reviewed): area_contributors = self._areas_statistics[area]['contributors'] if contributor not in area_contributors: area_contributors[contributor] = {'reviews': 0, 'reviewed': 0, 'unreviewed': 0} if contribution_type == 'patches': contribution_type = 'reviewed' if reviewed else 'unreviewed' area_contributors[contributor][contribution_type] += 1 def _collect_statistics_for_contributor(self, contributor, contribution_type, areas, touched_files, reviewed): if contributor not in self._contributors_statistics: self._contributors_statistics[contributor] = { 'reviews': {'total': 0, 'areas': {}, 'files': {}}, 'patches': {'reviewed': 0, 'unreviewed': 0, 'areas': {}, 'files': {}}} statistics = self._contributors_statistics[contributor][contribution_type] if contribution_type == 'reviews': statistics['total'] += 1 elif reviewed: statistics['reviewed'] += 1 else: statistics['unreviewed'] += 1 for area in areas: self._increment_dictionary_value(statistics['areas'], area) self._collect_statistics_for_contributor_area(area, contributor, contribution_type, reviewed) for touchedfile in touched_files: self._increment_dictionary_value(statistics['files'], touchedfile) def _increment_dictionary_value(self, dictionary, key): dictionary[key] = dictionary.get(key, 0) + 1 def _analyze_entries(self, entries, changelog_path): dirname = self._filesystem.dirname(changelog_path) i = 0 for i, entry in enumerate(entries): self._print_status('(%s) entries' % i) assert(entry.authors()) touchedfiles_for_entry = [self._filesystem.relpath(self._filesystem.join(dirname, name), self._scm.checkout_root) for name in entry.touched_files()] areas_for_entry = self._contribution_areas.areas_for_touched_files(touchedfiles_for_entry) authors_for_entry = entry.authors() reviewers_for_entry = entry.reviewers() for reviewer in reviewers_for_entry: self._collect_statistics_for_contributor(reviewer.full_name, 'reviews', areas_for_entry, touchedfiles_for_entry, reviewed=True) for author in authors_for_entry: self._collect_statistics_for_contributor(author['name'], 'patches', areas_for_entry, touchedfiles_for_entry, reviewed=bool(reviewers_for_entry)) for area in areas_for_entry: self._areas_statistics[area]['reviewed' if reviewers_for_entry else 'unreviewed'] += 1 self._summary['reviewed' if reviewers_for_entry else 'unreviewed'] += 1 self._print_status('(%s) entries' % i) return i
eemirtekin/edx-platform
refs/heads/master
lms/djangoapps/courseware/field_overrides.py
13
""" This module provides a :class:`~xblock.field_data.FieldData` implementation which wraps an other `FieldData` object and provides overrides based on the user. The use of providers allows for overrides that are arbitrarily extensible. One provider is found in `courseware.student_field_overrides` which allows for fields to be overridden for individual students. One can envision other providers being written that allow for fields to be overridden base on membership of a student in a cohort, or similar. The use of an extensible, modular architecture allows for overrides being done in ways not envisioned by the authors. Currently, this module is used in the `module_render` module in this same package and is used to wrap the `authored_data` when constructing an `LmsFieldData`. This means overrides will be in effect for all scopes covered by `authored_data`, e.g. course content and settings stored in Mongo. """ import threading from abc import ABCMeta, abstractmethod from contextlib import contextmanager from django.conf import settings from xblock.field_data import FieldData from xmodule.modulestore.inheritance import InheritanceMixin NOTSET = object() def resolve_dotted(name): """ Given the dotted name for a Python object, performs any necessary imports and returns the object. """ names = name.split('.') path = names.pop(0) target = __import__(path) while names: segment = names.pop(0) path += '.' + segment try: target = getattr(target, segment) except AttributeError: __import__(path) target = getattr(target, segment) return target class OverrideFieldData(FieldData): """ A :class:`~xblock.field_data.FieldData` which wraps another `FieldData` object and allows for fields handled by the wrapped `FieldData` to be overriden by arbitrary providers. Providers are configured by use of the Django setting, `FIELD_OVERRIDE_PROVIDERS` which should be a tuple of dotted names of :class:`FieldOverrideProvider` concrete implementations. Note that order is important for this setting. Override providers will tried in the order configured in the setting. The first provider to find an override 'wins' for a particular field lookup. """ provider_classes = None @classmethod def wrap(cls, user, wrapped): """ Will return a :class:`OverrideFieldData` which wraps the field data given in `wrapped` for the given `user`, if override providers are configred. If no override providers are configured, using the Django setting, `FIELD_OVERRIDE_PROVIDERS`, returns `wrapped`, eliminating any performance impact of this feature if no override providers are configured. """ if cls.provider_classes is None: cls.provider_classes = tuple( (resolve_dotted(name) for name in settings.FIELD_OVERRIDE_PROVIDERS)) if cls.provider_classes: return cls(user, wrapped) return wrapped def __init__(self, user, fallback): self.fallback = fallback self.providers = tuple((cls(user) for cls in self.provider_classes)) def get_override(self, block, name): """ Checks for an override for the field identified by `name` in `block`. Returns the overridden value or `NOTSET` if no override is found. """ if not overrides_disabled(): for provider in self.providers: value = provider.get(block, name, NOTSET) if value is not NOTSET: return value return NOTSET def get(self, block, name): value = self.get_override(block, name) if value is not NOTSET: return value return self.fallback.get(block, name) def set(self, block, name, value): self.fallback.set(block, name, value) def delete(self, block, name): self.fallback.delete(block, name) def has(self, block, name): has = self.get_override(block, name) if has is NOTSET: # If this is an inheritable field and an override is set above, # then we want to return False here, so the field_data uses the # override and not the original value for this block. inheritable = InheritanceMixin.fields.keys() if name in inheritable: for ancestor in _lineage(block): if self.get_override(ancestor, name) is not NOTSET: return False return has is not NOTSET or self.fallback.has(block, name) def set_many(self, block, update_dict): return self.fallback.set_many(block, update_dict) def default(self, block, name): # The `default` method is overloaded by the field storage system to # also handle inheritance. if not overrides_disabled(): inheritable = InheritanceMixin.fields.keys() if name in inheritable: for ancestor in _lineage(block): value = self.get_override(ancestor, name) if value is not NOTSET: return value return self.fallback.default(block, name) class _OverridesDisabled(threading.local): """ A thread local used to manage state of overrides being disabled or not. """ disabled = () _OVERRIDES_DISABLED = _OverridesDisabled() @contextmanager def disable_overrides(): """ A context manager which disables field overrides inside the context of a `with` statement, allowing code to get at the `original` value of a field. """ prev = _OVERRIDES_DISABLED.disabled _OVERRIDES_DISABLED.disabled += (True,) yield _OVERRIDES_DISABLED.disabled = prev def overrides_disabled(): """ Checks to see whether overrides are disabled in the current context. Returns a boolean value. See `disable_overrides`. """ return bool(_OVERRIDES_DISABLED.disabled) class FieldOverrideProvider(object): """ Abstract class which defines the interface that a `FieldOverrideProvider` must provide. In general, providers should derive from this class, but it's not strictly necessary as long as they correctly implement this interface. A `FieldOverrideProvider` implementation is only responsible for looking up field overrides. To set overrides, there will be a domain specific API for the concrete override implementation being used. """ __metaclass__ = ABCMeta def __init__(self, user): self.user = user @abstractmethod def get(self, block, name, default): # pragma no cover """ Look for an override value for the field named `name` in `block`. Returns the overridden value or `default` if no override is found. """ raise NotImplementedError def _lineage(block): """ Returns an iterator over all ancestors of the given block, starting with its immediate parent and ending at the root of the block tree. """ parent = block.get_parent() while parent: yield parent parent = parent.get_parent()
thaumos/ansible
refs/heads/devel
test/integration/targets/pause/test-pause.py
72
#!/usr/bin/env python import os import pexpect import sys import termios from ansible.module_utils.six import PY2 args = sys.argv[1:] env_vars = { 'ANSIBLE_ROLES_PATH': './roles', 'ANSIBLE_NOCOLOR': 'True', 'ANSIBLE_RETRY_FILES_ENABLED': 'False' } try: backspace = termios.tcgetattr(sys.stdin.fileno())[6][termios.VERASE] except Exception: backspace = b'\x7f' if PY2: log_buffer = sys.stdout else: log_buffer = sys.stdout.buffer os.environ.update(env_vars) # -- Plain pause -- # playbook = 'pause-1.yml' # Case 1 - Contiune with enter pause_test = pexpect.spawn( 'ansible-playbook', args=[playbook] + args, timeout=10, env=os.environ ) pause_test.logfile = log_buffer pause_test.expect(r'Press enter to continue, Ctrl\+C to interrupt:') pause_test.send('\r') pause_test.expect('Task after pause') pause_test.expect(pexpect.EOF) pause_test.close() # Case 2 - Continue with C pause_test = pexpect.spawn( 'ansible-playbook', args=[playbook] + args, timeout=10, env=os.environ ) pause_test.logfile = log_buffer pause_test.expect(r'Press enter to continue, Ctrl\+C to interrupt:') pause_test.send('\x03') pause_test.expect("Press 'C' to continue the play or 'A' to abort") pause_test.send('C') pause_test.expect('Task after pause') pause_test.expect(pexpect.EOF) pause_test.close() # Case 3 - Abort with A pause_test = pexpect.spawn( 'ansible-playbook', args=[playbook] + args, timeout=10, env=os.environ ) pause_test.logfile = log_buffer pause_test.expect(r'Press enter to continue, Ctrl\+C to interrupt:') pause_test.send('\x03') pause_test.expect("Press 'C' to continue the play or 'A' to abort") pause_test.send('A') pause_test.expect('user requested abort!') pause_test.expect(pexpect.EOF) pause_test.close() # -- Custom Prompt -- # playbook = 'pause-2.yml' # Case 1 - Contiune with enter pause_test = pexpect.spawn( 'ansible-playbook', args=[playbook] + args, timeout=10, env=os.environ ) pause_test.logfile = log_buffer pause_test.expect(r'Custom prompt:') pause_test.send('\r') pause_test.expect('Task after pause') pause_test.expect(pexpect.EOF) pause_test.close() # Case 2 - Contiune with C pause_test = pexpect.spawn( 'ansible-playbook', args=[playbook] + args, timeout=10, env=os.environ ) pause_test.logfile = log_buffer pause_test.expect(r'Custom prompt:') pause_test.send('\x03') pause_test.expect("Press 'C' to continue the play or 'A' to abort") pause_test.send('C') pause_test.expect('Task after pause') pause_test.expect(pexpect.EOF) pause_test.close() # Case 3 - Abort with A pause_test = pexpect.spawn( 'ansible-playbook', args=[playbook] + args, timeout=10, env=os.environ ) pause_test.logfile = log_buffer pause_test.expect(r'Custom prompt:') pause_test.send('\x03') pause_test.expect("Press 'C' to continue the play or 'A' to abort") pause_test.send('A') pause_test.expect('user requested abort!') pause_test.expect(pexpect.EOF) pause_test.close() # -- Pause for N seconds -- # playbook = 'pause-3.yml' # Case 1 - Wait for task to continue after timeout pause_test = pexpect.spawn( 'ansible-playbook', args=[playbook] + args, timeout=10, env=os.environ ) pause_test.logfile = log_buffer pause_test.expect(r'Pausing for \d+ seconds') pause_test.expect(r"\(ctrl\+C then 'C' = continue early, ctrl\+C then 'A' = abort\)") pause_test.expect('Task after pause') pause_test.expect(pexpect.EOF) pause_test.close() # Case 2 - Contiune with Ctrl + C, C pause_test = pexpect.spawn( 'ansible-playbook', args=[playbook] + args, timeout=10, env=os.environ ) pause_test.logfile = log_buffer pause_test.expect(r'Pausing for \d+ seconds') pause_test.expect(r"\(ctrl\+C then 'C' = continue early, ctrl\+C then 'A' = abort\)") pause_test.send('\x03') pause_test.send('C') pause_test.expect('Task after pause') pause_test.expect(pexpect.EOF) pause_test.close() # Case 3 - Abort with Ctrl + C, A pause_test = pexpect.spawn( 'ansible-playbook', args=[playbook] + args, timeout=10, env=os.environ ) pause_test.logfile = log_buffer pause_test.expect(r'Pausing for \d+ seconds') pause_test.expect(r"\(ctrl\+C then 'C' = continue early, ctrl\+C then 'A' = abort\)") pause_test.send('\x03') pause_test.send('A') pause_test.expect('user requested abort!') pause_test.expect(pexpect.EOF) pause_test.close() # -- Pause for N seconds with custom prompt -- # playbook = 'pause-4.yml' # Case 1 - Wait for task to continue after timeout pause_test = pexpect.spawn( 'ansible-playbook', args=[playbook] + args, timeout=10, env=os.environ ) pause_test.logfile = log_buffer pause_test.expect(r'Pausing for \d+ seconds') pause_test.expect(r"\(ctrl\+C then 'C' = continue early, ctrl\+C then 'A' = abort\)") pause_test.expect(r"Waiting for two seconds:") pause_test.expect('Task after pause') pause_test.expect(pexpect.EOF) pause_test.close() # Case 2 - Contiune with Ctrl + C, C pause_test = pexpect.spawn( 'ansible-playbook', args=[playbook] + args, timeout=10, env=os.environ ) pause_test.logfile = log_buffer pause_test.expect(r'Pausing for \d+ seconds') pause_test.expect(r"\(ctrl\+C then 'C' = continue early, ctrl\+C then 'A' = abort\)") pause_test.expect(r"Waiting for two seconds:") pause_test.send('\x03') pause_test.send('C') pause_test.expect('Task after pause') pause_test.expect(pexpect.EOF) pause_test.close() # Case 3 - Abort with Ctrl + C, A pause_test = pexpect.spawn( 'ansible-playbook', args=[playbook] + args, timeout=10, env=os.environ ) pause_test.logfile = log_buffer pause_test.expect(r'Pausing for \d+ seconds') pause_test.expect(r"\(ctrl\+C then 'C' = continue early, ctrl\+C then 'A' = abort\)") pause_test.expect(r"Waiting for two seconds:") pause_test.send('\x03') pause_test.send('A') pause_test.expect('user requested abort!') pause_test.expect(pexpect.EOF) pause_test.close() # -- Enter input and ensure it's captured, echoed, and can be edited -- # playbook = 'pause-5.yml' pause_test = pexpect.spawn( 'ansible-playbook', args=[playbook] + args, timeout=10, env=os.environ ) pause_test.logfile = log_buffer pause_test.expect(r'Enter some text:') pause_test.send('hello there') pause_test.send('\r') pause_test.expect(r'Enter some text to edit:') pause_test.send('hello there') pause_test.send(backspace * 4) pause_test.send('ommy boy') pause_test.send('\r') pause_test.expect(r'Enter some text \(output is hidden\):') pause_test.send('supersecretpancakes') pause_test.send('\r') pause_test.expect(pexpect.EOF) pause_test.close()
skyoo/jumpserver
refs/heads/master
apps/orgs/lock.py
1
from uuid import uuid4 from functools import wraps from django.core.cache import cache from django.db.transaction import atomic from rest_framework.request import Request from rest_framework.exceptions import NotAuthenticated from orgs.utils import current_org from common.exceptions import SomeoneIsDoingThis, Timeout from common.utils.timezone import dt_formater, now # Redis 中锁值得模板,该模板提供了很强的可读性,方便调试与排错 VALUE_TEMPLATE = '{stage}:{username}:{user_id}:{now}:{rand_str}' # 锁的状态 DOING = 'doing' # 处理中,此状态的锁可以被干掉 COMMITING = 'commiting' # 提交事务中,此状态很重要,要确保事务在锁消失之前返回了,不要轻易删除该锁 client = cache.client.get_client(write=True) """ 将锁的状态从 `doing` 切换到 `commiting` KEYS[1]: key ARGV[1]: doingvalue ARGV[2]: commitingvalue ARGV[3]: timeout """ change_lock_state_to_commiting_lua = ''' if (redis.call("get", KEYS[1]) == ARGV[1]) then return redis.call("set", KEYS[1], ARGV[2], "EX", ARGV[3], "XX") else return 0 end ''' change_lock_state_to_commiting_lua_obj = client.register_script(change_lock_state_to_commiting_lua) """ 释放锁,两种`value`都要检查`doing`和`commiting` KEYS[1]: key ARGV[1]: 两个 `value` 中的其中一个 ARGV[2]: 两个 `value` 中的其中一个 """ release_lua = ''' if (redis.call("get",KEYS[1]) == ARGV[1] or redis.call("get",KEYS[1]) == ARGV[2]) then return redis.call("del",KEYS[1]) else return 0 end ''' release_lua_obj = client.register_script(release_lua) def acquire(key, value, timeout): return client.set(key, value, ex=timeout, nx=True) def get(key): return client.get(key) def change_lock_state_to_commiting(key, doingvalue, commitingvalue, timeout=600): # 将锁的状态从 `doing` 切换到 `commiting` return bool(change_lock_state_to_commiting_lua_obj(keys=(key,), args=(doingvalue, commitingvalue, timeout))) def release(key, value1, value2): # 释放锁,两种`value` `doing`和`commiting` 都要检查 return release_lua_obj(keys=(key,), args=(value1, value2)) def _generate_value(request: Request, stage=DOING): # 不支持匿名用户 user = request.user if user.is_anonymous: raise NotAuthenticated return VALUE_TEMPLATE.format( stage=stage, username=user.username, user_id=user.id, now=dt_formater(now()), rand_str=uuid4() ) default_wait_msg = SomeoneIsDoingThis.default_detail def org_level_transaction_lock(key, timeout=300, wait_msg=default_wait_msg): """ 被装饰的 `View` 必须取消自身的 `ATOMIC_REQUESTS`,因为该装饰器要有事务的完全控制权 [官网](https://docs.djangoproject.com/en/3.1/topics/db/transactions/#tying-transactions-to-http-requests) 1. 获取锁:只有当锁对应的 `key` 不存在时成功获取,`value` 设置为 `doing` 2. 开启事务:本次请求的事务必须确保在这里开启 3. 执行 `View` 体 4. `View` 体执行结束未异常,此时事务还未提交 5. 检查锁是否过时,过时事务回滚,不过时,重新设置`key`延长`key`有效期,已确保足够时间提交事务,同时把`key`的状态改为`commiting` 6. 提交事务 7. 释放锁,释放的时候会检查`doing`与`commiting`的值,因为删除或者更改锁必须提供与当前锁的`value`相同的值,确保不误删 [锁参考文章](http://doc.redisfans.com/string/set.html#id2) """ def decorator(fun): @wraps(fun) def wrapper(request, *args, **kwargs): # `key`可能是组织相关的,如果是把组织`id`加上 _key = key.format(org_id=current_org.id) doing_value = _generate_value(request) commiting_value = _generate_value(request, stage=COMMITING) try: lock = acquire(_key, doing_value, timeout) if not lock: raise SomeoneIsDoingThis(detail=wait_msg) with atomic(savepoint=False): ret = fun(request, *args, **kwargs) # 提交事务前,检查一下锁是否还在 # 锁在的话,更新锁的状态为 `commiting`,延长锁时间,确保事务提交 # 锁不在的话回滚 ok = change_lock_state_to_commiting(_key, doing_value, commiting_value) if not ok: # 超时或者被中断了 raise Timeout return ret finally: # 释放锁,锁的两个值都要尝试,不确定异常是从什么位置抛出的 release(_key, commiting_value, doing_value) return wrapper return decorator
ianw/pip
refs/heads/develop
pip/locations.py
117
"""Locations where we look for configs, install stuff, etc""" from __future__ import absolute_import import getpass import os import os.path import site import sys import tempfile from distutils import sysconfig from distutils.command.install import install, SCHEME_KEYS from pip.compat import get_path_uid, WINDOWS from pip.utils import appdirs from pip import exceptions # Hack for flake8 install # CA Bundle Locations CA_BUNDLE_PATHS = [ # Debian/Ubuntu/Gentoo etc. "/etc/ssl/certs/ca-certificates.crt", # Fedora/RHEL "/etc/pki/tls/certs/ca-bundle.crt", # OpenSUSE "/etc/ssl/ca-bundle.pem", # OpenBSD "/etc/ssl/cert.pem", # FreeBSD/DragonFly "/usr/local/share/certs/ca-root-nss.crt", # Homebrew on OSX "/usr/local/etc/openssl/cert.pem", ] # Attempt to locate a CA Bundle that we can pass into requests, we have a list # of possible ones from various systems. If we cannot find one then we'll set # this to None so that we default to whatever requests is setup to handle. # # Note to Downstream: If you wish to disable this autodetection and simply use # whatever requests does (likely you've already patched # requests.certs.where()) then simply edit this line so # that it reads ``CA_BUNDLE_PATH = None``. CA_BUNDLE_PATH = next((x for x in CA_BUNDLE_PATHS if os.path.exists(x)), None) # Application Directories USER_CACHE_DIR = appdirs.user_cache_dir("pip") DELETE_MARKER_MESSAGE = '''\ This file is placed here by pip to indicate the source was put here by pip. Once this package is successfully installed this source code will be deleted (unless you remove this file). ''' PIP_DELETE_MARKER_FILENAME = 'pip-delete-this-directory.txt' def write_delete_marker_file(directory): """ Write the pip delete marker file into this directory. """ filepath = os.path.join(directory, PIP_DELETE_MARKER_FILENAME) with open(filepath, 'w') as marker_fp: marker_fp.write(DELETE_MARKER_MESSAGE) def running_under_virtualenv(): """ Return True if we're running inside a virtualenv, False otherwise. """ if hasattr(sys, 'real_prefix'): return True elif sys.prefix != getattr(sys, "base_prefix", sys.prefix): return True return False def virtualenv_no_global(): """ Return True if in a venv and no system site packages. """ # this mirrors the logic in virtualenv.py for locating the # no-global-site-packages.txt file site_mod_dir = os.path.dirname(os.path.abspath(site.__file__)) no_global_file = os.path.join(site_mod_dir, 'no-global-site-packages.txt') if running_under_virtualenv() and os.path.isfile(no_global_file): return True def __get_username(): """ Returns the effective username of the current process. """ if WINDOWS: return getpass.getuser() import pwd return pwd.getpwuid(os.geteuid()).pw_name def _get_build_prefix(): """ Returns a safe build_prefix """ path = os.path.join( tempfile.gettempdir(), 'pip_build_%s' % __get_username().replace(' ', '_') ) if WINDOWS: """ on windows(tested on 7) temp dirs are isolated """ return path try: os.mkdir(path) write_delete_marker_file(path) except OSError: file_uid = None try: # raises OSError for symlinks # https://github.com/pypa/pip/pull/935#discussion_r5307003 file_uid = get_path_uid(path) except OSError: file_uid = None if file_uid != os.geteuid(): msg = ( "The temporary folder for building (%s) is either not owned by" " you, or is a symlink." % path ) print(msg) print( "pip will not work until the temporary folder is either " "deleted or is a real directory owned by your user account." ) raise exceptions.InstallationError(msg) return path if running_under_virtualenv(): build_prefix = os.path.join(sys.prefix, 'build') src_prefix = os.path.join(sys.prefix, 'src') else: # Note: intentionally NOT using mkdtemp # See https://github.com/pypa/pip/issues/906 for plan to move to mkdtemp build_prefix = _get_build_prefix() # FIXME: keep src in cwd for now (it is not a temporary folder) try: src_prefix = os.path.join(os.getcwd(), 'src') except OSError: # In case the current working directory has been renamed or deleted sys.exit( "The folder you are executing pip from can no longer be found." ) # under Mac OS X + virtualenv sys.prefix is not properly resolved # it is something like /path/to/python/bin/.. # Note: using realpath due to tmp dirs on OSX being symlinks build_prefix = os.path.abspath(os.path.realpath(build_prefix)) src_prefix = os.path.abspath(src_prefix) # FIXME doesn't account for venv linked to global site-packages site_packages = sysconfig.get_python_lib() user_site = site.USER_SITE user_dir = os.path.expanduser('~') if WINDOWS: bin_py = os.path.join(sys.prefix, 'Scripts') bin_user = os.path.join(user_site, 'Scripts') # buildout uses 'bin' on Windows too? if not os.path.exists(bin_py): bin_py = os.path.join(sys.prefix, 'bin') bin_user = os.path.join(user_site, 'bin') config_basename = 'pip.ini' legacy_storage_dir = os.path.join(user_dir, 'pip') legacy_config_file = os.path.join( legacy_storage_dir, config_basename, ) else: bin_py = os.path.join(sys.prefix, 'bin') bin_user = os.path.join(user_site, 'bin') config_basename = 'pip.conf' legacy_storage_dir = os.path.join(user_dir, '.pip') legacy_config_file = os.path.join( legacy_storage_dir, config_basename, ) # Forcing to use /usr/local/bin for standard Mac OS X framework installs # Also log to ~/Library/Logs/ for use with the Console.app log viewer if sys.platform[:6] == 'darwin' and sys.prefix[:16] == '/System/Library/': bin_py = '/usr/local/bin' site_config_files = [ os.path.join(path, config_basename) for path in appdirs.site_config_dirs('pip') ] def distutils_scheme(dist_name, user=False, home=None, root=None, isolated=False): """ Return a distutils install scheme """ from distutils.dist import Distribution scheme = {} if isolated: extra_dist_args = {"script_args": ["--no-user-cfg"]} else: extra_dist_args = {} dist_args = {'name': dist_name} dist_args.update(extra_dist_args) d = Distribution(dist_args) d.parse_config_files() i = d.get_command_obj('install', create=True) # NOTE: setting user or home has the side-effect of creating the home dir # or user base for installations during finalize_options() # ideally, we'd prefer a scheme class that has no side-effects. i.user = user or i.user i.home = home or i.home i.root = root or i.root i.finalize_options() for key in SCHEME_KEYS: scheme[key] = getattr(i, 'install_' + key) if i.install_lib is not None: # install_lib takes precedence over purelib and platlib scheme.update(dict(purelib=i.install_lib, platlib=i.install_lib)) if running_under_virtualenv(): scheme['headers'] = os.path.join( sys.prefix, 'include', 'site', 'python' + sys.version[:3], dist_name, ) if root is not None: scheme["headers"] = os.path.join( root, os.path.abspath(scheme["headers"])[1:], ) return scheme
msabramo/ansible
refs/heads/devel
lib/ansible/modules/remote_management/ipmi/ipmi_power.py
69
#!/usr/bin/python # -*- coding: utf-8 -*- # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: ipmi_power short_description: Power management for machine description: - Use this module for power management version_added: "2.2" options: name: description: - Hostname or ip address of the BMC. required: true port: description: - Remote RMCP port. required: false default: 623 user: description: - Username to use to connect to the BMC. required: true password: description: - Password to connect to the BMC. required: true default: null state: description: - Whether to ensure that the machine in desired state. required: true choices: - on -- Request system turn on - off -- Request system turn off without waiting for OS to shutdown - shutdown -- Have system request OS proper shutdown - reset -- Request system reset without waiting for OS - boot -- If system is off, then 'on', else 'reset' timeout: description: - Maximum number of seconds before interrupt request. required: false default: 300 requirements: - "python >= 2.6" - pyghmi author: "Bulat Gaifullin (gaifullinbf@gmail.com)" ''' RETURN = ''' powerstate: description: The current power state of the machine. returned: success type: string sample: on ''' EXAMPLES = ''' # Ensure machine is powered on. - ipmi_power: name: test.testdomain.com user: admin password: password state: on ''' try: from pyghmi.ipmi import command except ImportError: command = None from ansible.module_utils.basic import * def main(): module = AnsibleModule( argument_spec=dict( name=dict(required=True), port=dict(default=623, type='int'), state=dict(required=True, choices=['on', 'off', 'shutdown', 'reset', 'boot']), user=dict(required=True, no_log=True), password=dict(required=True, no_log=True), timeout=dict(default=300, type='int'), ), supports_check_mode=True, ) if command is None: module.fail_json(msg='the python pyghmi module is required') name = module.params['name'] port = module.params['port'] user = module.params['user'] password = module.params['password'] state = module.params['state'] timeout = module.params['timeout'] # --- run command --- try: ipmi_cmd = command.Command( bmc=name, userid=user, password=password, port=port ) module.debug('ipmi instantiated - name: "%s"' % name) current = ipmi_cmd.get_power() if current['powerstate'] != state: response = {'powerstate': state} if module.check_mode else ipmi_cmd.set_power(state, wait=timeout) changed = True else: response = current changed = False if 'error' in response: module.fail_json(msg=response['error']) module.exit_json(changed=changed, **response) except Exception as e: module.fail_json(msg=str(e)) if __name__ == '__main__': main()
veger/ansible
refs/heads/devel
lib/ansible/modules/packaging/os/pkg5_publisher.py
102
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2014 Peter Oliver <ansible@mavit.org.uk> # # 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: pkg5_publisher author: "Peter Oliver (@mavit)" short_description: Manages Solaris 11 Image Packaging System publishers version_added: 1.9 description: - IPS packages are the native packages in Solaris 11 and higher. - This modules will configure which publishers a client will download IPS packages from. options: name: description: - The publisher's name. required: true aliases: [ publisher ] state: description: - Whether to ensure that a publisher is present or absent. default: present choices: [ present, absent ] sticky: description: - Packages installed from a sticky repository can only receive updates from that repository. type: bool enabled: description: - Is the repository enabled or disabled? type: bool origin: description: - A path or URL to the repository. - Multiple values may be provided. mirror: description: - A path or URL to the repository mirror. - Multiple values may be provided. ''' EXAMPLES = ''' # Fetch packages for the solaris publisher direct from Oracle: - pkg5_publisher: name: solaris sticky: true origin: https://pkg.oracle.com/solaris/support/ # Configure a publisher for locally-produced packages: - pkg5_publisher: name: site origin: 'https://pkg.example.com/site/' ''' from ansible.module_utils.basic import AnsibleModule def main(): module = AnsibleModule( argument_spec=dict( name=dict(required=True, aliases=['publisher']), state=dict(default='present', choices=['present', 'absent']), sticky=dict(type='bool'), enabled=dict(type='bool'), # search_after=dict(), # search_before=dict(), origin=dict(type='list'), mirror=dict(type='list'), ) ) for option in ['origin', 'mirror']: if module.params[option] == ['']: module.params[option] = [] if module.params['state'] == 'present': modify_publisher(module, module.params) else: unset_publisher(module, module.params['name']) def modify_publisher(module, params): name = params['name'] existing = get_publishers(module) if name in existing: for option in ['origin', 'mirror', 'sticky', 'enabled']: if params[option] is not None: if params[option] != existing[name][option]: return set_publisher(module, params) else: return set_publisher(module, params) module.exit_json() def set_publisher(module, params): name = params['name'] args = [] if params['origin'] is not None: args.append('--remove-origin=*') args.extend(['--add-origin=' + u for u in params['origin']]) if params['mirror'] is not None: args.append('--remove-mirror=*') args.extend(['--add-mirror=' + u for u in params['mirror']]) if params['sticky'] is not None and params['sticky']: args.append('--sticky') elif params['sticky'] is not None: args.append('--non-sticky') if params['enabled'] is not None and params['enabled']: args.append('--enable') elif params['enabled'] is not None: args.append('--disable') rc, out, err = module.run_command( ["pkg", "set-publisher"] + args + [name], check_rc=True ) response = { 'rc': rc, 'results': [out], 'msg': err, 'changed': True, } if rc != 0: module.fail_json(**response) module.exit_json(**response) def unset_publisher(module, publisher): if publisher not in get_publishers(module): module.exit_json() rc, out, err = module.run_command( ["pkg", "unset-publisher", publisher], check_rc=True ) response = { 'rc': rc, 'results': [out], 'msg': err, 'changed': True, } if rc != 0: module.fail_json(**response) module.exit_json(**response) def get_publishers(module): rc, out, err = module.run_command(["pkg", "publisher", "-Ftsv"], True) lines = out.splitlines() keys = lines.pop(0).lower().split("\t") publishers = {} for line in lines: values = dict(zip(keys, map(unstringify, line.split("\t")))) name = values['publisher'] if name not in publishers: publishers[name] = dict( (k, values[k]) for k in ['sticky', 'enabled'] ) publishers[name]['origin'] = [] publishers[name]['mirror'] = [] if values['type'] is not None: publishers[name][values['type']].append(values['uri']) return publishers def unstringify(val): if val == "-" or val == '': return None elif val == "true": return True elif val == "false": return False else: return val if __name__ == '__main__': main()
Peter92/MouseTrack
refs/heads/master
mousetracks/utils/os/mac/appkit/__init__.py
1
"""This is part of the Mouse Tracks Python application. Source: https://github.com/Peter92/MouseTracks """ #Mac functions that require AppKit #Thanks to /u/zlft for helping, still needs a lot of work from __future__ import absolute_import from AppKit import NSScreen from AppKit import NSEvent def get_resolution(): w = NSScreen.mainScreen().frame().size.width h = NSScreen.mainScreen().frame().size.height return (w, h) def get_cursor_pos(): d = NSEvent.mouseLocation() return (d.x, d.y) def get_monitor_locations(): """Not tested.""" result = [] for screen in NSScreen.screens(): rect = NSScreen.frame(screen) x, y = rect.origin.x, rect.origin.y width, height = rect.size.width, rect.size.height result.append(tuple(map(int, (x, y, x + width, y + height)))) return result
robjohnson189/home-assistant
refs/heads/dev
homeassistant/components/device_tracker/tplink.py
13
""" Support for TP-Link routers. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/device_tracker.tplink/ """ import base64 import hashlib import logging import re import threading from datetime import timedelta import requests import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA, DeviceScanner) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME from homeassistant.util import Throttle # Return cached results if last scan was less then this time ago MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5) _LOGGER = logging.getLogger(__name__) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string }) def get_scanner(hass, config): """Validate the configuration and return a TP-Link scanner.""" for cls in [Tplink4DeviceScanner, Tplink3DeviceScanner, Tplink2DeviceScanner, TplinkDeviceScanner]: scanner = cls(config[DOMAIN]) if scanner.success_init: return scanner return None class TplinkDeviceScanner(DeviceScanner): """This class queries a wireless router running TP-Link firmware.""" def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] username, password = config[CONF_USERNAME], config[CONF_PASSWORD] self.parse_macs = re.compile('[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-' + '[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}') self.host = host self.username = username self.password = password self.last_results = {} self.lock = threading.Lock() self.success_init = self._update_info() def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results # pylint: disable=no-self-use def get_device_name(self, device): """The firmware doesn't save the name of the wireless device.""" return None @Throttle(MIN_TIME_BETWEEN_SCANS) def _update_info(self): """Ensure the information from the TP-Link router is up to date. Return boolean if scanning successful. """ with self.lock: _LOGGER.info("Loading wireless clients...") url = 'http://{}/userRpm/WlanStationRpm.htm'.format(self.host) referer = 'http://{}'.format(self.host) page = requests.get(url, auth=(self.username, self.password), headers={'referer': referer}) result = self.parse_macs.findall(page.text) if result: self.last_results = [mac.replace("-", ":") for mac in result] return True return False class Tplink2DeviceScanner(TplinkDeviceScanner): """This class queries a router with newer version of TP-Link firmware.""" def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results.keys() # pylint: disable=no-self-use def get_device_name(self, device): """The firmware doesn't save the name of the wireless device.""" return self.last_results.get(device) @Throttle(MIN_TIME_BETWEEN_SCANS) def _update_info(self): """Ensure the information from the TP-Link router is up to date. Return boolean if scanning successful. """ with self.lock: _LOGGER.info("Loading wireless clients...") url = 'http://{}/data/map_access_wireless_client_grid.json' \ .format(self.host) referer = 'http://{}'.format(self.host) # Router uses Authorization cookie instead of header # Let's create the cookie username_password = '{}:{}'.format(self.username, self.password) b64_encoded_username_password = base64.b64encode( username_password.encode('ascii') ).decode('ascii') cookie = 'Authorization=Basic {}' \ .format(b64_encoded_username_password) response = requests.post(url, headers={'referer': referer, 'cookie': cookie}) try: result = response.json().get('data') except ValueError: _LOGGER.error("Router didn't respond with JSON. " "Check if credentials are correct.") return False if result: self.last_results = { device['mac_addr'].replace('-', ':'): device['name'] for device in result } return True return False class Tplink3DeviceScanner(TplinkDeviceScanner): """This class queries the Archer C9 router with version 150811 or high.""" def __init__(self, config): """Initialize the scanner.""" self.stok = '' self.sysauth = '' super(Tplink3DeviceScanner, self).__init__(config) def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results.keys() # pylint: disable=no-self-use def get_device_name(self, device): """The firmware doesn't save the name of the wireless device. We are forced to use the MAC address as name here. """ return self.last_results.get(device) def _get_auth_tokens(self): """Retrieve auth tokens from the router.""" _LOGGER.info("Retrieving auth tokens...") url = 'http://{}/cgi-bin/luci/;stok=/login?form=login' \ .format(self.host) referer = 'http://{}/webpages/login.html'.format(self.host) # If possible implement rsa encryption of password here. response = requests.post(url, params={'operation': 'login', 'username': self.username, 'password': self.password}, headers={'referer': referer}) try: self.stok = response.json().get('data').get('stok') _LOGGER.info(self.stok) regex_result = re.search('sysauth=(.*);', response.headers['set-cookie']) self.sysauth = regex_result.group(1) _LOGGER.info(self.sysauth) return True except ValueError: _LOGGER.error("Couldn't fetch auth tokens!") return False @Throttle(MIN_TIME_BETWEEN_SCANS) def _update_info(self): """Ensure the information from the TP-Link router is up to date. Return boolean if scanning successful. """ with self.lock: if (self.stok == '') or (self.sysauth == ''): self._get_auth_tokens() _LOGGER.info("Loading wireless clients...") url = ('http://{}/cgi-bin/luci/;stok={}/admin/wireless?' 'form=statistics').format(self.host, self.stok) referer = 'http://{}/webpages/index.html'.format(self.host) response = requests.post(url, params={'operation': 'load'}, headers={'referer': referer}, cookies={'sysauth': self.sysauth}) try: json_response = response.json() if json_response.get('success'): result = response.json().get('data') else: if json_response.get('errorcode') == 'timeout': _LOGGER.info("Token timed out. " "Relogging on next scan.") self.stok = '' self.sysauth = '' return False else: _LOGGER.error("An unknown error happened " "while fetching data.") return False except ValueError: _LOGGER.error("Router didn't respond with JSON. " "Check if credentials are correct.") return False if result: self.last_results = { device['mac'].replace('-', ':'): device['mac'] for device in result } return True return False class Tplink4DeviceScanner(TplinkDeviceScanner): """This class queries an Archer C7 router with TP-Link firmware 150427.""" def __init__(self, config): """Initialize the scanner.""" self.credentials = '' self.token = '' super(Tplink4DeviceScanner, self).__init__(config) def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results # pylint: disable=no-self-use def get_device_name(self, device): """The firmware doesn't save the name of the wireless device.""" return None def _get_auth_tokens(self): """Retrieve auth tokens from the router.""" _LOGGER.info("Retrieving auth tokens...") url = 'http://{}/userRpm/LoginRpm.htm?Save=Save'.format(self.host) # Generate md5 hash of password. The C7 appears to use the first 15 # characters of the password only, so we truncate to remove additional # characters from being hashed. password = hashlib.md5(self.password.encode('utf')[:15]).hexdigest() credentials = '{}:{}'.format(self.username, password).encode('utf') # Encode the credentials to be sent as a cookie. self.credentials = base64.b64encode(credentials).decode('utf') # Create the authorization cookie. cookie = 'Authorization=Basic {}'.format(self.credentials) response = requests.get(url, headers={'cookie': cookie}) try: result = re.search(r'window.parent.location.href = ' r'"https?:\/\/.*\/(.*)\/userRpm\/Index.htm";', response.text) if not result: return False self.token = result.group(1) return True except ValueError: _LOGGER.error("Couldn't fetch auth tokens!") return False @Throttle(MIN_TIME_BETWEEN_SCANS) def _update_info(self): """Ensure the information from the TP-Link router is up to date. Return boolean if scanning successful. """ with self.lock: if (self.credentials == '') or (self.token == ''): self._get_auth_tokens() _LOGGER.info("Loading wireless clients...") mac_results = [] # Check both the 2.4GHz and 5GHz client list URLs for clients_url in ('WlanStationRpm.htm', 'WlanStationRpm_5g.htm'): url = 'http://{}/{}/userRpm/{}' \ .format(self.host, self.token, clients_url) referer = 'http://{}'.format(self.host) cookie = 'Authorization=Basic {}'.format(self.credentials) page = requests.get(url, headers={ 'cookie': cookie, 'referer': referer }) mac_results.extend(self.parse_macs.findall(page.text)) if not mac_results: return False self.last_results = [mac.replace("-", ":") for mac in mac_results] return True
slozier/ironpython2
refs/heads/master
Tests/compat/sbs_exceptions/try_finally3.py
2
# Licensed to the .NET Foundation under one or more agreements. # The .NET Foundation licenses this file to you under the Apache 2.0 License. # See the LICENSE file in the project root for more information. from common import runtests from .shared import try_finally_maker3 from .shared import setGenerator, test_exceptions setGenerator(try_finally_maker3) runtests(test_exceptions)
NoelMacwan/SXDNickiUnified
refs/heads/master
scripts/build-all.py
1182
#! /usr/bin/env python # Copyright (c) 2009-2011, The Linux Foundation. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of The Linux Foundation 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, FITNESS FOR A PARTICULAR PURPOSE AND # NON-INFRINGEMENT 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. # Build the kernel for all targets using the Android build environment. # # TODO: Accept arguments to indicate what to build. import glob from optparse import OptionParser import subprocess import os import os.path import shutil import sys version = 'build-all.py, version 0.01' build_dir = '../all-kernels' make_command = ["vmlinux", "modules"] make_env = os.environ make_env.update({ 'ARCH': 'arm', 'CROSS_COMPILE': 'arm-none-linux-gnueabi-', 'KCONFIG_NOTIMESTAMP': 'true' }) all_options = {} def error(msg): sys.stderr.write("error: %s\n" % msg) def fail(msg): """Fail with a user-printed message""" error(msg) sys.exit(1) def check_kernel(): """Ensure that PWD is a kernel directory""" if (not os.path.isfile('MAINTAINERS') or not os.path.isfile('arch/arm/mach-msm/Kconfig')): fail("This doesn't seem to be an MSM kernel dir") def check_build(): """Ensure that the build directory is present.""" if not os.path.isdir(build_dir): try: os.makedirs(build_dir) except OSError as exc: if exc.errno == errno.EEXIST: pass else: raise def update_config(file, str): print 'Updating %s with \'%s\'\n' % (file, str) defconfig = open(file, 'a') defconfig.write(str + '\n') defconfig.close() def scan_configs(): """Get the full list of defconfigs appropriate for this tree.""" names = {} for n in glob.glob('arch/arm/configs/[fm]sm[0-9-]*_defconfig'): names[os.path.basename(n)[:-10]] = n for n in glob.glob('arch/arm/configs/qsd*_defconfig'): names[os.path.basename(n)[:-10]] = n for n in glob.glob('arch/arm/configs/apq*_defconfig'): names[os.path.basename(n)[:-10]] = n return names class Builder: def __init__(self, logname): self.logname = logname self.fd = open(logname, 'w') def run(self, args): devnull = open('/dev/null', 'r') proc = subprocess.Popen(args, stdin=devnull, env=make_env, bufsize=0, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) count = 0 # for line in proc.stdout: rawfd = proc.stdout.fileno() while True: line = os.read(rawfd, 1024) if not line: break self.fd.write(line) self.fd.flush() if all_options.verbose: sys.stdout.write(line) sys.stdout.flush() else: for i in range(line.count('\n')): count += 1 if count == 64: count = 0 print sys.stdout.write('.') sys.stdout.flush() print result = proc.wait() self.fd.close() return result failed_targets = [] def build(target): dest_dir = os.path.join(build_dir, target) log_name = '%s/log-%s.log' % (build_dir, target) print 'Building %s in %s log %s' % (target, dest_dir, log_name) if not os.path.isdir(dest_dir): os.mkdir(dest_dir) defconfig = 'arch/arm/configs/%s_defconfig' % target dotconfig = '%s/.config' % dest_dir savedefconfig = '%s/defconfig' % dest_dir shutil.copyfile(defconfig, dotconfig) devnull = open('/dev/null', 'r') subprocess.check_call(['make', 'O=%s' % dest_dir, '%s_defconfig' % target], env=make_env, stdin=devnull) devnull.close() if not all_options.updateconfigs: build = Builder(log_name) result = build.run(['make', 'O=%s' % dest_dir] + make_command) if result != 0: if all_options.keep_going: failed_targets.append(target) fail_or_error = error else: fail_or_error = fail fail_or_error("Failed to build %s, see %s" % (target, build.logname)) # Copy the defconfig back. if all_options.configs or all_options.updateconfigs: devnull = open('/dev/null', 'r') subprocess.check_call(['make', 'O=%s' % dest_dir, 'savedefconfig'], env=make_env, stdin=devnull) devnull.close() shutil.copyfile(savedefconfig, defconfig) def build_many(allconf, targets): print "Building %d target(s)" % len(targets) for target in targets: if all_options.updateconfigs: update_config(allconf[target], all_options.updateconfigs) build(target) if failed_targets: fail('\n '.join(["Failed targets:"] + [target for target in failed_targets])) def main(): global make_command check_kernel() check_build() configs = scan_configs() usage = (""" %prog [options] all -- Build all targets %prog [options] target target ... -- List specific targets %prog [options] perf -- Build all perf targets %prog [options] noperf -- Build all non-perf targets""") parser = OptionParser(usage=usage, version=version) parser.add_option('--configs', action='store_true', dest='configs', help="Copy configs back into tree") parser.add_option('--list', action='store_true', dest='list', help='List available targets') parser.add_option('-v', '--verbose', action='store_true', dest='verbose', help='Output to stdout in addition to log file') parser.add_option('--oldconfig', action='store_true', dest='oldconfig', help='Only process "make oldconfig"') parser.add_option('--updateconfigs', dest='updateconfigs', help="Update defconfigs with provided option setting, " "e.g. --updateconfigs=\'CONFIG_USE_THING=y\'") parser.add_option('-j', '--jobs', type='int', dest="jobs", help="Number of simultaneous jobs") parser.add_option('-l', '--load-average', type='int', dest='load_average', help="Don't start multiple jobs unless load is below LOAD_AVERAGE") parser.add_option('-k', '--keep-going', action='store_true', dest='keep_going', default=False, help="Keep building other targets if a target fails") parser.add_option('-m', '--make-target', action='append', help='Build the indicated make target (default: %s)' % ' '.join(make_command)) (options, args) = parser.parse_args() global all_options all_options = options if options.list: print "Available targets:" for target in configs.keys(): print " %s" % target sys.exit(0) if options.oldconfig: make_command = ["oldconfig"] elif options.make_target: make_command = options.make_target if options.jobs: make_command.append("-j%d" % options.jobs) if options.load_average: make_command.append("-l%d" % options.load_average) if args == ['all']: build_many(configs, configs.keys()) elif args == ['perf']: targets = [] for t in configs.keys(): if "perf" in t: targets.append(t) build_many(configs, targets) elif args == ['noperf']: targets = [] for t in configs.keys(): if "perf" not in t: targets.append(t) build_many(configs, targets) elif len(args) > 0: targets = [] for t in args: if t not in configs.keys(): parser.error("Target '%s' not one of %s" % (t, configs.keys())) targets.append(t) build_many(configs, targets) else: parser.error("Must specify a target to build, or 'all'") if __name__ == "__main__": main()
huxh10/iSDX
refs/heads/master
plot/plot-simple.py
1
#! /usr/bin/python import sys import matplotlib.pyplot as plt if len(sys.argv) == 1: print "please input latency files: ./plot.py [file1] [label1] [file2] [label2] .." exit(0) data = [] labels = [] for i in range(1, len(sys.argv)): if i % 2 != 0: with open(sys.argv[i], 'r') as f: data.append(map(lambda x: int(x[:-1].split(' ')[1]), f.readlines())) else: labels.append(sys.argv[i]) f = plt.figure() plt.boxplot(data, notch = 0, sym = '', vert = 1, whis = 1.4, labels = labels) # plot #plt.boxplot(data, notch = 0, sym = '', vert = 1, whis = 1.4, labels = labels) plt.gca().yaxis.grid(True) plt.yscale('log') #plt.legend(prop={'size':6}) plt.xlabel('RIB Entry Number') plt.ylabel('Time (us)') plt.title('SIX-PACK compute time for BGP updates') #plt.show() f.savefig('result_box.pdf', bbox_inches='tight')
xu-cheng/youtube-dl
refs/heads/master
youtube_dl/downloader/__init__.py
4
from __future__ import unicode_literals from .common import FileDownloader from .hls import HlsFD from .hls import NativeHlsFD from .http import HttpFD from .mplayer import MplayerFD from .rtmp import RtmpFD from .f4m import F4mFD from ..utils import ( determine_ext, ) def get_suitable_downloader(info_dict): """Get the downloader class that can handle the info dict.""" url = info_dict['url'] protocol = info_dict.get('protocol') if url.startswith('rtmp'): return RtmpFD if protocol == 'm3u8_native': return NativeHlsFD if (protocol == 'm3u8') or (protocol is None and determine_ext(url) == 'm3u8'): return HlsFD if url.startswith('mms') or url.startswith('rtsp'): return MplayerFD if determine_ext(url) == 'f4m': return F4mFD else: return HttpFD
JorgeCoock/django
refs/heads/master
django/contrib/staticfiles/apps.py
473
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class StaticFilesConfig(AppConfig): name = 'django.contrib.staticfiles' verbose_name = _("Static Files")
LiJingkang/PyQt5
refs/heads/master
Learn/高级特性/PyQt5_组件_切换按钮.py
1
# 切换按钮是QPushButton的特殊模式 # 切换按钮有两种状态:按下和没有按下。我们可以通过点击它在两种状态之间切换。 import sys from PyQt5.QtWidgets import (QWidget, QPushButton, QFrame, QApplication) from PyQt5.QtGui import QColor class Example(QWidget): # 一个QWidget组件 def __init__(self): super().__init__() self.initUI() def initUI(self): self.col = QColor(0, 0, 0) # QPuchButton redb = QPushButton('Red', self) # 设置他可以被选中 redb.setCheckable(True) redb.move(10, 10) # 我们把clicked信号连接到我们定义的方法上。 # 我们使用clicked信号来操作布尔值。 redb.clicked[bool].connect(self.setColor) greenb = QPushButton('Green', self) greenb.setCheckable(True) greenb.move(10, 60) greenb.clicked[bool].connect(self.setColor) blueb = QPushButton('Blue', self) blueb.setCheckable(True) blueb.move(10, 110) blueb.clicked[bool].connect(self.setColor) self.square = QFrame(self) self.square.setGeometry(150, 20, 100, 100) self.square.setStyleSheet("QWidget { background-color: %s }" % self.col.name()) self.setGeometry(300, 300, 280, 170) self.setWindowTitle('Toggle button') self.show() def setColor(self, pressed): source = self.sender() if pressed: val = 255 else: val = 0 if source.text() == "Red": self.col.setRed(val) elif source.text() == "Green": self.col.setGreen(val) else: self.col.setBlue(val) self.square.setStyleSheet("QFrame { background-color: %s }" % self.col.name()) if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
saurabh6790/medsyn-app1
refs/heads/master
patches/september_2012/all_permissions_patch.py
30
# 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 webnotes def execute(): web_cache_perms() stock_perms() project_perms() account_perms() def web_cache_perms(): webnotes.conn.sql("""update `tabDocPerm` set role='Guest' where parent='Web Cache' and role='All' and permlevel=0""") def project_perms(): webnotes.conn.sql("""delete from `tabDocPerm` where parent in ('Task', 'Project Activity') and role='All'""") def stock_perms(): webnotes.conn.sql("""delete from `tabDocPerm` where parent in ('Landed Cost Wizard', 'Sales and Purchase Return Tool') and role='All' and permlevel=0""") def account_perms(): # since it is a child doctype, it does not need permissions webnotes.conn.sql("""delete from tabDocPerm where parent='TDS Detail'""")
woiddei/pattern
refs/heads/master
pattern/text/xx/__init__.py
21
#### PATTERN | XX ################################################################################## # -*- coding: utf-8 -*- # Copyright (c) year, institute, country # Author: Name (e-mail) # License: BSD (see LICENSE.txt for details). # http://www.clips.ua.ac.be/pages/pattern #################################################################################################### # Template for pattern.xx, bundling natural language processing tools for language XXXXX. # The module bundles a shallow parser (part-of-speech tagger, chunker, lemmatizer) # with functions for word inflection (singularization, pluralization, conjugation) # and sentiment analysis. # Base classes for the parser, verb table and sentiment lexicon are inherited from pattern.text. # The parser can be subclassed with a custom tokenizer (finds sentence boundaries) # and lemmatizer (uses word inflection to find the base form of words). # The part-of-speech tagger requires a lexicon of tagged known words and rules for unknown words. # Tools for word inflection should be bundled in pattern.text.xx.inflect. import os import sys try: MODULE = os.path.dirname(os.path.realpath(__file__)) except: MODULE = "" sys.path.insert(0, os.path.join(MODULE, "..", "..", "..", "..")) # Import parser base classes. from pattern.text import ( Lexicon, Model, Morphology, Context, Parser as _Parser, ngrams, pprint, commandline, PUNCTUATION ) # Import parse tree base classes. from pattern.text.tree import ( Tree, Text, Sentence, Slice, Chunk, PNPChunk, Chink, Word, table, SLASH, WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA, AND, OR ) # Import sentiment analysis base classes. from pattern.text import ( Sentiment, NOUN, VERB, ADJECTIVE, ADVERB, MOOD, IRONY ) # Import spelling base class. from pattern.text import ( Spelling ) # Import verb tenses. from pattern.text import ( INFINITIVE, PRESENT, PAST, FUTURE, FIRST, SECOND, THIRD, SINGULAR, PLURAL, SG, PL, PROGRESSIVE, PARTICIPLE ) # Import inflection functions. from pattern.text.xx.inflect import ( article, referenced, DEFINITE, INDEFINITE, pluralize, singularize, NOUN, VERB, ADJECTIVE, verbs, conjugate, lemma, lexeme, tenses, predicative, attributive ) # Import all submodules. from pattern.text.xx import inflect sys.path.pop(0) #--- PARSER ---------------------------------------------------------------------------------------- # Pattern uses the Penn Treebank II tagset (http://www.clips.ua.ac.be/pages/penn-treebank-tagset). # The lexicon for pattern.xx may be using a different tagset (e.g., PAROLE, WOTAN). # The following functions are meant to map the tags to Penn Treebank II, see Parser.find_chunks(). TAGSET = {"??": "NN"} # pattern.xx tagset => Penn Treebank II. def tagset2penntreebank(tag): return TAGSET.get(tag, tag) # Different languages have different contractions (e.g., English "I've" or French "j'ai") # and abbreviations. The following functions define contractions and abbreviations # for pattern.xx, see also Parser.find_tokens(). REPLACEMENTS = {"'s": " 's", "'ve": " 've"} ABBREVIATIONS = set(("e.g.", "etc.", "i.e.")) # A lemmatizer can be constructed if we have a pattern.xx.inflect, # with functions for noun singularization and verb conjugation (i.e., infinitives). def find_lemmata(tokens): """ Annotates the tokens with lemmata for plural nouns and conjugated verbs, where each token is a [word, part-of-speech] list. """ for token in tokens: word, pos, lemma = token[0], token[1], token[0] if pos.startswith("JJ"): lemma = predicative(word) if pos == "NNS": lemma = singularize(word) if pos.startswith(("VB", "MD")): lemma = conjugate(word, INFINITIVE) or word token.append(lemma.lower()) return tokens # Subclass the base parser with the language-specific functionality: class Parser(_Parser): def find_tokens(self, tokens, **kwargs): kwargs.setdefault("abbreviations", ABBREVIATIONS) kwargs.setdefault("replace", REPLACEMENTS) return _Parser.find_tokens(self, tokens, **kwargs) def find_tags(self, tokens, **kwargs): kwargs.setdefault("map", tagset2penntreebank) return _Parser.find_tags(self, tokens, **kwargs) def find_chunks(self, tokens, **kwargs): return _Parser.find_chunks(self, tokens, **kwargs) def find_lemmata(self, tokens, **kwargs): return find_lemmata(tokens) # The parser's part-of-speech tagger requires a lexicon of tagged known words, # and rules for unknown words. See pattern.text.Morphology and pattern.text.Context # for further details. A tutorial on how to acquire data for the lexicon is here: # http://www.clips.ua.ac.be/pages/using-wiktionary-to-build-an-italian-part-of-speech-tagger # Create the parser with default tags for unknown words: # (noun, proper noun, numeric). parser = Parser( lexicon = os.path.join(MODULE, "xx-lexicon.txt"), # A dict of known words => most frequent tag. frequency = os.path.join(MODULE, "xx-frequency.txt"), # A dict of word frequency. morphology = os.path.join(MODULE, "xx-morphology.txt"), # A set of suffix rules. context = os.path.join(MODULE, "xx-context.txt"), # A set of contextual rules. entities = os.path.join(MODULE, "xx-entities.txt"), # A dict of named entities: John = NNP-PERS. default = ("NN", "NNP", "CD"), language = "xx" ) lexicon = parser.lexicon # Expose lexicon. # Create the sentiment lexicon, # see pattern/text/xx/xx-sentiment.xml for further details. # We also need to define the tag for modifiers, # words that modify the score of the following word # (e.g., *very* good, *not good, ...) sentiment = Sentiment( path = os.path.join(MODULE, "xx-sentiment.xml"), synset = None, negations = ("no", "not", "never"), modifiers = ("RB",), modifier = lambda w: w.endswith("ly"), # brilliantly, hardly, partially, ... language = "xx" ) # Nothing should be changed below. def tokenize(s, *args, **kwargs): """ Returns a list of sentences, where punctuation marks have been split from words. """ return parser.find_tokens(s, *args, **kwargs) def parse(s, *args, **kwargs): """ Returns a tagged Unicode string. """ return parser.parse(s, *args, **kwargs) def parsetree(s, *args, **kwargs): """ Returns a parsed Text from the given string. """ return Text(parse(s, *args, **kwargs)) def tree(s, token=[WORD, POS, CHUNK, PNP, REL, LEMMA]): """ Returns a parsed Text from the given parsed string. """ return Text(s, token) def tag(s, tokenize=True, encoding="utf-8", **kwargs): """ Returns a list of (token, tag)-tuples from the given string. """ tags = [] for sentence in parse(s, tokenize, True, False, False, False, encoding, **kwargs).split(): for token in sentence: tags.append((token[0], token[1])) return tags def keywords(s, top=10, **kwargs): """ Returns a sorted list of keywords in the given string. """ return parser.find_keywords(s, **dict({ "frequency": parser.frequency, "top": top, "pos": ("NN",), "ignore": ("rt",)}, **kwargs)) def polarity(s, **kwargs): """ Returns the sentence polarity (positive/negative) between -1.0 and 1.0. """ return sentiment(s, **kwargs)[0] def subjectivity(s, **kwargs): """ Returns the sentence subjectivity (objective/subjective) between 0.0 and 1.0. """ return sentiment(s, **kwargs)[1] def positive(s, threshold=0.1, **kwargs): """ Returns True if the given sentence has a positive sentiment. """ return polarity(s, **kwargs) >= threshold split = tree # Backwards compatibility. #--------------------------------------------------------------------------------------------------- # python -m pattern.xx xml -s "..." -OTCL if __name__ == "__main__": commandline(parse)
jjmiranda/edx-platform
refs/heads/master
common/lib/xmodule/xmodule/modulestore/split_mongo/caching_descriptor_system.py
21
import sys import logging from contracts import contract, new_contract from fs.osfs import OSFS from lazy import lazy from xblock.runtime import KvsFieldData, KeyValueStore from xblock.fields import ScopeIds from xblock.core import XBlock from opaque_keys.edx.locator import BlockUsageLocator, LocalId, CourseLocator, LibraryLocator, DefinitionLocator from xmodule.library_tools import LibraryToolsService from xmodule.mako_module import MakoDescriptorSystem from xmodule.error_module import ErrorDescriptor from xmodule.errortracker import exc_info_to_str from xmodule.modulestore import BlockData from xmodule.modulestore.edit_info import EditInfoRuntimeMixin from xmodule.modulestore.exceptions import ItemNotFoundError from xmodule.modulestore.inheritance import inheriting_field_data, InheritanceMixin from xmodule.modulestore.split_mongo import BlockKey, CourseEnvelope from xmodule.modulestore.split_mongo.id_manager import SplitMongoIdManager from xmodule.modulestore.split_mongo.definition_lazy_loader import DefinitionLazyLoader from xmodule.modulestore.split_mongo.split_mongo_kvs import SplitMongoKVS from xmodule.x_module import XModuleMixin log = logging.getLogger(__name__) new_contract('BlockUsageLocator', BlockUsageLocator) new_contract('CourseLocator', CourseLocator) new_contract('LibraryLocator', LibraryLocator) new_contract('BlockKey', BlockKey) new_contract('BlockData', BlockData) new_contract('CourseEnvelope', CourseEnvelope) new_contract('XBlock', XBlock) class CachingDescriptorSystem(MakoDescriptorSystem, EditInfoRuntimeMixin): """ A system that has a cache of a course version's json that it will use to load modules from, with a backup of calling to the underlying modulestore for more data. Computes the settings (nee 'metadata') inheritance upon creation. """ @contract(course_entry=CourseEnvelope) def __init__(self, modulestore, course_entry, default_class, module_data, lazy, **kwargs): """ Computes the settings inheritance and sets up the cache. modulestore: the module store that can be used to retrieve additional modules course_entry: the originally fetched enveloped course_structure w/ branch and course id info. Callers to _load_item provide an override but that function ignores the provided structure and only looks at the branch and course id module_data: a dict mapping Location -> json that was cached from the underlying modulestore """ # needed by capa_problem (as runtime.filestore via this.resources_fs) if course_entry.course_key.course: root = modulestore.fs_root / course_entry.course_key.org / course_entry.course_key.course / course_entry.course_key.run else: root = modulestore.fs_root / str(course_entry.structure['_id']) root.makedirs_p() # create directory if it doesn't exist id_manager = SplitMongoIdManager(self) kwargs.setdefault('id_reader', id_manager) kwargs.setdefault('id_generator', id_manager) super(CachingDescriptorSystem, self).__init__( field_data=None, load_item=self._load_item, resources_fs=OSFS(root), **kwargs ) self.modulestore = modulestore self.course_entry = course_entry # set course_id attribute to avoid problems with subsystems that expect # it here. (grading, for example) self.course_id = course_entry.course_key self.lazy = lazy self.module_data = module_data self.default_class = default_class self.local_modules = {} self._services['library_tools'] = LibraryToolsService(modulestore) @lazy @contract(returns="dict(BlockKey: BlockKey)") def _parent_map(self): parent_map = {} for block_key, block in self.course_entry.structure['blocks'].iteritems(): for child in block.fields.get('children', []): parent_map[child] = block_key return parent_map @contract(usage_key="BlockUsageLocator | BlockKey", course_entry_override="CourseEnvelope | None") def _load_item(self, usage_key, course_entry_override=None, **kwargs): """ Instantiate the xblock fetching it either from the cache or from the structure :param course_entry_override: the course_info with the course_key to use (defaults to cached) """ # usage_key is either a UsageKey or just the block_key. if a usage_key, if isinstance(usage_key, BlockUsageLocator): # trust the passed in key to know the caller's expectations of which fields are filled in. # particularly useful for strip_keys so may go away when we're version aware course_key = usage_key.course_key if isinstance(usage_key.block_id, LocalId): try: return self.local_modules[usage_key] except KeyError: raise ItemNotFoundError else: block_key = BlockKey.from_usage_key(usage_key) version_guid = self.course_entry.course_key.version_guid else: block_key = usage_key course_info = course_entry_override or self.course_entry course_key = course_info.course_key version_guid = course_key.version_guid # look in cache cached_module = self.modulestore.get_cached_block(course_key, version_guid, block_key) if cached_module: return cached_module block_data = self.get_module_data(block_key, course_key) class_ = self.load_block_type(block_data.block_type) block = self.xblock_from_json(class_, course_key, block_key, block_data, course_entry_override, **kwargs) self.modulestore.cache_block(course_key, version_guid, block_key, block) return block @contract(block_key=BlockKey, course_key="CourseLocator | LibraryLocator") def get_module_data(self, block_key, course_key): """ Get block from module_data adding it to module_data if it's not already there but is in the structure Raises: ItemNotFoundError if block is not in the structure """ json_data = self.module_data.get(block_key) if json_data is None: # deeper than initial descendant fetch or doesn't exist self.modulestore.cache_items(self, [block_key], course_key, lazy=self.lazy) json_data = self.module_data.get(block_key) if json_data is None: raise ItemNotFoundError(block_key) return json_data # xblock's runtime does not always pass enough contextual information to figure out # which named container (course x branch) or which parent is requesting an item. Because split allows # a many:1 mapping from named containers to structures and because item's identities encode # context as well as unique identity, this function must sometimes infer whether the access is # within an unspecified named container. In most cases, course_entry_override will give the # explicit context; however, runtime.get_block(), e.g., does not. HOWEVER, there are simple heuristics # which will work 99.999% of the time: a runtime is thread & even context specific. The likelihood that # the thread is working with more than one named container pointing to the same specific structure is # low; thus, the course_entry is most likely correct. If the thread is looking at > 1 named container # pointing to the same structure, the access is likely to be chunky enough that the last known container # is the intended one when not given a course_entry_override; thus, the caching of the last branch/course id. @contract(block_key="BlockKey | None") def xblock_from_json(self, class_, course_key, block_key, block_data, course_entry_override=None, **kwargs): """ Load and return block info. """ if course_entry_override is None: course_entry_override = self.course_entry else: # most recent retrieval is most likely the right one for next caller (see comment above fn) self.course_entry = CourseEnvelope(course_entry_override.course_key, self.course_entry.structure) definition_id = block_data.definition # If no usage id is provided, generate an in-memory id if block_key is None: block_key = BlockKey(block_data.block_type, LocalId()) convert_fields = lambda field: self.modulestore.convert_references_to_keys( course_key, class_, field, self.course_entry.structure['blocks'], ) if definition_id is not None and not block_data.definition_loaded: definition_loader = DefinitionLazyLoader( self.modulestore, course_key, block_key.type, definition_id, convert_fields, ) else: definition_loader = None # If no definition id is provide, generate an in-memory id if definition_id is None: definition_id = LocalId() # Construct the Block Usage Locator: block_locator = course_key.make_usage_key( block_type=block_key.type, block_id=block_key.id, ) converted_fields = convert_fields(block_data.fields) converted_defaults = convert_fields(block_data.defaults) if block_key in self._parent_map: parent_key = self._parent_map[block_key] parent = course_key.make_usage_key(parent_key.type, parent_key.id) else: parent = None aside_fields = None # for the situation if block_data has no asides attribute # (in case it was taken from memcache) try: if block_data.asides: aside_fields = {block_key.type: {}} for aside in block_data.asides: aside_fields[block_key.type].update(aside['fields']) except AttributeError: pass try: kvs = SplitMongoKVS( definition_loader, converted_fields, converted_defaults, parent=parent, aside_fields=aside_fields, field_decorator=kwargs.get('field_decorator') ) if InheritanceMixin in self.modulestore.xblock_mixins: field_data = inheriting_field_data(kvs) else: field_data = KvsFieldData(kvs) module = self.construct_xblock_from_class( class_, ScopeIds(None, block_key.type, definition_id, block_locator), field_data, for_parent=kwargs.get('for_parent') ) except Exception: # pylint: disable=broad-except log.warning("Failed to load descriptor", exc_info=True) return ErrorDescriptor.from_json( block_data, self, course_entry_override.course_key.make_usage_key( block_type='error', block_id=block_key.id ), error_msg=exc_info_to_str(sys.exc_info()) ) edit_info = block_data.edit_info module._edited_by = edit_info.edited_by # pylint: disable=protected-access module._edited_on = edit_info.edited_on # pylint: disable=protected-access module.previous_version = edit_info.previous_version module.update_version = edit_info.update_version module.source_version = edit_info.source_version module.definition_locator = DefinitionLocator(block_key.type, definition_id) for wrapper in self.modulestore.xblock_field_data_wrappers: module._field_data = wrapper(module, module._field_data) # pylint: disable=protected-access # decache any pending field settings module.save() # If this is an in-memory block, store it in this system if isinstance(block_locator.block_id, LocalId): self.local_modules[block_locator] = module return module def get_edited_by(self, xblock): """ See :meth: cms.lib.xblock.runtime.EditInfoRuntimeMixin.get_edited_by """ return xblock._edited_by def get_edited_on(self, xblock): """ See :class: cms.lib.xblock.runtime.EditInfoRuntimeMixin """ return xblock._edited_on @contract(xblock='XBlock') def get_subtree_edited_by(self, xblock): """ See :class: cms.lib.xblock.runtime.EditInfoRuntimeMixin """ # pylint: disable=protected-access if not hasattr(xblock, '_subtree_edited_by'): block_data = self.module_data[BlockKey.from_usage_key(xblock.location)] if block_data.edit_info._subtree_edited_by is None: self._compute_subtree_edited_internal( block_data, xblock.location.course_key ) xblock._subtree_edited_by = block_data.edit_info._subtree_edited_by return xblock._subtree_edited_by @contract(xblock='XBlock') def get_subtree_edited_on(self, xblock): """ See :class: cms.lib.xblock.runtime.EditInfoRuntimeMixin """ # pylint: disable=protected-access if not hasattr(xblock, '_subtree_edited_on'): block_data = self.module_data[BlockKey.from_usage_key(xblock.location)] if block_data.edit_info._subtree_edited_on is None: self._compute_subtree_edited_internal( block_data, xblock.location.course_key ) xblock._subtree_edited_on = block_data.edit_info._subtree_edited_on return xblock._subtree_edited_on def get_published_by(self, xblock): """ See :class: cms.lib.xblock.runtime.EditInfoRuntimeMixin """ if not hasattr(xblock, '_published_by'): self.modulestore.compute_published_info_internal(xblock) return getattr(xblock, '_published_by', None) def get_published_on(self, xblock): """ See :class: cms.lib.xblock.runtime.EditInfoRuntimeMixin """ if not hasattr(xblock, '_published_on'): self.modulestore.compute_published_info_internal(xblock) return getattr(xblock, '_published_on', None) @contract(block_data='BlockData') def _compute_subtree_edited_internal(self, block_data, course_key): """ Recurse the subtree finding the max edited_on date and its corresponding edited_by. Cache it. """ # pylint: disable=protected-access max_date = block_data.edit_info.edited_on max_date_by = block_data.edit_info.edited_by for child in block_data.fields.get('children', []): child_data = self.get_module_data(BlockKey(*child), course_key) if block_data.edit_info._subtree_edited_on is None: self._compute_subtree_edited_internal(child_data, course_key) if child_data.edit_info._subtree_edited_on > max_date: max_date = child_data.edit_info._subtree_edited_on max_date_by = child_data.edit_info._subtree_edited_by block_data.edit_info._subtree_edited_on = max_date block_data.edit_info._subtree_edited_by = max_date_by def get_aside_of_type(self, block, aside_type): """ See `runtime.Runtime.get_aside_of_type` This override adds the field data from the block to the aside """ asides_cached = block.get_asides() if isinstance(block, XModuleMixin) else None if asides_cached: for aside in asides_cached: if aside.scope_ids.block_type == aside_type: return aside new_aside = super(CachingDescriptorSystem, self).get_aside_of_type(block, aside_type) new_aside._field_data = block._field_data # pylint: disable=protected-access for key, _ in new_aside.fields.iteritems(): if isinstance(key, KeyValueStore.Key) and block._field_data.has(new_aside, key): # pylint: disable=protected-access try: value = block._field_data.get(new_aside, key) # pylint: disable=protected-access except KeyError: pass else: setattr(new_aside, key, value) block.add_aside(new_aside) return new_aside
michaelBenin/sqlalchemy
refs/heads/master
lib/sqlalchemy/testing/schema.py
76
# testing/schema.py # Copyright (C) 2005-2014 the SQLAlchemy authors and contributors <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from . import exclusions from .. import schema, event from . import config __all__ = 'Table', 'Column', table_options = {} def Table(*args, **kw): """A schema.Table wrapper/hook for dialect-specific tweaks.""" test_opts = dict([(k, kw.pop(k)) for k in list(kw) if k.startswith('test_')]) kw.update(table_options) if exclusions.against(config._current, 'mysql'): if 'mysql_engine' not in kw and 'mysql_type' not in kw: if 'test_needs_fk' in test_opts or 'test_needs_acid' in test_opts: kw['mysql_engine'] = 'InnoDB' else: kw['mysql_engine'] = 'MyISAM' # Apply some default cascading rules for self-referential foreign keys. # MySQL InnoDB has some issues around seleting self-refs too. if exclusions.against(config._current, 'firebird'): table_name = args[0] unpack = (config.db.dialect. identifier_preparer.unformat_identifiers) # Only going after ForeignKeys in Columns. May need to # expand to ForeignKeyConstraint too. fks = [fk for col in args if isinstance(col, schema.Column) for fk in col.foreign_keys] for fk in fks: # root around in raw spec ref = fk._colspec if isinstance(ref, schema.Column): name = ref.table.name else: # take just the table name: on FB there cannot be # a schema, so the first element is always the # table name, possibly followed by the field name name = unpack(ref)[0] if name == table_name: if fk.ondelete is None: fk.ondelete = 'CASCADE' if fk.onupdate is None: fk.onupdate = 'CASCADE' return schema.Table(*args, **kw) def Column(*args, **kw): """A schema.Column wrapper/hook for dialect-specific tweaks.""" test_opts = dict([(k, kw.pop(k)) for k in list(kw) if k.startswith('test_')]) if config.requirements.foreign_key_ddl.predicate(config): args = [arg for arg in args if not isinstance(arg, schema.ForeignKey)] col = schema.Column(*args, **kw) if 'test_needs_autoincrement' in test_opts and \ kw.get('primary_key', False): # allow any test suite to pick up on this col.info['test_needs_autoincrement'] = True # hardcoded rule for firebird, oracle; this should # be moved out if exclusions.against(config._current, 'firebird', 'oracle'): def add_seq(c, tbl): c._init_items( schema.Sequence(_truncate_name( config.db.dialect, tbl.name + '_' + c.name + '_seq'), optional=True) ) event.listen(col, 'after_parent_attach', add_seq, propagate=True) return col def _truncate_name(dialect, name): if len(name) > dialect.max_identifier_length: return name[0:max(dialect.max_identifier_length - 6, 0)] + \ "_" + hex(hash(name) % 64)[2:] else: return name
adelina-t/compute-hyperv
refs/heads/master
hyperv/nova/hostutils.py
1
# Copyright 2013 Cloudbase Solutions Srl # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import ctypes import socket import sys if sys.platform == 'win32': import wmi from hyperv.i18n import _ from hyperv.nova import constants class HostUtils(object): _HOST_FORCED_REBOOT = 6 _HOST_FORCED_SHUTDOWN = 12 _DEFAULT_VM_GENERATION = constants.IMAGE_PROP_VM_GEN_1 FEATURE_RDS_VIRTUALIZATION = 322 def __init__(self): self._conn_cimv2 = None if sys.platform == 'win32': self._conn_cimv2 = wmi.WMI(privileges=["Shutdown"]) if self.check_min_windows_version(6, 2): self._conn_virt_v2 = wmi.WMI(moniker='//./root/' 'virtualization/v2') else: self._conn_virt_v2 = None def get_cpus_info(self): cpus = self._conn_cimv2.query("SELECT * FROM Win32_Processor " "WHERE ProcessorType = 3") cpus_list = [] for cpu in cpus: cpu_info = {'Architecture': cpu.Architecture, 'Name': cpu.Name, 'Manufacturer': cpu.Manufacturer, 'NumberOfCores': cpu.NumberOfCores, 'NumberOfLogicalProcessors': cpu.NumberOfLogicalProcessors} cpus_list.append(cpu_info) return cpus_list def is_cpu_feature_present(self, feature_key): return ctypes.windll.kernel32.IsProcessorFeaturePresent(feature_key) def get_memory_info(self): """Returns a tuple with total visible memory and free physical memory expressed in kB. """ mem_info = self._conn_cimv2.query("SELECT TotalVisibleMemorySize, " "FreePhysicalMemory " "FROM win32_operatingsystem")[0] return (long(mem_info.TotalVisibleMemorySize), long(mem_info.FreePhysicalMemory)) def get_volume_info(self, drive): """Returns a tuple with total size and free space expressed in bytes. """ logical_disk = self._conn_cimv2.query("SELECT Size, FreeSpace " "FROM win32_logicaldisk " "WHERE DeviceID='%s'" % drive)[0] return (long(logical_disk.Size), long(logical_disk.FreeSpace)) def check_min_windows_version(self, major, minor, build=0): version_str = self.get_windows_version() return map(int, version_str.split('.')) >= [major, minor, build] def get_windows_version(self): if self._conn_cimv2: return self._conn_cimv2.Win32_OperatingSystem()[0].Version def get_local_ips(self): addr_info = socket.getaddrinfo(socket.gethostname(), None, 0, 0, 0) # Returns IPv4 and IPv6 addresses, ordered by protocol family addr_info.sort() return [a[4][0] for a in addr_info] def get_host_tick_count64(self): return ctypes.windll.kernel32.GetTickCount64() def host_power_action(self, action): win32_os = self._conn_cimv2.Win32_OperatingSystem()[0] if action == constants.HOST_POWER_ACTION_SHUTDOWN: win32_os.Win32Shutdown(self._HOST_FORCED_SHUTDOWN) elif action == constants.HOST_POWER_ACTION_REBOOT: win32_os.Win32Shutdown(self._HOST_FORCED_REBOOT) else: raise NotImplementedError( _("Host %(action)s is not supported by the Hyper-V driver") % {"action": action}) def get_supported_vm_types(self): """Get the supported Hyper-V VM generations. Hyper-V Generation 2 VMs are supported in Windows 8.1, Windows Server / Hyper-V Server 2012 R2 or newer. :returns: array of supported VM generations (ex. ['hyperv-gen1']) """ if self.check_min_windows_version(6, 3): return [constants.IMAGE_PROP_VM_GEN_1, constants.IMAGE_PROP_VM_GEN_2] else: return [constants.IMAGE_PROP_VM_GEN_1] def get_default_vm_generation(self): return self._DEFAULT_VM_GENERATION def check_server_feature(self, feature_id): return len(self._conn_cimv2.Win32_ServerFeature(ID=feature_id)) > 0 def get_remotefx_gpu_info(self): gpus = [] if self._conn_virt_v2: all_gpus = self._conn_virt_v2.Msvm_Physical3dGraphicsProcessor( EnabledForVirtualization=True) for gpu in all_gpus: gpus.append({'name': gpu.Name, 'driver_version': gpu.DriverVersion, 'total_video_ram': gpu.TotalVideoMemory, 'available_video_ram': gpu.AvailableVideoMemory, 'directx_version': gpu.DirectXVersion}) return gpus
iivic/BoiseStateX
refs/heads/master
lms/djangoapps/instructor_task/tests/test_api.py
6
""" Test for LMS instructor background task queue management """ from mock import patch, Mock from bulk_email.models import CourseEmail, SEND_TO_ALL from courseware.tests.factories import UserFactory from xmodule.modulestore.exceptions import ItemNotFoundError from instructor_task.api import ( get_running_instructor_tasks, get_instructor_task_history, submit_rescore_problem_for_all_students, submit_rescore_problem_for_student, submit_reset_problem_attempts_for_all_students, submit_delete_problem_state_for_all_students, submit_bulk_course_email, submit_calculate_problem_responses_csv, submit_calculate_students_features_csv, submit_cohort_students, submit_detailed_enrollment_features_csv, submit_calculate_may_enroll_csv, submit_executive_summary_report, submit_course_survey_report, generate_certificates_for_all_students, ) from instructor_task.api_helper import AlreadyRunningError from instructor_task.models import InstructorTask, PROGRESS from instructor_task.tests.test_base import (InstructorTaskTestCase, InstructorTaskCourseTestCase, InstructorTaskModuleTestCase, TestReportMixin, TEST_COURSE_KEY) class InstructorTaskReportTest(InstructorTaskTestCase): """ Tests API methods that involve the reporting of status for background tasks. """ def test_get_running_instructor_tasks(self): # when fetching running tasks, we get all running tasks, and only running tasks for _ in range(1, 5): self._create_failure_entry() self._create_success_entry() progress_task_ids = [self._create_progress_entry().task_id for _ in range(1, 5)] task_ids = [instructor_task.task_id for instructor_task in get_running_instructor_tasks(TEST_COURSE_KEY)] self.assertEquals(set(task_ids), set(progress_task_ids)) def test_get_instructor_task_history(self): # when fetching historical tasks, we get all tasks, including running tasks expected_ids = [] for _ in range(1, 5): expected_ids.append(self._create_failure_entry().task_id) expected_ids.append(self._create_success_entry().task_id) expected_ids.append(self._create_progress_entry().task_id) task_ids = [instructor_task.task_id for instructor_task in get_instructor_task_history(TEST_COURSE_KEY, usage_key=self.problem_url)] self.assertEquals(set(task_ids), set(expected_ids)) # make the same call using explicit task_type: task_ids = [instructor_task.task_id for instructor_task in get_instructor_task_history( TEST_COURSE_KEY, usage_key=self.problem_url, task_type='rescore_problem' )] self.assertEquals(set(task_ids), set(expected_ids)) # make the same call using a non-existent task_type: task_ids = [instructor_task.task_id for instructor_task in get_instructor_task_history( TEST_COURSE_KEY, usage_key=self.problem_url, task_type='dummy_type' )] self.assertEquals(set(task_ids), set()) class InstructorTaskModuleSubmitTest(InstructorTaskModuleTestCase): """Tests API methods that involve the submission of module-based background tasks.""" def setUp(self): super(InstructorTaskModuleSubmitTest, self).setUp() self.initialize_course() self.student = UserFactory.create(username="student", email="student@edx.org") self.instructor = UserFactory.create(username="instructor", email="instructor@edx.org") def test_submit_nonexistent_modules(self): # confirm that a rescore of a non-existent module returns an exception problem_url = InstructorTaskModuleTestCase.problem_location("NonexistentProblem") request = None with self.assertRaises(ItemNotFoundError): submit_rescore_problem_for_student(request, problem_url, self.student) with self.assertRaises(ItemNotFoundError): submit_rescore_problem_for_all_students(request, problem_url) with self.assertRaises(ItemNotFoundError): submit_reset_problem_attempts_for_all_students(request, problem_url) with self.assertRaises(ItemNotFoundError): submit_delete_problem_state_for_all_students(request, problem_url) def test_submit_nonrescorable_modules(self): # confirm that a rescore of an existent but unscorable module returns an exception # (Note that it is easier to test a scoreable but non-rescorable module in test_tasks, # where we are creating real modules.) problem_url = self.problem_section.location request = None with self.assertRaises(NotImplementedError): submit_rescore_problem_for_student(request, problem_url, self.student) with self.assertRaises(NotImplementedError): submit_rescore_problem_for_all_students(request, problem_url) def _test_submit_with_long_url(self, task_function, student=None): problem_url_name = 'x' * 255 self.define_option_problem(problem_url_name) location = InstructorTaskModuleTestCase.problem_location(problem_url_name) with self.assertRaises(ValueError): if student is not None: task_function(self.create_task_request(self.instructor), location, student) else: task_function(self.create_task_request(self.instructor), location) def test_submit_rescore_all_with_long_url(self): self._test_submit_with_long_url(submit_rescore_problem_for_all_students) def test_submit_rescore_student_with_long_url(self): self._test_submit_with_long_url(submit_rescore_problem_for_student, self.student) def test_submit_reset_all_with_long_url(self): self._test_submit_with_long_url(submit_reset_problem_attempts_for_all_students) def test_submit_delete_all_with_long_url(self): self._test_submit_with_long_url(submit_delete_problem_state_for_all_students) def _test_submit_task(self, task_function, student=None): # tests submit, and then tests a second identical submission. problem_url_name = 'H1P1' self.define_option_problem(problem_url_name) location = InstructorTaskModuleTestCase.problem_location(problem_url_name) if student is not None: instructor_task = task_function(self.create_task_request(self.instructor), location, student) else: instructor_task = task_function(self.create_task_request(self.instructor), location) # test resubmitting, by updating the existing record: instructor_task = InstructorTask.objects.get(id=instructor_task.id) instructor_task.task_state = PROGRESS instructor_task.save() with self.assertRaises(AlreadyRunningError): if student is not None: task_function(self.create_task_request(self.instructor), location, student) else: task_function(self.create_task_request(self.instructor), location) def test_submit_rescore_all(self): self._test_submit_task(submit_rescore_problem_for_all_students) def test_submit_rescore_student(self): self._test_submit_task(submit_rescore_problem_for_student, self.student) def test_submit_reset_all(self): self._test_submit_task(submit_reset_problem_attempts_for_all_students) def test_submit_delete_all(self): self._test_submit_task(submit_delete_problem_state_for_all_students) @patch('bulk_email.models.html_to_text', Mock(return_value='Mocking CourseEmail.text_message')) class InstructorTaskCourseSubmitTest(TestReportMixin, InstructorTaskCourseTestCase): """Tests API methods that involve the submission of course-based background tasks.""" def setUp(self): super(InstructorTaskCourseSubmitTest, self).setUp() self.initialize_course() self.student = UserFactory.create(username="student", email="student@edx.org") self.instructor = UserFactory.create(username="instructor", email="instructor@edx.org") def _define_course_email(self): """Create CourseEmail object for testing.""" course_email = CourseEmail.create(self.course.id, self.instructor, SEND_TO_ALL, "Test Subject", "<p>This is a test message</p>") return course_email.id # pylint: disable=no-member def _test_resubmission(self, api_call): """ Tests the resubmission of an instructor task through the API. The call to the API is a lambda expression passed via `api_call`. Expects that the API call returns the resulting InstructorTask object, and that its resubmission raises `AlreadyRunningError`. """ instructor_task = api_call() instructor_task = InstructorTask.objects.get(id=instructor_task.id) instructor_task.task_state = PROGRESS instructor_task.save() with self.assertRaises(AlreadyRunningError): api_call() def test_submit_bulk_email_all(self): email_id = self._define_course_email() api_call = lambda: submit_bulk_course_email( self.create_task_request(self.instructor), self.course.id, email_id ) self._test_resubmission(api_call) def test_submit_calculate_problem_responses(self): api_call = lambda: submit_calculate_problem_responses_csv( self.create_task_request(self.instructor), self.course.id, problem_location='' ) self._test_resubmission(api_call) def test_submit_calculate_students_features(self): api_call = lambda: submit_calculate_students_features_csv( self.create_task_request(self.instructor), self.course.id, features=[] ) self._test_resubmission(api_call) def test_submit_enrollment_report_features_csv(self): api_call = lambda: submit_detailed_enrollment_features_csv(self.create_task_request(self.instructor), self.course.id) self._test_resubmission(api_call) def test_submit_executive_summary_report(self): api_call = lambda: submit_executive_summary_report( self.create_task_request(self.instructor), self.course.id ) self._test_resubmission(api_call) def test_submit_course_survey_report(self): api_call = lambda: submit_course_survey_report( self.create_task_request(self.instructor), self.course.id ) self._test_resubmission(api_call) def test_submit_calculate_may_enroll(self): api_call = lambda: submit_calculate_may_enroll_csv( self.create_task_request(self.instructor), self.course.id, features=[] ) self._test_resubmission(api_call) def test_submit_cohort_students(self): api_call = lambda: submit_cohort_students( self.create_task_request(self.instructor), self.course.id, file_name=u'filename.csv' ) self._test_resubmission(api_call) def test_submit_generate_certs_students(self): """ Tests certificates generation task submission api """ api_call = lambda: generate_certificates_for_all_students( self.create_task_request(self.instructor), self.course.id ) self._test_resubmission(api_call)
laurent-george/weboob
refs/heads/master
modules/feedly/google.py
1
# -*- coding: utf-8 -*- # Copyright(C) 2014 Bezleputh # # This file is part of weboob. # # weboob 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. # # weboob 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 weboob. If not, see <http://www.gnu.org/licenses/>. from urlparse import urlparse, parse_qs from weboob.browser import LoginBrowser, URL from weboob.browser.pages import HTMLPage, LoggedPage from weboob.exceptions import BrowserIncorrectPassword class GoogleLoginPage(LoggedPage, HTMLPage): def login(self, login, passwd): form = self.get_form('//form[@id="gaia_loginform"]') form['Email'] = login form['Passwd'] = passwd form.submit() class GoogleBrowser(LoginBrowser): BASEURL = 'https://accounts.google.com' code = None google_login = URL('https://accounts.google.com/(?P<auth>.+)', GoogleLoginPage) def __init__(self, username, password, redirect_uri, *args, **kwargs): super(GoogleBrowser, self).__init__(username, password, *args, **kwargs) self.redirect_uri = redirect_uri def do_login(self): params = {'response_type': 'code', 'client_id': '534890559860-r6gn7e3agcpiriehe63dkeus0tpl5i4i.apps.googleusercontent.com', 'redirect_uri': self.redirect_uri} queryString = "&".join([key+'='+value for key, value in params.items()]) self.google_login.go(auth='o/oauth2/auth', params=queryString).login(self.username, self.password) try: self.code = parse_qs(urlparse(self.url).query).get('code')[0] except: raise BrowserIncorrectPassword()
badp/ganeti
refs/heads/master
lib/http/server.py
2
# # # Copyright (C) 2007, 2008, 2010, 2012 Google Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. """HTTP server module. """ import BaseHTTPServer import cgi import logging import os import socket import time import signal import asyncore from ganeti import http from ganeti import utils from ganeti import netutils from ganeti import compat from ganeti import errors WEEKDAYNAME = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] MONTHNAME = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] # Default error message DEFAULT_ERROR_CONTENT_TYPE = "text/html" DEFAULT_ERROR_MESSAGE = """\ <html> <head> <title>Error response</title> </head> <body> <h1>Error response</h1> <p>Error code %(code)d. <p>Message: %(message)s. <p>Error code explanation: %(code)s = %(explain)s. </body> </html> """ def _DateTimeHeader(gmnow=None): """Return the current date and time formatted for a message header. The time MUST be in the GMT timezone. """ if gmnow is None: gmnow = time.gmtime() (year, month, day, hh, mm, ss, wd, _, _) = gmnow return ("%s, %02d %3s %4d %02d:%02d:%02d GMT" % (WEEKDAYNAME[wd], day, MONTHNAME[month], year, hh, mm, ss)) class _HttpServerRequest(object): """Data structure for HTTP request on server side. """ def __init__(self, method, path, headers, body): # Request attributes self.request_method = method self.request_path = path self.request_headers = headers self.request_body = body # Response attributes self.resp_headers = {} # Private data for request handler (useful in combination with # authentication) self.private = None def __repr__(self): status = ["%s.%s" % (self.__class__.__module__, self.__class__.__name__), self.request_method, self.request_path, "headers=%r" % str(self.request_headers), "body=%r" % (self.request_body, )] return "<%s at %#x>" % (" ".join(status), id(self)) class _HttpServerToClientMessageWriter(http.HttpMessageWriter): """Writes an HTTP response to client. """ def __init__(self, sock, request_msg, response_msg, write_timeout): """Writes the response to the client. @type sock: socket @param sock: Target socket @type request_msg: http.HttpMessage @param request_msg: Request message, required to determine whether response may have a message body @type response_msg: http.HttpMessage @param response_msg: Response message @type write_timeout: float @param write_timeout: Write timeout for socket """ self._request_msg = request_msg self._response_msg = response_msg http.HttpMessageWriter.__init__(self, sock, response_msg, write_timeout) def HasMessageBody(self): """Logic to detect whether response should contain a message body. """ if self._request_msg.start_line: request_method = self._request_msg.start_line.method else: request_method = None response_code = self._response_msg.start_line.code # RFC2616, section 4.3: "A message-body MUST NOT be included in a request # if the specification of the request method (section 5.1.1) does not allow # sending an entity-body in requests" # # RFC2616, section 9.4: "The HEAD method is identical to GET except that # the server MUST NOT return a message-body in the response." # # RFC2616, section 10.2.5: "The 204 response MUST NOT include a # message-body [...]" # # RFC2616, section 10.3.5: "The 304 response MUST NOT contain a # message-body, [...]" return (http.HttpMessageWriter.HasMessageBody(self) and (request_method is not None and request_method != http.HTTP_HEAD) and response_code >= http.HTTP_OK and response_code not in (http.HTTP_NO_CONTENT, http.HTTP_NOT_MODIFIED)) class _HttpClientToServerMessageReader(http.HttpMessageReader): """Reads an HTTP request sent by client. """ # Length limits START_LINE_LENGTH_MAX = 8192 HEADER_LENGTH_MAX = 4096 def ParseStartLine(self, start_line): """Parses the start line sent by client. Example: "GET /index.html HTTP/1.1" @type start_line: string @param start_line: Start line """ # Empty lines are skipped when reading assert start_line logging.debug("HTTP request: %s", start_line) words = start_line.split() if len(words) == 3: [method, path, version] = words if version[:5] != "HTTP/": raise http.HttpBadRequest("Bad request version (%r)" % version) try: base_version_number = version.split("/", 1)[1] version_number = base_version_number.split(".") # RFC 2145 section 3.1 says there can be only one "." and # - major and minor numbers MUST be treated as # separate integers; # - HTTP/2.4 is a lower version than HTTP/2.13, which in # turn is lower than HTTP/12.3; # - Leading zeros MUST be ignored by recipients. if len(version_number) != 2: raise http.HttpBadRequest("Bad request version (%r)" % version) version_number = (int(version_number[0]), int(version_number[1])) except (ValueError, IndexError): raise http.HttpBadRequest("Bad request version (%r)" % version) if version_number >= (2, 0): raise http.HttpVersionNotSupported("Invalid HTTP Version (%s)" % base_version_number) elif len(words) == 2: version = http.HTTP_0_9 [method, path] = words if method != http.HTTP_GET: raise http.HttpBadRequest("Bad HTTP/0.9 request type (%r)" % method) else: raise http.HttpBadRequest("Bad request syntax (%r)" % start_line) return http.HttpClientToServerStartLine(method, path, version) def _HandleServerRequestInner(handler, req_msg): """Calls the handler function for the current request. """ handler_context = _HttpServerRequest(req_msg.start_line.method, req_msg.start_line.path, req_msg.headers, req_msg.body) logging.debug("Handling request %r", handler_context) try: try: # Authentication, etc. handler.PreHandleRequest(handler_context) # Call actual request handler result = handler.HandleRequest(handler_context) except (http.HttpException, errors.RapiTestResult, KeyboardInterrupt, SystemExit): raise except Exception, err: logging.exception("Caught exception") raise http.HttpInternalServerError(message=str(err)) except: logging.exception("Unknown exception") raise http.HttpInternalServerError(message="Unknown error") if not isinstance(result, basestring): raise http.HttpError("Handler function didn't return string type") return (http.HTTP_OK, handler_context.resp_headers, result) finally: # No reason to keep this any longer, even for exceptions handler_context.private = None class HttpResponder(object): # The default request version. This only affects responses up until # the point where the request line is parsed, so it mainly decides what # the client gets back when sending a malformed request line. # Most web servers default to HTTP 0.9, i.e. don't send a status line. default_request_version = http.HTTP_0_9 responses = BaseHTTPServer.BaseHTTPRequestHandler.responses def __init__(self, handler): """Initializes this class. """ self._handler = handler def __call__(self, fn): """Handles a request. @type fn: callable @param fn: Callback for retrieving HTTP request, must return a tuple containing request message (L{http.HttpMessage}) and C{None} or the message reader (L{_HttpClientToServerMessageReader}) """ response_msg = http.HttpMessage() response_msg.start_line = \ http.HttpServerToClientStartLine(version=self.default_request_version, code=None, reason=None) force_close = True try: (request_msg, req_msg_reader) = fn() response_msg.start_line.version = request_msg.start_line.version # RFC2616, 14.23: All Internet-based HTTP/1.1 servers MUST respond # with a 400 (Bad Request) status code to any HTTP/1.1 request # message which lacks a Host header field. if (request_msg.start_line.version == http.HTTP_1_1 and not (request_msg.headers and http.HTTP_HOST in request_msg.headers)): raise http.HttpBadRequest(message="Missing Host header") (response_msg.start_line.code, response_msg.headers, response_msg.body) = \ _HandleServerRequestInner(self._handler, request_msg) except http.HttpException, err: self._SetError(self.responses, self._handler, response_msg, err) else: # Only wait for client to close if we didn't have any exception. force_close = False return (request_msg, req_msg_reader, force_close, self._Finalize(self.responses, response_msg)) @staticmethod def _SetError(responses, handler, response_msg, err): """Sets the response code and body from a HttpException. @type err: HttpException @param err: Exception instance """ try: (shortmsg, longmsg) = responses[err.code] except KeyError: shortmsg = longmsg = "Unknown" if err.message: message = err.message else: message = shortmsg values = { "code": err.code, "message": cgi.escape(message), "explain": longmsg, } (content_type, body) = handler.FormatErrorMessage(values) headers = { http.HTTP_CONTENT_TYPE: content_type, } if err.headers: headers.update(err.headers) response_msg.start_line.code = err.code response_msg.headers = headers response_msg.body = body @staticmethod def _Finalize(responses, msg): assert msg.start_line.reason is None if not msg.headers: msg.headers = {} msg.headers.update({ # TODO: Keep-alive is not supported http.HTTP_CONNECTION: "close", http.HTTP_DATE: _DateTimeHeader(), http.HTTP_SERVER: http.HTTP_GANETI_VERSION, }) # Get response reason based on code try: code_desc = responses[msg.start_line.code] except KeyError: reason = "" else: (reason, _) = code_desc msg.start_line.reason = reason return msg class HttpServerRequestExecutor(object): """Implements server side of HTTP. This class implements the server side of HTTP. It's based on code of Python's BaseHTTPServer, from both version 2.4 and 3k. It does not support non-ASCII character encodings. Keep-alive connections are not supported. """ # Timeouts in seconds for socket layer WRITE_TIMEOUT = 10 READ_TIMEOUT = 10 CLOSE_TIMEOUT = 1 def __init__(self, server, handler, sock, client_addr): """Initializes this class. """ responder = HttpResponder(handler) # Disable Python's timeout sock.settimeout(None) # Operate in non-blocking mode sock.setblocking(0) request_msg_reader = None force_close = True logging.debug("Connection from %s:%s", client_addr[0], client_addr[1]) try: # Block for closing connection try: # Do the secret SSL handshake if server.using_ssl: sock.set_accept_state() try: http.Handshake(sock, self.WRITE_TIMEOUT) except http.HttpSessionHandshakeUnexpectedEOF: # Ignore rest return (request_msg, request_msg_reader, force_close, response_msg) = \ responder(compat.partial(self._ReadRequest, sock, self.READ_TIMEOUT)) if response_msg: # HttpMessage.start_line can be of different types # Instance of 'HttpClientToServerStartLine' has no 'code' member # pylint: disable=E1103,E1101 logging.info("%s:%s %s %s", client_addr[0], client_addr[1], request_msg.start_line, response_msg.start_line.code) self._SendResponse(sock, request_msg, response_msg, self.WRITE_TIMEOUT) finally: http.ShutdownConnection(sock, self.CLOSE_TIMEOUT, self.WRITE_TIMEOUT, request_msg_reader, force_close) sock.close() finally: logging.debug("Disconnected %s:%s", client_addr[0], client_addr[1]) @staticmethod def _ReadRequest(sock, timeout): """Reads a request sent by client. """ msg = http.HttpMessage() try: reader = _HttpClientToServerMessageReader(sock, msg, timeout) except http.HttpSocketTimeout: raise http.HttpError("Timeout while reading request") except socket.error, err: raise http.HttpError("Error reading request: %s" % err) return (msg, reader) @staticmethod def _SendResponse(sock, req_msg, msg, timeout): """Sends the response to the client. """ try: _HttpServerToClientMessageWriter(sock, req_msg, msg, timeout) except http.HttpSocketTimeout: raise http.HttpError("Timeout while sending response") except socket.error, err: raise http.HttpError("Error sending response: %s" % err) class HttpServer(http.HttpBase, asyncore.dispatcher): """Generic HTTP server class """ MAX_CHILDREN = 20 def __init__(self, mainloop, local_address, port, handler, ssl_params=None, ssl_verify_peer=False, request_executor_class=None, ssl_verify_callback=None): """Initializes the HTTP server @type mainloop: ganeti.daemon.Mainloop @param mainloop: Mainloop used to poll for I/O events @type local_address: string @param local_address: Local IP address to bind to @type port: int @param port: TCP port to listen on @type ssl_params: HttpSslParams @param ssl_params: SSL key and certificate @type ssl_verify_peer: bool @param ssl_verify_peer: Whether to require client certificate and compare it with our certificate @type request_executor_class: class @param request_executor_class: an class derived from the HttpServerRequestExecutor class """ http.HttpBase.__init__(self) asyncore.dispatcher.__init__(self) if request_executor_class is None: self.request_executor = HttpServerRequestExecutor else: self.request_executor = request_executor_class self.mainloop = mainloop self.local_address = local_address self.port = port self.handler = handler family = netutils.IPAddress.GetAddressFamily(local_address) self.socket = self._CreateSocket(ssl_params, ssl_verify_peer, family, ssl_verify_callback) # Allow port to be reused self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self._children = [] self.set_socket(self.socket) self.accepting = True mainloop.RegisterSignal(self) def Start(self): self.socket.bind((self.local_address, self.port)) self.socket.listen(1024) def Stop(self): self.socket.close() def handle_accept(self): self._IncomingConnection() def OnSignal(self, signum): if signum == signal.SIGCHLD: self._CollectChildren(True) def _CollectChildren(self, quick): """Checks whether any child processes are done @type quick: bool @param quick: Whether to only use non-blocking functions """ if not quick: # Don't wait for other processes if it should be a quick check while len(self._children) > self.MAX_CHILDREN: try: # Waiting without a timeout brings us into a potential DoS situation. # As soon as too many children run, we'll not respond to new # requests. The real solution would be to add a timeout for children # and killing them after some time. pid, _ = os.waitpid(0, 0) except os.error: pid = None if pid and pid in self._children: self._children.remove(pid) for child in self._children: try: pid, _ = os.waitpid(child, os.WNOHANG) except os.error: pid = None if pid and pid in self._children: self._children.remove(pid) def _IncomingConnection(self): """Called for each incoming connection """ # pylint: disable=W0212 (connection, client_addr) = self.socket.accept() self._CollectChildren(False) pid = os.fork() if pid == 0: # Child process try: # The client shouldn't keep the listening socket open. If the parent # process is restarted, it would fail when there's already something # listening (in this case its own child from a previous run) on the # same port. try: self.socket.close() except socket.error: pass self.socket = None # In case the handler code uses temporary files utils.ResetTempfileModule() self.request_executor(self, self.handler, connection, client_addr) except Exception: # pylint: disable=W0703 logging.exception("Error while handling request from %s:%s", client_addr[0], client_addr[1]) os._exit(1) os._exit(0) else: self._children.append(pid) class HttpServerHandler(object): """Base class for handling HTTP server requests. Users of this class must subclass it and override the L{HandleRequest} function. """ def PreHandleRequest(self, req): """Called before handling a request. Can be overridden by a subclass. """ def HandleRequest(self, req): """Handles a request. Must be overridden by subclass. """ raise NotImplementedError() @staticmethod def FormatErrorMessage(values): """Formats the body of an error message. @type values: dict @param values: dictionary with keys C{code}, C{message} and C{explain}. @rtype: tuple; (string, string) @return: Content-type and response body """ return (DEFAULT_ERROR_CONTENT_TYPE, DEFAULT_ERROR_MESSAGE % values)
jeeftor/alfredToday
refs/heads/master
src/lib/pyasn1/type/useful.py
172
# ASN.1 "useful" types from pyasn1.type import char, tag class ObjectDescriptor(char.GraphicString): tagSet = char.GraphicString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 7) ) class GeneralizedTime(char.VisibleString): tagSet = char.VisibleString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 24) ) class UTCTime(char.VisibleString): tagSet = char.VisibleString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 23) )
dorotan/pythontraining
refs/heads/master
env/Lib/encodings/iso2022_jp_3.py
816
# # iso2022_jp_3.py: Python Unicode Codec for ISO2022_JP_3 # # Written by Hye-Shik Chang <perky@FreeBSD.org> # import _codecs_iso2022, codecs import _multibytecodec as mbc codec = _codecs_iso2022.getcodec('iso2022_jp_3') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): codec = codec class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): codec = codec class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): codec = codec class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): codec = codec def getregentry(): return codecs.CodecInfo( name='iso2022_jp_3', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, )
terryoy/django-skeleton
refs/heads/master
app/app/local_settings.py
1
from .settings import * # change to the place where you put your static files (e.g. where "/srv/www/django-skeleton/" is web root) STATIC_ROOT = "/srv/www/django-skeleton/static" # an upload folder where you upload files to (can use symbolic link to set under app folder) MEDIA_ROOT = os.path.join(BASE_DIR, "upload")
mkacik/bcc
refs/heads/master
tools/ext4dist.py
2
#!/usr/bin/python # @lint-avoid-python-3-compatibility-imports # # ext4dist Summarize ext4 operation latency. # For Linux, uses BCC, eBPF. # # USAGE: ext4dist [-h] [-T] [-m] [-p PID] [interval] [count] # # Copyright 2016 Netflix, Inc. # Licensed under the Apache License, Version 2.0 (the "License") # # 12-Feb-2016 Brendan Gregg Created this. from __future__ import print_function from bcc import BPF from time import sleep, strftime import argparse # symbols kallsyms = "/proc/kallsyms" # arguments examples = """examples: ./ext4dist # show operation latency as a histogram ./ext4dist -p 181 # trace PID 181 only ./ext4dist 1 10 # print 1 second summaries, 10 times ./ext4dist -m 5 # 5s summaries, milliseconds """ parser = argparse.ArgumentParser( description="Summarize ext4 operation latency", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=examples) parser.add_argument("-T", "--notimestamp", action="store_true", help="don't include timestamp on interval output") parser.add_argument("-m", "--milliseconds", action="store_true", help="output in milliseconds") parser.add_argument("-p", "--pid", help="trace this PID only") parser.add_argument("interval", nargs="?", help="output interval, in seconds") parser.add_argument("count", nargs="?", default=99999999, help="number of outputs") args = parser.parse_args() pid = args.pid countdown = int(args.count) if args.milliseconds: factor = 1000000 label = "msecs" else: factor = 1000 label = "usecs" if args.interval and int(args.interval) == 0: print("ERROR: interval 0. Exiting.") exit() debug = 0 # define BPF program bpf_text = """ #include <uapi/linux/ptrace.h> #include <linux/fs.h> #include <linux/sched.h> #define OP_NAME_LEN 8 typedef struct dist_key { char op[OP_NAME_LEN]; u64 slot; } dist_key_t; BPF_HASH(start, u32); BPF_HISTOGRAM(dist, dist_key_t); // time operation int trace_entry(struct pt_regs *ctx) { u32 pid = bpf_get_current_pid_tgid(); if (FILTER_PID) return 0; u64 ts = bpf_ktime_get_ns(); start.update(&pid, &ts); return 0; } // The current ext4 (Linux 4.5) uses generic_file_read_iter(), instead of it's // own function, for reads. So we need to trace that and then filter on ext4, // which I do by checking file->f_op. int trace_read_entry(struct pt_regs *ctx, struct kiocb *iocb) { u32 pid = bpf_get_current_pid_tgid(); if (FILTER_PID) return 0; // ext4 filter on file->f_op == ext4_file_operations struct file *fp = iocb->ki_filp; if ((u64)fp->f_op != EXT4_FILE_OPERATIONS) return 0; u64 ts = bpf_ktime_get_ns(); start.update(&pid, &ts); return 0; } static int trace_return(struct pt_regs *ctx, const char *op) { u64 *tsp; u32 pid = bpf_get_current_pid_tgid(); // fetch timestamp and calculate delta tsp = start.lookup(&pid); if (tsp == 0) { return 0; // missed start or filtered } u64 delta = (bpf_ktime_get_ns() - *tsp) / FACTOR; // store as histogram dist_key_t key = {.slot = bpf_log2l(delta)}; __builtin_memcpy(&key.op, op, sizeof(key.op)); dist.increment(key); start.delete(&pid); return 0; } int trace_read_return(struct pt_regs *ctx) { char *op = "read"; return trace_return(ctx, op); } int trace_write_return(struct pt_regs *ctx) { char *op = "write"; return trace_return(ctx, op); } int trace_open_return(struct pt_regs *ctx) { char *op = "open"; return trace_return(ctx, op); } int trace_fsync_return(struct pt_regs *ctx) { char *op = "fsync"; return trace_return(ctx, op); } """ # code replacements with open(kallsyms) as syms: ops = '' for line in syms: (addr, size, name) = line.rstrip().split(" ", 2) name = name.split("\t")[0] if name == "ext4_file_operations": ops = "0x" + addr break if ops == '': print("ERROR: no ext4_file_operations in /proc/kallsyms. Exiting.") exit() bpf_text = bpf_text.replace('EXT4_FILE_OPERATIONS', ops) bpf_text = bpf_text.replace('FACTOR', str(factor)) if args.pid: bpf_text = bpf_text.replace('FILTER_PID', 'pid != %s' % pid) else: bpf_text = bpf_text.replace('FILTER_PID', '0') if debug: print(bpf_text) # load BPF program b = BPF(text=bpf_text) # Common file functions. See earlier comment about generic_file_read_iter(). b.attach_kprobe(event="generic_file_read_iter", fn_name="trace_read_entry") b.attach_kprobe(event="ext4_file_write_iter", fn_name="trace_entry") b.attach_kprobe(event="ext4_file_open", fn_name="trace_entry") b.attach_kprobe(event="ext4_sync_file", fn_name="trace_entry") b.attach_kretprobe(event="generic_file_read_iter", fn_name="trace_read_return") b.attach_kretprobe(event="ext4_file_write_iter", fn_name="trace_write_return") b.attach_kretprobe(event="ext4_file_open", fn_name="trace_open_return") b.attach_kretprobe(event="ext4_sync_file", fn_name="trace_fsync_return") print("Tracing ext4 operation latency... Hit Ctrl-C to end.") # output exiting = 0 dist = b.get_table("dist") while (1): try: if args.interval: sleep(int(args.interval)) else: sleep(99999999) except KeyboardInterrupt: exiting = 1 print() if args.interval and (not args.notimestamp): print(strftime("%H:%M:%S:")) dist.print_log2_hist(label, "operation") dist.clear() countdown -= 1 if exiting or countdown == 0: exit()
cainiaocome/scikit-learn
refs/heads/master
examples/ensemble/plot_ensemble_oob.py
259
""" ============================= OOB Errors for Random Forests ============================= The ``RandomForestClassifier`` is trained using *bootstrap aggregation*, where each new tree is fit from a bootstrap sample of the training observations :math:`z_i = (x_i, y_i)`. The *out-of-bag* (OOB) error is the average error for each :math:`z_i` calculated using predictions from the trees that do not contain :math:`z_i` in their respective bootstrap sample. This allows the ``RandomForestClassifier`` to be fit and validated whilst being trained [1]. The example below demonstrates how the OOB error can be measured at the addition of each new tree during training. The resulting plot allows a practitioner to approximate a suitable value of ``n_estimators`` at which the error stabilizes. .. [1] T. Hastie, R. Tibshirani and J. Friedman, "Elements of Statistical Learning Ed. 2", p592-593, Springer, 2009. """ import matplotlib.pyplot as plt from collections import OrderedDict from sklearn.datasets import make_classification from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier # Author: Kian Ho <hui.kian.ho@gmail.com> # Gilles Louppe <g.louppe@gmail.com> # Andreas Mueller <amueller@ais.uni-bonn.de> # # License: BSD 3 Clause print(__doc__) RANDOM_STATE = 123 # Generate a binary classification dataset. X, y = make_classification(n_samples=500, n_features=25, n_clusters_per_class=1, n_informative=15, random_state=RANDOM_STATE) # NOTE: Setting the `warm_start` construction parameter to `True` disables # support for paralellised ensembles but is necessary for tracking the OOB # error trajectory during training. ensemble_clfs = [ ("RandomForestClassifier, max_features='sqrt'", RandomForestClassifier(warm_start=True, oob_score=True, max_features="sqrt", random_state=RANDOM_STATE)), ("RandomForestClassifier, max_features='log2'", RandomForestClassifier(warm_start=True, max_features='log2', oob_score=True, random_state=RANDOM_STATE)), ("RandomForestClassifier, max_features=None", RandomForestClassifier(warm_start=True, max_features=None, oob_score=True, random_state=RANDOM_STATE)) ] # Map a classifier name to a list of (<n_estimators>, <error rate>) pairs. error_rate = OrderedDict((label, []) for label, _ in ensemble_clfs) # Range of `n_estimators` values to explore. min_estimators = 15 max_estimators = 175 for label, clf in ensemble_clfs: for i in range(min_estimators, max_estimators + 1): clf.set_params(n_estimators=i) clf.fit(X, y) # Record the OOB error for each `n_estimators=i` setting. oob_error = 1 - clf.oob_score_ error_rate[label].append((i, oob_error)) # Generate the "OOB error rate" vs. "n_estimators" plot. for label, clf_err in error_rate.items(): xs, ys = zip(*clf_err) plt.plot(xs, ys, label=label) plt.xlim(min_estimators, max_estimators) plt.xlabel("n_estimators") plt.ylabel("OOB error rate") plt.legend(loc="upper right") plt.show()
bjesus/wagtail
refs/heads/master
wagtail/wagtailcore/management/commands/move_pages.py
26
from django.core.management.base import BaseCommand from wagtail.wagtailcore.models import Page class Command(BaseCommand): args = "<from id> <to id>" def handle(self, _from_id, _to_id, **options): # Convert args to integers from_id = int(_from_id) to_id = int(_to_id) # Get pages from_page = Page.objects.get(pk=from_id) to_page = Page.objects.get(pk=to_id) pages = from_page.get_children() # Move the pages self.stdout.write('Moving ' + str(len(pages)) + ' pages from "' + from_page.title + '" to "' + to_page.title + '"') for page in pages: page.move(to_page, pos='last-child') self.stdout.write('Done')
ludia/moto
refs/heads/master
tests/test_cloudformation/fixtures/route53_roundrobin.py
21
from __future__ import unicode_literals template = { "AWSTemplateFormatVersion" : "2010-09-09", "Description" : "AWS CloudFormation Sample Template Route53_RoundRobin: Sample template showing how to use weighted round robin (WRR) DNS entried via Amazon Route 53. This contrived sample uses weighted CNAME records to illustrate that the weighting influences the return records. It assumes that you already have a Hosted Zone registered with Amazon Route 53. **WARNING** This template creates one or more AWS resources. You will be billed for the AWS resources used if you create a stack from this template.", "Resources" : { "MyZone": { "Type" : "AWS::Route53::HostedZone", "Properties" : { "Name" : "my_zone" } }, "MyDNSRecord" : { "Type" : "AWS::Route53::RecordSetGroup", "Properties" : { "HostedZoneName" : {"Ref": "MyZone"}, "Comment" : "Contrived example to redirect to aws.amazon.com 75% of the time and www.amazon.com 25% of the time.", "RecordSets" : [{ "SetIdentifier" : { "Fn::Join" : [ " ", [{"Ref" : "AWS::StackName"}, "AWS" ]]}, "Name" : { "Fn::Join" : [ "", [{"Ref" : "AWS::StackName"}, ".", {"Ref" : "AWS::Region"}, ".", {"Ref" : "MyZone"}, "."]]}, "Type" : "CNAME", "TTL" : "900", "ResourceRecords" : ["aws.amazon.com"], "Weight" : "3" },{ "SetIdentifier" : { "Fn::Join" : [ " ", [{"Ref" : "AWS::StackName"}, "Amazon" ]]}, "Name" : { "Fn::Join" : [ "", [{"Ref" : "AWS::StackName"}, ".", {"Ref" : "AWS::Region"}, ".", {"Ref" : "MyZone"}, "."]]}, "Type" : "CNAME", "TTL" : "900", "ResourceRecords" : ["www.amazon.com"], "Weight" : "1" }] } } }, "Outputs" : { "DomainName" : { "Description" : "Fully qualified domain name", "Value" : { "Ref" : "MyDNSRecord" } } } }
mlcommons/inference
refs/heads/master
compliance/audit_v0.5/nvidia/TEST03/modify_image_data.py
1
#! /usr/bin/env python3 import os import sys sys.path.append(os.getcwd()) import argparse import numpy as np import shutil #from common import logging #from PIL import Image import cv2 import math def modify_imagenet(data_dir, custom_data_dir): #logging.info("Modifying imagenet...") print("Moidfying imagenet") dirlist = os.listdir(data_dir) image_list = [x for x in dirlist if x.endswith(".JPEG")] src_dir = data_dir dst_dir = os.path.join(custom_data_dir, "imagenet") if not os.path.exists(dst_dir): os.makedirs(dst_dir) for idx, file_name in enumerate(image_list): if (idx % 1000) == 0: print("Processing image No.{:d}/{:d}...".format(idx, len(image_list))) img_out = os.path.join(dst_dir, file_name) if not os.path.exists(img_out): image = cv2.imread(os.path.join(src_dir, file_name)) #Set pixels to 0 image[:,:,0] = 0 #print ("Writing image No.{:d}/{:d}...".format(idx, len(image_list))) cv2.imwrite(img_out, image) def modify_coco(data_dir, custom_data_dir): #logging.info("Preprocessing coco...") def modify_coco_helper(src_dir, dst_dir, image_list): if not os.path.exists(dst_dir): os.makedirs(dst_dir) for idx, file_name in enumerate(image_list): #logging.info("Processing image No.{:d}/{:d}...".format(idx, len(image_list))) img_out = os.path.join(dst_dir, file_name) if not os.path.exists(img_out): image_path = os.path.join(src_dir, file_name) image = cv2.imread(image_path) #Set pixels to 0 image[:,:,0] = 0 cv2.imwrite(img_out, image) #Modify the validation set src_dir = os.path.join(data_dir, "val2017") dst_dir = os.path.join(custom_data_dir, "coco/val2017/") dirlist = os.listdir(src_dir) image_list = [x for x in dirlist if x.endswith(".jpg")] modify_coco_helper(src_dir, dst_dir, image_list) #Copy the training set src_dir = os.path.join(data_dir, "train2017") dst_dir = os.path.join(custom_data_dir, "coco/train2017") shutil.copytree(src_dir, dst_dir) def copy_coco_annotations(data_dir, output_dir): src_dir = os.path.join(data_dir, "annotations") dst_dir = os.path.join(output_dir, "coco/annotations") shutil.copytree(src_dir, dst_dir) def main(): # Parse arguments to identify the data directory with the input images # and the output directory for the new custom images parser = argparse.ArgumentParser() parser.add_argument( "--data_dir", "-d", help="Specifies the directory containing the input images.", default="" ) parser.add_argument( "--output_dir", "-o", help="Specifies the output directory for the custom data.", default="" ) parser.add_argument( "--dataset", help="Specifies the dataset - coco or imagenet", default="" ) args = parser.parse_args() print ("Running dataset modifer....") # Now, actually modify the input images #logging.info("Loading and modifying images. This might take a while...") data_dir = args.data_dir output_dir = args.output_dir #while True: #print ("a") #pass if args.dataset == "imagenet": print("Begin Imagenet") modify_imagenet(data_dir, output_dir) print("Imagenet complete") elif args.dataset == "coco": modify_coco(data_dir, output_dir) copy_coco_annotations(data_dir, output_dir) else: print("Incorrect dataset") #logging.info("Incorrect dataset. It can be either coco or imagenet.") #logging.info("Processing done.") if __name__ == '__main__': main()
Azure/azure-sdk-for-python
refs/heads/sync-eng/common-js-nightly-docs-2-1768-ForTestPipeline
sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_02_01/aio/operations/_network_profiles_operations.py
1
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class NetworkProfilesOperations: """NetworkProfilesOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.network.v2019_02_01.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config async def _delete_initial( self, resource_group_name: str, network_profile_name: str, **kwargs ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-02-01" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'networkProfileName': self._serialize.url("network_profile_name", network_profile_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles/{networkProfileName}'} # type: ignore async def begin_delete( self, resource_group_name: str, network_profile_name: str, **kwargs ) -> AsyncLROPoller[None]: """Deletes the specified network profile. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param network_profile_name: The name of the NetworkProfile. :type network_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, network_profile_name=network_profile_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'networkProfileName': self._serialize.url("network_profile_name", network_profile_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles/{networkProfileName}'} # type: ignore async def get( self, resource_group_name: str, network_profile_name: str, expand: Optional[str] = None, **kwargs ) -> "_models.NetworkProfile": """Gets the specified network profile in a specified resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param network_profile_name: The name of the public IP prefix. :type network_profile_name: str :param expand: Expands referenced resources. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: NetworkProfile, or the result of cls(response) :rtype: ~azure.mgmt.network.v2019_02_01.models.NetworkProfile :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.NetworkProfile"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-02-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'networkProfileName': self._serialize.url("network_profile_name", network_profile_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') if expand is not None: query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('NetworkProfile', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles/{networkProfileName}'} # type: ignore async def create_or_update( self, resource_group_name: str, network_profile_name: str, parameters: "_models.NetworkProfile", **kwargs ) -> "_models.NetworkProfile": """Creates or updates a network profile. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param network_profile_name: The name of the network profile. :type network_profile_name: str :param parameters: Parameters supplied to the create or update network profile operation. :type parameters: ~azure.mgmt.network.v2019_02_01.models.NetworkProfile :keyword callable cls: A custom type or function that will be passed the direct response :return: NetworkProfile, or the result of cls(response) :rtype: ~azure.mgmt.network.v2019_02_01.models.NetworkProfile :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.NetworkProfile"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-02-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.create_or_update.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'networkProfileName': self._serialize.url("network_profile_name", network_profile_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'NetworkProfile') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('NetworkProfile', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('NetworkProfile', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles/{networkProfileName}'} # type: ignore async def update_tags( self, resource_group_name: str, network_profile_name: str, parameters: "_models.TagsObject", **kwargs ) -> "_models.NetworkProfile": """Updates network profile tags. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param network_profile_name: The name of the network profile. :type network_profile_name: str :param parameters: Parameters supplied to update network profile tags. :type parameters: ~azure.mgmt.network.v2019_02_01.models.TagsObject :keyword callable cls: A custom type or function that will be passed the direct response :return: NetworkProfile, or the result of cls(response) :rtype: ~azure.mgmt.network.v2019_02_01.models.NetworkProfile :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.NetworkProfile"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-02-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.update_tags.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'networkProfileName': self._serialize.url("network_profile_name", network_profile_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'TagsObject') body_content_kwargs['content'] = body_content request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('NetworkProfile', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update_tags.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles/{networkProfileName}'} # type: ignore def list_all( self, **kwargs ) -> AsyncIterable["_models.NetworkProfileListResult"]: """Gets all the network profiles in a subscription. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either NetworkProfileListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2019_02_01.models.NetworkProfileListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.NetworkProfileListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-02-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_all.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('NetworkProfileListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_all.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkProfiles'} # type: ignore def list( self, resource_group_name: str, **kwargs ) -> AsyncIterable["_models.NetworkProfileListResult"]: """Gets all network profiles in a resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either NetworkProfileListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2019_02_01.models.NetworkProfileListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.NetworkProfileListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-02-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('NetworkProfileListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles'} # type: ignore
fnkr/POSS
refs/heads/master
tests/PossTest.py
1
import unittest import uuid from app.auth.models import User class PossTest(unittest.TestCase): def setUp(self): from app import app app.config.update( SERVER_NAME='localhost:%s' % app.config.get('PORT') ) self.app = app.test_client() from app import db self.db = db user = User('%s' % str(uuid.uuid4())[:8], '%s@example.com' % str(uuid.uuid4())[:8], '%s' % str(uuid.uuid4())[:8]) user.role_admin = True self.db.session.add(user) self.user_admin = user user = User('%s' % str(uuid.uuid4())[:8], '%s@example.com' % str(uuid.uuid4())[:8], '%s' % str(uuid.uuid4())[:8]) self.db.session.add(user) self.user_user = user self.baseUrl = 'http://localhost:%s' % app.config.get('PORT') def login(self, user): email = user.email name = user.name password = user.plain_password request = self.app.post('/login', data=dict( email=email, password=password ), follow_redirects=True) assert request.status_code == 200 assert 'Welcome %s.' % name in str(request.data)
Donkyhotay/MoonPy
refs/heads/master
zope/app/renderer/interfaces.py
1
############################################################################## # # Copyright (c) 2003 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Renderer Interface Declarations The source renderer takes a special type of string, an ISource, and is able to produce $Id: interfaces.py 25177 2004-06-02 13:17:31Z jim $ """ from zope.interface import Interface class ISource(Interface): """Simple base interface for all possible Wiki Page Source types.""" class ISourceRenderer(Interface): """Object implementing this interface are responsible for rendering an ISource objects to an output format. This is the base class for all possible output types.""" def __init__(self, source): """Initialize the renderer. The source argument is the source code that needs to be converted. """ def render(): """Renders the source into another format.""" class IHTMLRenderer(ISourceRenderer): """Renders an ISource object to HTML."""
IndonesiaX/edx-platform
refs/heads/master
lms/djangoapps/commerce/api/v1/tests/test_models.py
127
""" Tests for models. """ import ddt from django.test import TestCase from commerce.api.v1.models import Course from course_modes.models import CourseMode @ddt.ddt class CourseTests(TestCase): """ Tests for Course model. """ def setUp(self): super(CourseTests, self).setUp() self.course = Course('a/b/c', []) @ddt.unpack @ddt.data( ('credit', 'Credit'), ('professional', 'Professional Education'), ('no-id-professional', 'Professional Education'), ('verified', 'Verified Certificate'), ('honor', 'Honor Certificate'), ('audit', 'Audit'), ) def test_get_mode_display_name(self, slug, expected_display_name): """ Verify the method properly maps mode slugs to display names. """ mode = CourseMode(mode_slug=slug) self.assertEqual(self.course.get_mode_display_name(mode), expected_display_name) def test_get_mode_display_name_unknown_slug(self): """ Verify the method returns the slug if it has no known mapping. """ mode = CourseMode(mode_slug='Blah!') self.assertEqual(self.course.get_mode_display_name(mode), mode.mode_slug)
Dhivyap/ansible
refs/heads/devel
lib/ansible/modules/system/hostname.py
5
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2013, Hiroaki Nakamura <hnakamur@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: hostname author: - Adrian Likins (@alikins) - Hideki Saito (@saito-hideki) version_added: "1.4" short_description: Manage hostname requirements: [ hostname ] description: - Set system's hostname, supports most OSs/Distributions, including those using systemd. - Note, this module does *NOT* modify C(/etc/hosts). You need to modify it yourself using other modules like template or replace. - Windows, HP-UX and AIX are not currently supported. options: name: description: - Name of the host required: true use: description: - Which strategy to use to update the hostname. - If not set we try to autodetect, but this can be problematic, specially with containers as they can present misleading information. choices: ['generic', 'debian','sles', 'redhat', 'alpine', 'systemd', 'openrc', 'openbsd', 'solaris', 'freebsd'] version_added: '2.9' ''' EXAMPLES = ''' - hostname: name: web01 ''' import os import socket import traceback from ansible.module_utils.basic import ( AnsibleModule, get_distribution, get_distribution_version, get_platform, load_platform_subclass, ) from ansible.module_utils.facts.system.service_mgr import ServiceMgrFactCollector from ansible.module_utils._text import to_native STRATS = {'generic': 'Generic', 'debian': 'Debian', 'sles': 'SLES', 'redhat': 'RedHat', 'alpine': 'Alpine', 'systemd': 'Systemd', 'openrc': 'OpenRC', 'openbsd': 'OpenBSD', 'solaris': 'Solaris', 'freebsd': 'FreeBSD'} class UnimplementedStrategy(object): def __init__(self, module): self.module = module def update_current_and_permanent_hostname(self): self.unimplemented_error() def update_current_hostname(self): self.unimplemented_error() def update_permanent_hostname(self): self.unimplemented_error() def get_current_hostname(self): self.unimplemented_error() def set_current_hostname(self, name): self.unimplemented_error() def get_permanent_hostname(self): self.unimplemented_error() def set_permanent_hostname(self, name): self.unimplemented_error() def unimplemented_error(self): platform = get_platform() distribution = get_distribution() if distribution is not None: msg_platform = '%s (%s)' % (platform, distribution) else: msg_platform = platform self.module.fail_json( msg='hostname module cannot be used on platform %s' % msg_platform) class Hostname(object): """ This is a generic Hostname manipulation class that is subclassed based on platform. A subclass may wish to set different strategy instance to self.strategy. All subclasses MUST define platform and distribution (which may be None). """ platform = 'Generic' distribution = None strategy_class = UnimplementedStrategy def __new__(cls, *args, **kwargs): return load_platform_subclass(Hostname, args, kwargs) def __init__(self, module): self.module = module self.name = module.params['name'] self.use = module.params['use'] if self.use is not None: strat = globals()['%sStrategy' % STRATS[self.use]] self.strategy = strat(module) elif self.platform == 'Linux' and ServiceMgrFactCollector.is_systemd_managed(module): self.strategy = SystemdStrategy(module) else: self.strategy = self.strategy_class(module) def update_current_and_permanent_hostname(self): return self.strategy.update_current_and_permanent_hostname() def get_current_hostname(self): return self.strategy.get_current_hostname() def set_current_hostname(self, name): self.strategy.set_current_hostname(name) def get_permanent_hostname(self): return self.strategy.get_permanent_hostname() def set_permanent_hostname(self, name): self.strategy.set_permanent_hostname(name) class GenericStrategy(object): """ This is a generic Hostname manipulation strategy class. A subclass may wish to override some or all of these methods. - get_current_hostname() - get_permanent_hostname() - set_current_hostname(name) - set_permanent_hostname(name) """ def __init__(self, module): self.module = module self.changed = False self.hostname_cmd = self.module.get_bin_path('hostnamectl', False) if not self.hostname_cmd: self.hostname_cmd = self.module.get_bin_path('hostname', True) def update_current_and_permanent_hostname(self): self.update_current_hostname() self.update_permanent_hostname() return self.changed def update_current_hostname(self): name = self.module.params['name'] current_name = self.get_current_hostname() if current_name != name: if not self.module.check_mode: self.set_current_hostname(name) self.changed = True def update_permanent_hostname(self): name = self.module.params['name'] permanent_name = self.get_permanent_hostname() if permanent_name != name: if not self.module.check_mode: self.set_permanent_hostname(name) self.changed = True def get_current_hostname(self): cmd = [self.hostname_cmd] rc, out, err = self.module.run_command(cmd) if rc != 0: self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) return to_native(out).strip() def set_current_hostname(self, name): cmd = [self.hostname_cmd, name] rc, out, err = self.module.run_command(cmd) if rc != 0: self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) def get_permanent_hostname(self): return 'UNKNOWN' def set_permanent_hostname(self, name): pass class DebianStrategy(GenericStrategy): """ This is a Debian family Hostname manipulation strategy class - it edits the /etc/hostname file. """ HOSTNAME_FILE = '/etc/hostname' def get_permanent_hostname(self): if not os.path.isfile(self.HOSTNAME_FILE): try: open(self.HOSTNAME_FILE, "a").write("") except IOError as e: self.module.fail_json(msg="failed to write file: %s" % to_native(e), exception=traceback.format_exc()) try: f = open(self.HOSTNAME_FILE) try: return f.read().strip() finally: f.close() except Exception as e: self.module.fail_json(msg="failed to read hostname: %s" % to_native(e), exception=traceback.format_exc()) def set_permanent_hostname(self, name): try: f = open(self.HOSTNAME_FILE, 'w+') try: f.write("%s\n" % name) finally: f.close() except Exception as e: self.module.fail_json(msg="failed to update hostname: %s" % to_native(e), exception=traceback.format_exc()) class SLESStrategy(GenericStrategy): """ This is a SLES Hostname strategy class - it edits the /etc/HOSTNAME file. """ HOSTNAME_FILE = '/etc/HOSTNAME' def get_permanent_hostname(self): if not os.path.isfile(self.HOSTNAME_FILE): try: open(self.HOSTNAME_FILE, "a").write("") except IOError as e: self.module.fail_json(msg="failed to write file: %s" % to_native(e), exception=traceback.format_exc()) try: f = open(self.HOSTNAME_FILE) try: return f.read().strip() finally: f.close() except Exception as e: self.module.fail_json(msg="failed to read hostname: %s" % to_native(e), exception=traceback.format_exc()) def set_permanent_hostname(self, name): try: f = open(self.HOSTNAME_FILE, 'w+') try: f.write("%s\n" % name) finally: f.close() except Exception as e: self.module.fail_json(msg="failed to update hostname: %s" % to_native(e), exception=traceback.format_exc()) class RedHatStrategy(GenericStrategy): """ This is a Redhat Hostname strategy class - it edits the /etc/sysconfig/network file. """ NETWORK_FILE = '/etc/sysconfig/network' def get_permanent_hostname(self): try: f = open(self.NETWORK_FILE, 'rb') try: for line in f.readlines(): if line.startswith('HOSTNAME'): k, v = line.split('=') return v.strip() finally: f.close() except Exception as e: self.module.fail_json(msg="failed to read hostname: %s" % to_native(e), exception=traceback.format_exc()) def set_permanent_hostname(self, name): try: lines = [] found = False f = open(self.NETWORK_FILE, 'rb') try: for line in f.readlines(): if line.startswith('HOSTNAME'): lines.append("HOSTNAME=%s\n" % name) found = True else: lines.append(line) finally: f.close() if not found: lines.append("HOSTNAME=%s\n" % name) f = open(self.NETWORK_FILE, 'w+') try: f.writelines(lines) finally: f.close() except Exception as e: self.module.fail_json(msg="failed to update hostname: %s" % to_native(e), exception=traceback.format_exc()) class AlpineStrategy(GenericStrategy): """ This is a Alpine Linux Hostname manipulation strategy class - it edits the /etc/hostname file then run hostname -F /etc/hostname. """ HOSTNAME_FILE = '/etc/hostname' def update_current_and_permanent_hostname(self): self.update_permanent_hostname() self.update_current_hostname() return self.changed def get_permanent_hostname(self): if not os.path.isfile(self.HOSTNAME_FILE): try: open(self.HOSTNAME_FILE, "a").write("") except IOError as e: self.module.fail_json(msg="failed to write file: %s" % to_native(e), exception=traceback.format_exc()) try: f = open(self.HOSTNAME_FILE) try: return f.read().strip() finally: f.close() except Exception as e: self.module.fail_json(msg="failed to read hostname: %s" % to_native(e), exception=traceback.format_exc()) def set_permanent_hostname(self, name): try: f = open(self.HOSTNAME_FILE, 'w+') try: f.write("%s\n" % name) finally: f.close() except Exception as e: self.module.fail_json(msg="failed to update hostname: %s" % to_native(e), exception=traceback.format_exc()) def set_current_hostname(self, name): cmd = [self.hostname_cmd, '-F', self.HOSTNAME_FILE] rc, out, err = self.module.run_command(cmd) if rc != 0: self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) class SystemdStrategy(GenericStrategy): """ This is a Systemd hostname manipulation strategy class - it uses the hostnamectl command. """ def get_current_hostname(self): cmd = [self.hostname_cmd, '--transient', 'status'] rc, out, err = self.module.run_command(cmd) if rc != 0: self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) return to_native(out).strip() def set_current_hostname(self, name): if len(name) > 64: self.module.fail_json(msg="name cannot be longer than 64 characters on systemd servers, try a shorter name") cmd = [self.hostname_cmd, '--transient', 'set-hostname', name] rc, out, err = self.module.run_command(cmd) if rc != 0: self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) def get_permanent_hostname(self): cmd = [self.hostname_cmd, '--static', 'status'] rc, out, err = self.module.run_command(cmd) if rc != 0: self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) return to_native(out).strip() def set_permanent_hostname(self, name): if len(name) > 64: self.module.fail_json(msg="name cannot be longer than 64 characters on systemd servers, try a shorter name") cmd = [self.hostname_cmd, '--pretty', 'set-hostname', name] rc, out, err = self.module.run_command(cmd) if rc != 0: self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) cmd = [self.hostname_cmd, '--static', 'set-hostname', name] rc, out, err = self.module.run_command(cmd) if rc != 0: self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) class OpenRCStrategy(GenericStrategy): """ This is a Gentoo (OpenRC) Hostname manipulation strategy class - it edits the /etc/conf.d/hostname file. """ HOSTNAME_FILE = '/etc/conf.d/hostname' def get_permanent_hostname(self): name = 'UNKNOWN' try: try: f = open(self.HOSTNAME_FILE, 'r') for line in f: line = line.strip() if line.startswith('hostname='): name = line[10:].strip('"') break except Exception as e: self.module.fail_json(msg="failed to read hostname: %s" % to_native(e), exception=traceback.format_exc()) finally: f.close() return name def set_permanent_hostname(self, name): try: try: f = open(self.HOSTNAME_FILE, 'r') lines = [x.strip() for x in f] for i, line in enumerate(lines): if line.startswith('hostname='): lines[i] = 'hostname="%s"' % name break f.close() f = open(self.HOSTNAME_FILE, 'w') f.write('\n'.join(lines) + '\n') except Exception as e: self.module.fail_json(msg="failed to update hostname: %s" % to_native(e), exception=traceback.format_exc()) finally: f.close() class OpenBSDStrategy(GenericStrategy): """ This is a OpenBSD family Hostname manipulation strategy class - it edits the /etc/myname file. """ HOSTNAME_FILE = '/etc/myname' def get_permanent_hostname(self): if not os.path.isfile(self.HOSTNAME_FILE): try: open(self.HOSTNAME_FILE, "a").write("") except IOError as e: self.module.fail_json(msg="failed to write file: %s" % to_native(e), exception=traceback.format_exc()) try: f = open(self.HOSTNAME_FILE) try: return f.read().strip() finally: f.close() except Exception as e: self.module.fail_json(msg="failed to read hostname: %s" % to_native(e), exception=traceback.format_exc()) def set_permanent_hostname(self, name): try: f = open(self.HOSTNAME_FILE, 'w+') try: f.write("%s\n" % name) finally: f.close() except Exception as e: self.module.fail_json(msg="failed to update hostname: %s" % to_native(e), exception=traceback.format_exc()) class SolarisStrategy(GenericStrategy): """ This is a Solaris11 or later Hostname manipulation strategy class - it execute hostname command. """ def set_current_hostname(self, name): cmd_option = '-t' cmd = [self.hostname_cmd, cmd_option, name] rc, out, err = self.module.run_command(cmd) if rc != 0: self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) def get_permanent_hostname(self): fmri = 'svc:/system/identity:node' pattern = 'config/nodename' cmd = '/usr/sbin/svccfg -s %s listprop -o value %s' % (fmri, pattern) rc, out, err = self.module.run_command(cmd, use_unsafe_shell=True) if rc != 0: self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) return to_native(out).strip() def set_permanent_hostname(self, name): cmd = [self.hostname_cmd, name] rc, out, err = self.module.run_command(cmd) if rc != 0: self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) class FreeBSDStrategy(GenericStrategy): """ This is a FreeBSD hostname manipulation strategy class - it edits the /etc/rc.conf.d/hostname file. """ HOSTNAME_FILE = '/etc/rc.conf.d/hostname' def get_permanent_hostname(self): name = 'UNKNOWN' if not os.path.isfile(self.HOSTNAME_FILE): try: open(self.HOSTNAME_FILE, "a").write("hostname=temporarystub\n") except IOError as e: self.module.fail_json(msg="failed to write file: %s" % to_native(e), exception=traceback.format_exc()) try: try: f = open(self.HOSTNAME_FILE, 'r') for line in f: line = line.strip() if line.startswith('hostname='): name = line[10:].strip('"') break except Exception as e: self.module.fail_json(msg="failed to read hostname: %s" % to_native(e), exception=traceback.format_exc()) finally: f.close() return name def set_permanent_hostname(self, name): try: try: f = open(self.HOSTNAME_FILE, 'r') lines = [x.strip() for x in f] for i, line in enumerate(lines): if line.startswith('hostname='): lines[i] = 'hostname="%s"' % name break f.close() f = open(self.HOSTNAME_FILE, 'w') f.write('\n'.join(lines) + '\n') except Exception as e: self.module.fail_json(msg="failed to update hostname: %s" % to_native(e), exception=traceback.format_exc()) finally: f.close() class FedoraHostname(Hostname): platform = 'Linux' distribution = 'Fedora' strategy_class = SystemdStrategy class SLESHostname(Hostname): platform = 'Linux' distribution = 'Sles' try: distribution_version = get_distribution_version() # cast to float may raise ValueError on non SLES, we use float for a little more safety over int if distribution_version and 10 <= float(distribution_version) <= 12: strategy_class = SLESStrategy else: raise ValueError() except ValueError: strategy_class = UnimplementedStrategy class OpenSUSEHostname(Hostname): platform = 'Linux' distribution = 'Opensuse' strategy_class = SystemdStrategy class OpenSUSELeapHostname(Hostname): platform = 'Linux' distribution = 'Opensuse-leap' strategy_class = SystemdStrategy class AsteraHostname(Hostname): platform = 'Linux' distribution = '"astralinuxce"' strategy_class = SystemdStrategy class ArchHostname(Hostname): platform = 'Linux' distribution = 'Arch' strategy_class = SystemdStrategy class ArchARMHostname(Hostname): platform = 'Linux' distribution = 'Archarm' strategy_class = SystemdStrategy class RHELHostname(Hostname): platform = 'Linux' distribution = 'Redhat' strategy_class = RedHatStrategy class CentOSHostname(Hostname): platform = 'Linux' distribution = 'Centos' strategy_class = RedHatStrategy class ClearLinuxHostname(Hostname): platform = 'Linux' distribution = 'Clear-linux-os' strategy_class = SystemdStrategy class CloudlinuxHostname(Hostname): platform = 'Linux' distribution = 'Cloudlinux' strategy_class = RedHatStrategy class CoreosHostname(Hostname): platform = 'Linux' distribution = 'Coreos' strategy_class = SystemdStrategy class ScientificHostname(Hostname): platform = 'Linux' distribution = 'Scientific' strategy_class = RedHatStrategy class OracleLinuxHostname(Hostname): platform = 'Linux' distribution = 'Oracle' strategy_class = RedHatStrategy class VirtuozzoLinuxHostname(Hostname): platform = 'Linux' distribution = 'Virtuozzo' strategy_class = RedHatStrategy class AmazonLinuxHostname(Hostname): platform = 'Linux' distribution = 'Amazon' strategy_class = RedHatStrategy class DebianHostname(Hostname): platform = 'Linux' distribution = 'Debian' strategy_class = DebianStrategy class KylinHostname(Hostname): platform = 'Linux' distribution = 'Kylin' strategy_class = DebianStrategy class CumulusHostname(Hostname): platform = 'Linux' distribution = 'Cumulus-linux' strategy_class = DebianStrategy class KaliHostname(Hostname): platform = 'Linux' distribution = 'Kali' strategy_class = DebianStrategy class UbuntuHostname(Hostname): platform = 'Linux' distribution = 'Ubuntu' strategy_class = DebianStrategy class LinuxmintHostname(Hostname): platform = 'Linux' distribution = 'Linuxmint' strategy_class = DebianStrategy class LinaroHostname(Hostname): platform = 'Linux' distribution = 'Linaro' strategy_class = DebianStrategy class DevuanHostname(Hostname): platform = 'Linux' distribution = 'Devuan' strategy_class = DebianStrategy class RaspbianHostname(Hostname): platform = 'Linux' distribution = 'Raspbian' strategy_class = DebianStrategy class GentooHostname(Hostname): platform = 'Linux' distribution = 'Gentoo' strategy_class = OpenRCStrategy class ALTLinuxHostname(Hostname): platform = 'Linux' distribution = 'Altlinux' strategy_class = RedHatStrategy class AlpineLinuxHostname(Hostname): platform = 'Linux' distribution = 'Alpine' strategy_class = AlpineStrategy class OpenBSDHostname(Hostname): platform = 'OpenBSD' distribution = None strategy_class = OpenBSDStrategy class SolarisHostname(Hostname): platform = 'SunOS' distribution = None strategy_class = SolarisStrategy class FreeBSDHostname(Hostname): platform = 'FreeBSD' distribution = None strategy_class = FreeBSDStrategy class NetBSDHostname(Hostname): platform = 'NetBSD' distribution = None strategy_class = FreeBSDStrategy class NeonHostname(Hostname): platform = 'Linux' distribution = 'Neon' strategy_class = DebianStrategy def main(): module = AnsibleModule( argument_spec=dict( name=dict(type='str', required=True), use=dict(type='str', choices=STRATS.keys()) ), supports_check_mode=True, ) hostname = Hostname(module) name = module.params['name'] current_hostname = hostname.get_current_hostname() permanent_hostname = hostname.get_permanent_hostname() changed = hostname.update_current_and_permanent_hostname() if name != current_hostname: name_before = current_hostname elif name != permanent_hostname: name_before = permanent_hostname kw = dict(changed=changed, name=name, ansible_facts=dict(ansible_hostname=name.split('.')[0], ansible_nodename=name, ansible_fqdn=socket.getfqdn(), ansible_domain='.'.join(socket.getfqdn().split('.')[1:]))) if changed: kw['diff'] = {'after': 'hostname = ' + name + '\n', 'before': 'hostname = ' + name_before + '\n'} module.exit_json(**kw) if __name__ == '__main__': main()
0Chencc/CTFCrackTools
refs/heads/master
Lib/test/test_readline.py
60
""" Very minimal unittests for parts of the readline module. These tests were added to check that the libedit emulation on OSX and the "real" readline have the same interface for history manipulation. That's why the tests cover only a small subset of the interface. """ import unittest from test.test_support import run_unittest, import_module # Skip tests if there is no readline module readline = import_module('readline') class TestHistoryManipulation (unittest.TestCase): @unittest.skipIf(not hasattr(readline, 'clear_history'), "The history update test cannot be run because the " "clear_history method is not available.") def testHistoryUpdates(self): readline.clear_history() readline.add_history("first line") readline.add_history("second line") self.assertEqual(readline.get_history_item(0), None) self.assertEqual(readline.get_history_item(1), "first line") self.assertEqual(readline.get_history_item(2), "second line") readline.replace_history_item(0, "replaced line") self.assertEqual(readline.get_history_item(0), None) self.assertEqual(readline.get_history_item(1), "replaced line") self.assertEqual(readline.get_history_item(2), "second line") self.assertEqual(readline.get_current_history_length(), 2) readline.remove_history_item(0) self.assertEqual(readline.get_history_item(0), None) self.assertEqual(readline.get_history_item(1), "second line") self.assertEqual(readline.get_current_history_length(), 1) def test_main(): run_unittest(TestHistoryManipulation) if __name__ == "__main__": test_main()
kenshay/ImageScripter
refs/heads/master
ProgramData/SystemFiles/Python/Lib/site-packages/pytank/Core/sadfas.py
2
from elan import * HlConfig.cautionreset.Wait()
yk5/beam
refs/heads/master
sdks/python/apache_beam/internal/util.py
9
# # 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. # """Utility functions used throughout the package. For internal use only. No backwards compatibility guarantees. """ import logging from multiprocessing.pool import ThreadPool import threading import weakref class ArgumentPlaceholder(object): """For internal use only; no backwards-compatibility guarantees. A place holder object replacing PValues in argument lists. A Fn object can take any number of "side inputs", which are PValues that will be evaluated during pipeline execution and will be provided to the function at the moment of its execution as positional or keyword arguments. This is used only internally and should never be used by user code. A custom Fn object by the time it executes will have such values replaced with real computed values. """ def __eq__(self, other): """Tests for equality of two placeholder objects. Args: other: Another placeholder object to compare to. This method is used only for test code. All placeholder objects are equal to each other. """ return isinstance(other, ArgumentPlaceholder) def remove_objects_from_args(args, kwargs, pvalue_classes): """For internal use only; no backwards-compatibility guarantees. Replaces all objects of a given type in args/kwargs with a placeholder. Args: args: A list of positional arguments. kwargs: A dictionary of keyword arguments. pvalue_classes: A tuple of class objects representing the types of the arguments that must be replaced with a placeholder value (instance of ArgumentPlaceholder) Returns: A 3-tuple containing a modified list of positional arguments, a modified dictionary of keyword arguments, and a list of all objects replaced with a placeholder value. """ pvals = [] def swapper(value): pvals.append(value) return ArgumentPlaceholder() new_args = [swapper(v) if isinstance(v, pvalue_classes) else v for v in args] # Make sure the order in which we process the dictionary keys is predictable # by sorting the entries first. This will be important when putting back # PValues. new_kwargs = dict((k, swapper(v)) if isinstance(v, pvalue_classes) else (k, v) for k, v in sorted(kwargs.iteritems())) return (new_args, new_kwargs, pvals) def insert_values_in_args(args, kwargs, values): """For internal use only; no backwards-compatibility guarantees. Replaces all placeholders in args/kwargs with actual values. Args: args: A list of positional arguments. kwargs: A dictionary of keyword arguments. values: A list of values that will be used to replace placeholder values. Returns: A 2-tuple containing a modified list of positional arguments, and a modified dictionary of keyword arguments. """ # Use a local iterator so that we don't modify values. v_iter = iter(values) new_args = [ v_iter.next() if isinstance(arg, ArgumentPlaceholder) else arg for arg in args] new_kwargs = dict( (k, v_iter.next()) if isinstance(v, ArgumentPlaceholder) else (k, v) for k, v in sorted(kwargs.iteritems())) return (new_args, new_kwargs) def run_using_threadpool(fn_to_execute, inputs, pool_size): """For internal use only; no backwards-compatibility guarantees. Runs the given function on given inputs using a thread pool. Args: fn_to_execute: Function to execute inputs: Inputs on which given function will be executed in parallel. pool_size: Size of thread pool. Returns: Results retrieved after executing the given function on given inputs. """ # ThreadPool crashes in old versions of Python (< 2.7.5) if created # from a child thread. (http://bugs.python.org/issue10015) if not hasattr(threading.current_thread(), '_children'): threading.current_thread()._children = weakref.WeakKeyDictionary() pool = ThreadPool(min(pool_size, len(inputs))) try: # We record and reset logging level here since 'apitools' library Beam # depends on updates the logging level when used with a threadpool - # https://github.com/google/apitools/issues/141 # TODO: Remove this once above issue in 'apitools' is fixed. old_level = logging.getLogger().level return pool.map(fn_to_execute, inputs) finally: pool.terminate() logging.getLogger().setLevel(old_level)
pstirparo/artifacts
refs/heads/master
tests/registry_test.py
1
# -*- coding: utf-8 -*- """Tests for the artifact definitions registry.""" import io import unittest from artifacts import errors from artifacts import reader from artifacts import registry from artifacts import source_type from tests import test_lib class TestSourceType(source_type.SourceType): """Class that implements a test source type.""" TYPE_INDICATOR = u'test' def __init__(self, test=None): """Initializes the source type object. Args: test (Optional[str]): test string. Raises: FormatError: when test is not set. """ if not test: raise errors.FormatError(u'Missing test value.') super(TestSourceType, self).__init__() self.test = test def AsDict(self): """Represents a source type as a dictionary. Returns: dict[str, str]: source type attributes. """ return {u'test': self.test} class ArtifactDefinitionsRegistryTest(test_lib.BaseTestCase): """Tests for the artifact definitions registry.""" # pylint: disable=protected-access @test_lib.skipUnlessHasTestFile(['definitions.yaml']) def testArtifactDefinitionsRegistry(self): """Tests the ArtifactDefinitionsRegistry functions.""" artifact_registry = registry.ArtifactDefinitionsRegistry() artifact_reader = reader.YamlArtifactsReader() test_file = self._GetTestFilePath(['definitions.yaml']) for artifact_definition in artifact_reader.ReadFile(test_file): artifact_registry.RegisterDefinition(artifact_definition) # Make sure the test file got turned into artifacts. self.assertEqual(len(artifact_registry.GetDefinitions()), 7) artifact_definition = artifact_registry.GetDefinitionByName(u'EventLogs') self.assertIsNotNone(artifact_definition) # Try to register something already registered with self.assertRaises(KeyError): artifact_registry.RegisterDefinition(artifact_definition) # Deregister artifact_registry.DeregisterDefinition(artifact_definition) # Check it is gone with self.assertRaises(KeyError): artifact_registry.DeregisterDefinition(artifact_definition) self.assertEqual(len(artifact_registry.GetDefinitions()), 6) test_artifact_definition = artifact_registry.GetDefinitionByName( u'SecurityEventLogEvtx') self.assertIsNotNone(test_artifact_definition) self.assertEqual(test_artifact_definition.name, u'SecurityEventLogEvtx') expected_description = ( u'Windows Security Event log for Vista or later systems.') self.assertEqual(test_artifact_definition.description, expected_description) bad_args = io.BytesIO( b'name: SecurityEventLogEvtx\n' b'doc: Windows Security Event log for Vista or later systems.\n' b'sources:\n' b'- type: FILE\n' b' attributes: {broken: [\'%%environ_systemroot%%\\System32\\' b'winevt\\Logs\\Security.evtx\']}\n' b'conditions: [os_major_version >= 6]\n' b'labels: [Logs]\n' b'supported_os: [Windows]\n' b'urls: [\'http://www.forensicswiki.org/wiki/\n' b'Windows_XML_Event_Log_(EVTX)\']\n') generator = artifact_reader.ReadFileObject(bad_args) with self.assertRaises(errors.FormatError): next(generator) def testSourceTypeFunctions(self): """Tests the source type functions.""" number_of_source_types = len( registry.ArtifactDefinitionsRegistry._source_type_classes) registry.ArtifactDefinitionsRegistry.RegisterSourceType(TestSourceType) self.assertEqual( len(registry.ArtifactDefinitionsRegistry._source_type_classes), number_of_source_types + 1) with self.assertRaises(KeyError): registry.ArtifactDefinitionsRegistry.RegisterSourceType(TestSourceType) registry.ArtifactDefinitionsRegistry.DeregisterSourceType(TestSourceType) self.assertEqual( len(registry.ArtifactDefinitionsRegistry._source_type_classes), number_of_source_types) registry.ArtifactDefinitionsRegistry.RegisterSourceTypes([TestSourceType]) self.assertEqual( len(registry.ArtifactDefinitionsRegistry._source_type_classes), number_of_source_types + 1) with self.assertRaises(KeyError): registry.ArtifactDefinitionsRegistry.RegisterSourceTypes([TestSourceType]) source_object = registry.ArtifactDefinitionsRegistry.CreateSourceType( u'test', {u'test': u'test123'}) self.assertIsNotNone(source_object) self.assertEqual(source_object.test, u'test123') with self.assertRaises(errors.FormatError): source_object = registry.ArtifactDefinitionsRegistry.CreateSourceType( u'test', {}) with self.assertRaises(errors.FormatError): source_object = registry.ArtifactDefinitionsRegistry.CreateSourceType( u'bogus', {}) registry.ArtifactDefinitionsRegistry.DeregisterSourceType(TestSourceType) if __name__ == '__main__': unittest.main()
lcharleux/abapy
refs/heads/master
doc/sphinxext/apigen.py
59
"""Attempt to generate templates for module reference with Sphinx XXX - we exclude extension modules To include extension modules, first identify them as valid in the ``_uri2path`` method, then handle them in the ``_parse_module`` script. We get functions and classes by parsing the text of .py files. Alternatively we could import the modules for discovery, and we'd have to do that for extension modules. This would involve changing the ``_parse_module`` method to work via import and introspection, and might involve changing ``discover_modules`` (which determines which files are modules, and therefore which module URIs will be passed to ``_parse_module``). NOTE: this is a modified version of a script originally shipped with the PyMVPA project, which we've adapted for NIPY use. PyMVPA is an MIT-licensed project.""" # Stdlib imports import os import re # Functions and classes class ApiDocWriter(object): ''' Class for automatic detection and parsing of API docs to Sphinx-parsable reST format''' # only separating first two levels rst_section_levels = ['*', '=', '-', '~', '^'] def __init__(self, package_name, rst_extension='.rst', package_skip_patterns=None, module_skip_patterns=None, ): ''' Initialize package for parsing Parameters ---------- package_name : string Name of the top-level package. *package_name* must be the name of an importable package rst_extension : string, optional Extension for reST files, default '.rst' package_skip_patterns : None or sequence of {strings, regexps} Sequence of strings giving URIs of packages to be excluded Operates on the package path, starting at (including) the first dot in the package path, after *package_name* - so, if *package_name* is ``sphinx``, then ``sphinx.util`` will result in ``.util`` being passed for earching by these regexps. If is None, gives default. Default is: ['\.tests$'] module_skip_patterns : None or sequence Sequence of strings giving URIs of modules to be excluded Operates on the module name including preceding URI path, back to the first dot after *package_name*. For example ``sphinx.util.console`` results in the string to search of ``.util.console`` If is None, gives default. Default is: ['\.setup$', '\._'] ''' if package_skip_patterns is None: package_skip_patterns = ['\\.tests$'] if module_skip_patterns is None: module_skip_patterns = ['\\.setup$', '\\._'] self.package_name = package_name self.rst_extension = rst_extension self.package_skip_patterns = package_skip_patterns self.module_skip_patterns = module_skip_patterns def get_package_name(self): return self._package_name def set_package_name(self, package_name): ''' Set package_name >>> docwriter = ApiDocWriter('sphinx') >>> import sphinx >>> docwriter.root_path == sphinx.__path__[0] True >>> docwriter.package_name = 'docutils' >>> import docutils >>> docwriter.root_path == docutils.__path__[0] True ''' # It's also possible to imagine caching the module parsing here self._package_name = package_name self.root_module = __import__(package_name) self.root_path = self.root_module.__path__[0] self.written_modules = None package_name = property(get_package_name, set_package_name, None, 'get/set package_name') def _get_object_name(self, line): ''' Get second token in line >>> docwriter = ApiDocWriter('sphinx') >>> docwriter._get_object_name(" def func(): ") 'func' >>> docwriter._get_object_name(" class Klass(object): ") 'Klass' >>> docwriter._get_object_name(" class Klass: ") 'Klass' ''' name = line.split()[1].split('(')[0].strip() # in case we have classes which are not derived from object # ie. old style classes return name.rstrip(':') def _uri2path(self, uri): ''' Convert uri to absolute filepath Parameters ---------- uri : string URI of python module to return path for Returns ------- path : None or string Returns None if there is no valid path for this URI Otherwise returns absolute file system path for URI Examples -------- >>> docwriter = ApiDocWriter('sphinx') >>> import sphinx >>> modpath = sphinx.__path__[0] >>> res = docwriter._uri2path('sphinx.builder') >>> res == os.path.join(modpath, 'builder.py') True >>> res = docwriter._uri2path('sphinx') >>> res == os.path.join(modpath, '__init__.py') True >>> docwriter._uri2path('sphinx.does_not_exist') ''' if uri == self.package_name: return os.path.join(self.root_path, '__init__.py') path = uri.replace('.', os.path.sep) path = path.replace(self.package_name + os.path.sep, '') path = os.path.join(self.root_path, path) # XXX maybe check for extensions as well? if os.path.exists(path + '.py'): # file path += '.py' elif os.path.exists(os.path.join(path, '__init__.py')): path = os.path.join(path, '__init__.py') else: return None return path def _path2uri(self, dirpath): ''' Convert directory path to uri ''' relpath = dirpath.replace(self.root_path, self.package_name) if relpath.startswith(os.path.sep): relpath = relpath[1:] return relpath.replace(os.path.sep, '.') def _parse_module(self, uri): ''' Parse module defined in *uri* ''' filename = self._uri2path(uri) if filename is None: # nothing that we could handle here. return ([],[]) f = open(filename, 'rt') functions, classes = self._parse_lines(f) f.close() return functions, classes def _parse_lines(self, linesource): ''' Parse lines of text for functions and classes ''' functions = [] classes = [] for line in linesource: if line.startswith('def ') and line.count('('): # exclude private stuff name = self._get_object_name(line) if not name.startswith('_'): functions.append(name) elif line.startswith('class '): # exclude private stuff name = self._get_object_name(line) if not name.startswith('_'): classes.append(name) else: pass functions.sort() classes.sort() return functions, classes def generate_api_doc(self, uri): '''Make autodoc documentation template string for a module Parameters ---------- uri : string python location of module - e.g 'sphinx.builder' Returns ------- S : string Contents of API doc ''' # get the names of all classes and functions functions, classes = self._parse_module(uri) if not len(functions) and not len(classes): print 'WARNING: Empty -',uri # dbg return '' # Make a shorter version of the uri that omits the package name for # titles uri_short = re.sub(r'^%s\.' % self.package_name,'',uri) ad = '.. AUTO-GENERATED FILE -- DO NOT EDIT!\n\n' chap_title = uri_short ad += (chap_title+'\n'+ self.rst_section_levels[1] * len(chap_title) + '\n\n') # Set the chapter title to read 'module' for all modules except for the # main packages if '.' in uri: title = 'Module: :mod:`' + uri_short + '`' else: title = ':mod:`' + uri_short + '`' ad += title + '\n' + self.rst_section_levels[2] * len(title) if len(classes): ad += '\nInheritance diagram for ``%s``:\n\n' % uri ad += '.. inheritance-diagram:: %s \n' % uri ad += ' :parts: 3\n' ad += '\n.. automodule:: ' + uri + '\n' ad += '\n.. currentmodule:: ' + uri + '\n' multi_class = len(classes) > 1 multi_fx = len(functions) > 1 if multi_class: ad += '\n' + 'Classes' + '\n' + \ self.rst_section_levels[2] * 7 + '\n' elif len(classes) and multi_fx: ad += '\n' + 'Class' + '\n' + \ self.rst_section_levels[2] * 5 + '\n' for c in classes: ad += '\n:class:`' + c + '`\n' \ + self.rst_section_levels[multi_class + 2 ] * \ (len(c)+9) + '\n\n' ad += '\n.. autoclass:: ' + c + '\n' # must NOT exclude from index to keep cross-refs working ad += ' :members:\n' \ ' :undoc-members:\n' \ ' :show-inheritance:\n' \ ' :inherited-members:\n' \ '\n' \ ' .. automethod:: __init__\n' if multi_fx: ad += '\n' + 'Functions' + '\n' + \ self.rst_section_levels[2] * 9 + '\n\n' elif len(functions) and multi_class: ad += '\n' + 'Function' + '\n' + \ self.rst_section_levels[2] * 8 + '\n\n' for f in functions: # must NOT exclude from index to keep cross-refs working ad += '\n.. autofunction:: ' + uri + '.' + f + '\n\n' return ad def _survives_exclude(self, matchstr, match_type): ''' Returns True if *matchstr* does not match patterns ``self.package_name`` removed from front of string if present Examples -------- >>> dw = ApiDocWriter('sphinx') >>> dw._survives_exclude('sphinx.okpkg', 'package') True >>> dw.package_skip_patterns.append('^\\.badpkg$') >>> dw._survives_exclude('sphinx.badpkg', 'package') False >>> dw._survives_exclude('sphinx.badpkg', 'module') True >>> dw._survives_exclude('sphinx.badmod', 'module') True >>> dw.module_skip_patterns.append('^\\.badmod$') >>> dw._survives_exclude('sphinx.badmod', 'module') False ''' if match_type == 'module': patterns = self.module_skip_patterns elif match_type == 'package': patterns = self.package_skip_patterns else: raise ValueError('Cannot interpret match type "%s"' % match_type) # Match to URI without package name L = len(self.package_name) if matchstr[:L] == self.package_name: matchstr = matchstr[L:] for pat in patterns: try: pat.search except AttributeError: pat = re.compile(pat) if pat.search(matchstr): return False return True def discover_modules(self): ''' Return module sequence discovered from ``self.package_name`` Parameters ---------- None Returns ------- mods : sequence Sequence of module names within ``self.package_name`` Examples -------- >>> dw = ApiDocWriter('sphinx') >>> mods = dw.discover_modules() >>> 'sphinx.util' in mods True >>> dw.package_skip_patterns.append('\.util$') >>> 'sphinx.util' in dw.discover_modules() False >>> ''' modules = [self.package_name] # raw directory parsing for dirpath, dirnames, filenames in os.walk(self.root_path): # Check directory names for packages root_uri = self._path2uri(os.path.join(self.root_path, dirpath)) for dirname in dirnames[:]: # copy list - we modify inplace package_uri = '.'.join((root_uri, dirname)) if (self._uri2path(package_uri) and self._survives_exclude(package_uri, 'package')): modules.append(package_uri) else: dirnames.remove(dirname) # Check filenames for modules for filename in filenames: module_name = filename[:-3] module_uri = '.'.join((root_uri, module_name)) if (self._uri2path(module_uri) and self._survives_exclude(module_uri, 'module')): modules.append(module_uri) return sorted(modules) def write_modules_api(self, modules,outdir): # write the list written_modules = [] for m in modules: api_str = self.generate_api_doc(m) if not api_str: continue # write out to file outfile = os.path.join(outdir, m + self.rst_extension) fileobj = open(outfile, 'wt') fileobj.write(api_str) fileobj.close() written_modules.append(m) self.written_modules = written_modules def write_api_docs(self, outdir): """Generate API reST files. Parameters ---------- outdir : string Directory name in which to store files We create automatic filenames for each module Returns ------- None Notes ----- Sets self.written_modules to list of written modules """ if not os.path.exists(outdir): os.mkdir(outdir) # compose list of modules modules = self.discover_modules() self.write_modules_api(modules,outdir) def write_index(self, outdir, froot='gen', relative_to=None): """Make a reST API index file from written files Parameters ---------- path : string Filename to write index to outdir : string Directory to which to write generated index file froot : string, optional root (filename without extension) of filename to write to Defaults to 'gen'. We add ``self.rst_extension``. relative_to : string path to which written filenames are relative. This component of the written file path will be removed from outdir, in the generated index. Default is None, meaning, leave path as it is. """ if self.written_modules is None: raise ValueError('No modules written') # Get full filename path path = os.path.join(outdir, froot+self.rst_extension) # Path written into index is relative to rootpath if relative_to is not None: relpath = outdir.replace(relative_to + os.path.sep, '') else: relpath = outdir idx = open(path,'wt') w = idx.write w('.. AUTO-GENERATED FILE -- DO NOT EDIT!\n\n') w('.. toctree::\n\n') for f in self.written_modules: w(' %s\n' % os.path.join(relpath,f)) idx.close()
pepetreshere/odoo
refs/heads/patch-2
odoo/addons/test_action_bindings/tests/__init__.py
13
from . import test_bindings
gurneyalex/partner-contact
refs/heads/8.0
base_partner_sequence/tests/test_base_partner_sequence.py
10
# -*- coding: utf-8 -*- # © 2015 ACSONE SA/NV (<http://acsone.eu>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import openerp.tests.common as common class TestBasePartnerSequence(common.TransactionCase): def test_ref_sequence_on_partner(self): res_partner = self.env['res.partner'] partner = res_partner.create({ 'name': "test1", 'email': "test@test.com"}) self.assertTrue(partner.ref, "A partner has always a ref.") copy = partner.copy() self.assertTrue(copy.ref, "A partner with ref created by copy " "has a ref by default.")
takeshineshiro/django
refs/heads/master
tests/template_tests/filter_tests/test_rjust.py
521
from django.template.defaultfilters import rjust from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class RjustTests(SimpleTestCase): @setup({'rjust01': '{% autoescape off %}.{{ a|rjust:"5" }}. .{{ b|rjust:"5" }}.{% endautoescape %}'}) def test_rjust01(self): output = self.engine.render_to_string('rjust01', {"a": "a&b", "b": mark_safe("a&b")}) self.assertEqual(output, ". a&b. . a&b.") @setup({'rjust02': '.{{ a|rjust:"5" }}. .{{ b|rjust:"5" }}.'}) def test_rjust02(self): output = self.engine.render_to_string('rjust02', {"a": "a&b", "b": mark_safe("a&b")}) self.assertEqual(output, ". a&amp;b. . a&b.") class FunctionTests(SimpleTestCase): def test_rjust(self): self.assertEqual(rjust('test', 10), ' test') def test_less_than_string_length(self): self.assertEqual(rjust('test', 3), 'test') def test_non_string_input(self): self.assertEqual(rjust(123, 4), ' 123')
dhalperi/beam
refs/heads/master
sdks/python/apache_beam/runners/worker/data_plane_test.py
2
# # 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. # """Tests for apache_beam.runners.worker.data_plane.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging import sys import threading import unittest import grpc from concurrent import futures from apache_beam.runners.api import beam_fn_api_pb2 from apache_beam.runners.worker import data_plane def timeout(timeout_secs): def decorate(fn): exc_info = [] def wrapper(*args, **kwargs): def call_fn(): try: fn(*args, **kwargs) except: # pylint: disable=bare-except exc_info[:] = sys.exc_info() thread = threading.Thread(target=call_fn) thread.daemon = True thread.start() thread.join(timeout_secs) if exc_info: t, v, tb = exc_info # pylint: disable=unbalanced-tuple-unpacking raise t, v, tb assert not thread.is_alive(), 'timed out after %s seconds' % timeout_secs return wrapper return decorate class DataChannelTest(unittest.TestCase): @timeout(5) def test_grpc_data_channel(self): data_channel_service = data_plane.GrpcServerDataChannel() server = grpc.server(futures.ThreadPoolExecutor(max_workers=2)) beam_fn_api_pb2.add_BeamFnDataServicer_to_server( data_channel_service, server) test_port = server.add_insecure_port('[::]:0') server.start() data_channel_stub = beam_fn_api_pb2.BeamFnDataStub( grpc.insecure_channel('localhost:%s' % test_port)) data_channel_client = data_plane.GrpcClientDataChannel(data_channel_stub) try: self._data_channel_test(data_channel_service, data_channel_client) finally: data_channel_client.close() data_channel_service.close() data_channel_client.wait() data_channel_service.wait() def test_in_memory_data_channel(self): channel = data_plane.InMemoryDataChannel() self._data_channel_test(channel, channel.inverse()) def _data_channel_test(self, server, client): self._data_channel_test_one_direction(server, client) self._data_channel_test_one_direction(client, server) def _data_channel_test_one_direction(self, from_channel, to_channel): def send(instruction_id, target, data): stream = from_channel.output_stream(instruction_id, target) stream.write(data) stream.close() target_1 = beam_fn_api_pb2.Target( primitive_transform_reference='1', name='out') target_2 = beam_fn_api_pb2.Target( primitive_transform_reference='2', name='out') # Single write. send('0', target_1, 'abc') self.assertEqual( list(to_channel.input_elements('0', [target_1])), [beam_fn_api_pb2.Elements.Data( instruction_reference='0', target=target_1, data='abc')]) # Multiple interleaved writes to multiple instructions. target_2 = beam_fn_api_pb2.Target( primitive_transform_reference='2', name='out') send('1', target_1, 'abc') send('2', target_1, 'def') self.assertEqual( list(to_channel.input_elements('1', [target_1])), [beam_fn_api_pb2.Elements.Data( instruction_reference='1', target=target_1, data='abc')]) send('2', target_2, 'ghi') self.assertEqual( list(to_channel.input_elements('2', [target_1, target_2])), [beam_fn_api_pb2.Elements.Data( instruction_reference='2', target=target_1, data='def'), beam_fn_api_pb2.Elements.Data( instruction_reference='2', target=target_2, data='ghi')]) if __name__ == '__main__': logging.getLogger().setLevel(logging.INFO) unittest.main()
janssen/kivy
refs/heads/master
kivy/factory_registers.py
15
# Auto-generated file by setup.py build_factory from kivy.factory import Factory r = Factory.register r('Adapter', module='kivy.adapters.adapter') r('ListAdapter', module='kivy.adapters.listadapter') r('SimpleListAdapter', module='kivy.adapters.simplelistadapter') r('DictAdapter', module='kivy.adapters.dictadapter') r('SelectableDataItem', module='kivy.adapters.models') r('Animation', module='kivy.animation') r('AnimationTransition', module='kivy.animation') r('ExceptionHandler', module='kivy.base') r('Cache', module='kivy.cache') r('ClockBase', module='kivy.clock') r('ColorPicker', module='kivy.uix.colorpicker') r('ColorWheel', module='kivy.uix.colorpicker') r('ConfigParser', module='kivy.config') r('EventDispatcher', module='kivy.event') r('Observable', module='kivy.event') r('FactoryException', module='kivy.factory') r('Gesture', module='kivy.gesture') r('GestureDatabase', module='kivy.gesture') r('GesturePoint', module='kivy.gesture') r('GestureStroke', module='kivy.gesture') r('Parser', module='kivy.lang.parser') r('LoaderBase', module='kivy.loader') r('ProxyImage', module='kivy.loader') r('LoggerHistory', module='kivy.logger') r('NumericProperty', module='kivy.properties') r('StringProperty', module='kivy.properties') r('ListProperty', module='kivy.properties') r('ObjectProperty', module='kivy.properties') r('BooleanProperty', module='kivy.properties') r('BoundedNumericProperty', module='kivy.properties') r('OptionProperty', module='kivy.properties') r('ReferenceListProperty', module='kivy.properties') r('AliasProperty', module='kivy.properties') r('NumericProperty', module='kivy.properties') r('DictProperty', module='kivy.properties') r('VariableListProperty', module='kivy.properties') r('ConfigParserProperty', module='kivy.properties') r('Property', module='kivy.properties') r('SafeList', module='kivy.utils') r('Vector', module='kivy.vector') r('Color', module='kivy.graphics.context_instructions') r('BindTexture', module='kivy.graphics.context_instructions') r('PushMatrix', module='kivy.graphics.context_instructions') r('PopMatrix', module='kivy.graphics.context_instructions') r('Rotate', module='kivy.graphics.context_instructions') r('Scale', module='kivy.graphics.context_instructions') r('Translate', module='kivy.graphics.context_instructions') r('MatrixInstruction', module='kivy.graphics.context_instructions') r('Fbo', module='kivy.graphics.fbo') r('Instruction', module='kivy.graphics.instructions') r('InstructionGroup', module='kivy.graphics.instructions') r('ContextInstruction', module='kivy.graphics.instructions') r('VertexInstruction', module='kivy.graphics.instructions') r('Canvas', module='kivy.graphics.instructions') r('CanvasBase', module='kivy.graphics.instructions') r('RenderContext', module='kivy.graphics.instructions') r('Shader', module='kivy.graphics.shader') r('Texture', module='kivy.graphics.texture') r('TextureRegion', module='kivy.graphics.texture') r('Matrix', module='kivy.graphics.transformation') r('VBO', module='kivy.graphics.vbo') r('VertexBatch', module='kivy.graphics.vbo') r('StencilPush', module='kivy.graphics.stencil_instructions') r('StencilPop', module='kivy.graphics.stencil_instructions') r('StencilUse', module='kivy.graphics.stencil_instructions') r('StencilUnUse', module='kivy.graphics.stencil_instructions') r('ScissorPush', module='kivy.graphics.scissor_instructions') r('ScissorPop', module='kivy.graphics.scissor_instructions') r('Triangle', module='kivy.graphics.vertex_instructions') r('Quad', module='kivy.graphics.vertex_instructions') r('Rectangle', module='kivy.graphics.vertex_instructions') r('RoundedRectangle', module='kivy.graphics.vertex_instructions') r('BorderImage', module='kivy.graphics.vertex_instructions') r('Ellipse', module='kivy.graphics.vertex_instructions') r('Line', module='kivy.graphics.vertex_instructions') r('SmoothLine', module='kivy.graphics.vertex_instructions') r('Point', module='kivy.graphics.vertex_instructions') r('Bezier', module='kivy.graphics.vertex_instructions') r('Mesh', module='kivy.graphics.vertex_instructions') r('Svg', module='kivy.graphics.svg') r('MotionEventFactory', module='kivy.input.factory') r('MotionEventProvider', module='kivy.input.provider') r('Shape', module='kivy.input.shape') r('ShapeRect', module='kivy.input.shape') r('ActionBar', module='kivy.uix.actionbar') r('ActionItem', module='kivy.uix.actionbar') r('ActionButton', module='kivy.uix.actionbar') r('ActionToggleButton', module='kivy.uix.actionbar') r('ActionCheck', module='kivy.uix.actionbar') r('ActionSeparator', module='kivy.uix.actionbar') r('ActionDropDown', module='kivy.uix.actionbar') r('ActionGroup', module='kivy.uix.actionbar') r('ActionOverflow', module='kivy.uix.actionbar') r('ActionView', module='kivy.uix.actionbar') r('ContextualActionView', module='kivy.uix.actionbar') r('AnchorLayout', module='kivy.uix.anchorlayout') r('BoxLayout', module='kivy.uix.boxlayout') r('GridLayout', module='kivy.uix.gridlayout') r('PageLayout', module='kivy.uix.pagelayout') r('Accordion', module='kivy.uix.accordion') r('AccordionItem', module='kivy.uix.accordion') r('Button', module='kivy.uix.button') r('ButtonBehavior', module='kivy.uix.behaviors.button') r('ToggleButtonBehavior', module='kivy.uix.behaviors.togglebutton') r('DragBehavior', module='kivy.uix.behaviors.drag') r('FocusBehavior', module='kivy.uix.behaviors.focus') r('CompoundSelectionBehavior', module='kivy.uix.behaviors.compoundselection') r('KNSpaceBehavior', module='kivy.uix.behaviors.knspace') r('CodeNavigationBehavior', module='kivy.uix.behaviors.codenavigation') r('EmacsBehavior', module='kivy.uix.behaviors.emacs') r('CoverBehavior', module='kivy.uix.behaviors.cover') r('Bubble', module='kivy.uix.bubble') r('BubbleButton', module='kivy.uix.bubble') r('Camera', module='kivy.uix.camera') r('Carousel', module='kivy.uix.carousel') r('CodeInput', module='kivy.uix.codeinput') r('CheckBox', module='kivy.uix.checkbox') r('DropDown', module='kivy.uix.dropdown') r('EffectWidget', module='kivy.uix.effectwidget') r('FloatLayout', module='kivy.uix.floatlayout') r('RelativeLayout', module='kivy.uix.relativelayout') r('ScatterLayout', module='kivy.uix.scatterlayout') r('ScatterPlaneLayout', module='kivy.uix.scatterlayout') r('FileChooserListView', module='kivy.uix.filechooser') r('FileChooserIconView', module='kivy.uix.filechooser') r('FileChooser', module='kivy.uix.filechooser') r('Image', module='kivy.uix.image') r('AsyncImage', module='kivy.uix.image') r('Label', module='kivy.uix.label') r('Layout', module='kivy.uix.layout') r('AbstractView', module='kivy.uix.abstractview') r('CompositeListItem', module='kivy.uix.listview') r('ListItemButton', module='kivy.uix.listview') r('ListItemLabel', module='kivy.uix.listview') r('ListView', module='kivy.uix.listview') r('SelectableView', module='kivy.uix.selectableview') r('ModalView', module='kivy.uix.modalview') r('ProgressBar', module='kivy.uix.progressbar') r('Popup', module='kivy.uix.popup') r('Scatter', module='kivy.uix.scatter') r('ScatterPlane', module='kivy.uix.scatter') r('ScrollView', module='kivy.uix.scrollview') r('Settings', module='kivy.uix.settings') r('Slider', module='kivy.uix.slider') r('Screen', module='kivy.uix.screenmanager') r('ScreenManager', module='kivy.uix.screenmanager') r('Spinner', module='kivy.uix.spinner') r('Splitter', module='kivy.uix.splitter') r('StackLayout', module='kivy.uix.stacklayout') r('StencilView', module='kivy.uix.stencilview') r('Switch', module='kivy.uix.switch') r('TabbedPanel', module='kivy.uix.tabbedpanel') r('TabbedPanelHeader', module='kivy.uix.tabbedpanel') r('TextInput', module='kivy.uix.textinput') r('ToggleButton', module='kivy.uix.togglebutton') r('TreeView', module='kivy.uix.treeview') r('TreeViewLabel', module='kivy.uix.treeview') r('TreeViewNode', module='kivy.uix.treeview') r('ShaderTransition', module='kivy.uix.screenmanager') r('SlideTransition', module='kivy.uix.screenmanager') r('SwapTransition', module='kivy.uix.screenmanager') r('WipeTransition', module='kivy.uix.screenmanager') r('FadeTransition', module='kivy.uix.screenmanager') r('Sandbox', module='kivy.uix.sandbox') r('Video', module='kivy.uix.video') r('VideoPlayer', module='kivy.uix.videoplayer') r('VideoPlayerVolume', module='kivy.uix.videoplayer') r('VideoPlayerStop', module='kivy.uix.videoplayer') r('VideoPlayerPlayPause', module='kivy.uix.videoplayer') r('VideoPlayerProgressBar', module='kivy.uix.videoplayer') r('VKeyboard', module='kivy.uix.vkeyboard') r('Widget', module='kivy.uix.widget') r('WidgetException', module='kivy.uix.widget') r('RstDocument', module='kivy.uix.rst') r('KineticEffect', module='kivy.effects.kinetic') r('ScrollEffect', module='kivy.effects.scroll') r('DampedScrollEffect', module='kivy.effects.dampedscroll') r('OpacityScrollEffect', module='kivy.effects.opacityscroll') r('Recognizer', module='kivy.multistroke') r('MultistrokeGesture', module='kivy.multistroke') r('UnistrokeTemplate', module='kivy.multistroke') r('ProgressTracker', module='kivy.multistroke') r('GestureSurface', module='kivy.uix.gesturesurface') r('GestureContainer', module='kivy.uix.gesturesurface') r('RecycleViewBehavior', module='kivy.uix.recycleview.__init__') r('RecycleView', module='kivy.uix.recycleview.__init__') r('LayoutSelectionBehavior', module='kivy.uix.recycleview.layout') r('RecycleLayoutManagerBehavior', module='kivy.uix.recycleview.layout') r('RecycleDataViewBehavior', module='kivy.uix.recycleview.views') r('RecycleDataAdapter', module='kivy.uix.recycleview.views') r('RecycleDataModelBehavior', module='kivy.uix.recycleview.datamodel') r('RecycleDataModel', module='kivy.uix.recycleview.datamodel') r('RecycleLayout', module='kivy.uix.recyclelayout') r('RecycleGridLayout', module='kivy.uix.recyclegridlayout') r('RecycleBoxLayout', module='kivy.uix.recycleboxlayout')
MyAOSP/kernel_htc_msm8960
refs/heads/jb-4.2
scripts/gcc-wrapper.py
473
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2011-2012, The Linux Foundation. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of The Linux Foundation 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, FITNESS FOR A PARTICULAR PURPOSE AND # NON-INFRINGEMENT 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. # Invoke gcc, looking for warnings, and causing a failure if there are # non-whitelisted warnings. import errno import re import os import sys import subprocess # Note that gcc uses unicode, which may depend on the locale. TODO: # force LANG to be set to en_US.UTF-8 to get consistent warnings. allowed_warnings = set([ "alignment.c:327", "mmu.c:602", "return_address.c:62", ]) # Capture the name of the object file, can find it. ofile = None warning_re = re.compile(r'''(.*/|)([^/]+\.[a-z]+:\d+):(\d+:)? warning:''') def interpret_warning(line): """Decode the message from gcc. The messages we care about have a filename, and a warning""" line = line.rstrip('\n') m = warning_re.match(line) if m and m.group(2) not in allowed_warnings: print "error, forbidden warning:", m.group(2) # If there is a warning, remove any object if it exists. if ofile: try: os.remove(ofile) except OSError: pass sys.exit(1) def run_gcc(): args = sys.argv[1:] # Look for -o try: i = args.index('-o') global ofile ofile = args[i+1] except (ValueError, IndexError): pass compiler = sys.argv[0] try: proc = subprocess.Popen(args, stderr=subprocess.PIPE) for line in proc.stderr: print line, interpret_warning(line) result = proc.wait() except OSError as e: result = e.errno if result == errno.ENOENT: print args[0] + ':',e.strerror print 'Is your PATH set correctly?' else: print ' '.join(args), str(e) return result if __name__ == '__main__': status = run_gcc() sys.exit(status)
AsimmHirani/ISpyPi
refs/heads/master
tensorflow/contrib/tensorflow-master/tensorflow/python/ops/cloud/bigquery_reader_ops_test.py
12
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for BigQueryReader Op.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import os import re import threading from six.moves import SimpleHTTPServer from six.moves import socketserver from tensorflow.core.example import example_pb2 from tensorflow.core.framework import types_pb2 from tensorflow.python.framework import dtypes from tensorflow.python.ops import array_ops from tensorflow.python.ops import data_flow_ops from tensorflow.python.ops import parsing_ops from tensorflow.python.ops.cloud import cloud from tensorflow.python.platform import test from tensorflow.python.platform import tf_logging as logging from tensorflow.python.util import compat _PROJECT = "test-project" _DATASET = "test-dataset" _TABLE = "test-table" # List representation of the test rows in the 'test-table' in BigQuery. # The schema for each row is: [int64, string, float]. # The values for rows are generated such that some columns have null values. The # general formula here is: # - The int64 column is present in every row. # - The string column is only avaiable in even rows. # - The float column is only available in every third row. _ROWS = [[0, "s_0", 0.1], [1, None, None], [2, "s_2", None], [3, None, 3.1], [4, "s_4", None], [5, None, None], [6, "s_6", 6.1], [7, None, None], [8, "s_8", None], [9, None, 9.1]] # Schema for 'test-table'. # The schema currently has three columns: int64, string, and float _SCHEMA = { "kind": "bigquery#table", "id": "test-project:test-dataset.test-table", "schema": { "fields": [{ "name": "int64_col", "type": "INTEGER", "mode": "NULLABLE" }, { "name": "string_col", "type": "STRING", "mode": "NULLABLE" }, { "name": "float_col", "type": "FLOAT", "mode": "NULLABLE" }] } } def _ConvertRowToExampleProto(row): """Converts the input row to an Example proto. Args: row: Input Row instance. Returns: An Example proto initialized with row values. """ example = example_pb2.Example() example.features.feature["int64_col"].int64_list.value.append(row[0]) if row[1] is not None: example.features.feature["string_col"].bytes_list.value.append( compat.as_bytes(row[1])) if row[2] is not None: example.features.feature["float_col"].float_list.value.append(row[2]) return example class FakeBigQueryServer(threading.Thread): """Fake http server to return schema and data for sample table.""" def __init__(self, address, port): """Creates a FakeBigQueryServer. Args: address: Server address port: Server port. Pass 0 to automatically pick an empty port. """ threading.Thread.__init__(self) self.handler = BigQueryRequestHandler self.httpd = socketserver.TCPServer((address, port), self.handler) def run(self): self.httpd.serve_forever() def shutdown(self): self.httpd.shutdown() self.httpd.socket.close() class BigQueryRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): """Responds to BigQuery HTTP requests. Attributes: num_rows: num_rows in the underlying table served by this class. """ num_rows = 0 def do_GET(self): if "data?maxResults=" not in self.path: # This is a schema request. _SCHEMA["numRows"] = self.num_rows response = json.dumps(_SCHEMA) else: # This is a data request. # # Extract max results and start index. max_results = int(re.findall(r"maxResults=(\d+)", self.path)[0]) start_index = int(re.findall(r"startIndex=(\d+)", self.path)[0]) # Send the rows as JSON. rows = [] for row in _ROWS[start_index:start_index + max_results]: row_json = { "f": [{ "v": str(row[0]) }, { "v": str(row[1]) if row[1] is not None else None }, { "v": str(row[2]) if row[2] is not None else None }] } rows.append(row_json) response = json.dumps({ "kind": "bigquery#table", "id": "test-project:test-dataset.test-table", "rows": rows }) self.send_response(200) self.end_headers() self.wfile.write(compat.as_bytes(response)) def _SetUpQueue(reader): """Sets up a queue for a reader.""" queue = data_flow_ops.FIFOQueue(8, [types_pb2.DT_STRING], shapes=()) key, value = reader.read(queue) queue.enqueue_many(reader.partitions()).run() queue.close().run() return key, value class BigQueryReaderOpsTest(test.TestCase): def setUp(self): super(BigQueryReaderOpsTest, self).setUp() self.server = FakeBigQueryServer("127.0.0.1", 0) self.server.start() logging.info("server address is %s:%s", self.server.httpd.server_address[0], self.server.httpd.server_address[1]) # An override to bypass the GCP auth token retrieval logic # in google_auth_provider.cc. os.environ["GOOGLE_AUTH_TOKEN_FOR_TESTING"] = "not-used" def tearDown(self): self.server.shutdown() super(BigQueryReaderOpsTest, self).tearDown() def _ReadAndCheckRowsUsingFeatures(self, num_rows): self.server.handler.num_rows = num_rows with self.test_session() as sess: feature_configs = { "int64_col": parsing_ops.FixedLenFeature( [1], dtype=dtypes.int64), "string_col": parsing_ops.FixedLenFeature( [1], dtype=dtypes.string, default_value="s_default"), } reader = cloud.BigQueryReader( project_id=_PROJECT, dataset_id=_DATASET, table_id=_TABLE, num_partitions=4, features=feature_configs, timestamp_millis=1, test_end_point=("%s:%s" % (self.server.httpd.server_address[0], self.server.httpd.server_address[1]))) key, value = _SetUpQueue(reader) seen_rows = [] features = parsing_ops.parse_example( array_ops.reshape(value, [1]), feature_configs) for _ in range(num_rows): int_value, str_value = sess.run( [features["int64_col"], features["string_col"]]) # Parse values returned from the session. self.assertEqual(int_value.shape, (1, 1)) self.assertEqual(str_value.shape, (1, 1)) int64_col = int_value[0][0] string_col = str_value[0][0] seen_rows.append(int64_col) # Compare. expected_row = _ROWS[int64_col] self.assertEqual(int64_col, expected_row[0]) self.assertEqual( compat.as_str(string_col), ("s_%d" % int64_col) if expected_row[1] else "s_default") self.assertItemsEqual(seen_rows, range(num_rows)) with self.assertRaisesOpError("is closed and has insufficient elements " "\\(requested 1, current size 0\\)"): sess.run([key, value]) def testReadingSingleRowUsingFeatures(self): self._ReadAndCheckRowsUsingFeatures(1) def testReadingMultipleRowsUsingFeatures(self): self._ReadAndCheckRowsUsingFeatures(10) def testReadingMultipleRowsUsingColumns(self): num_rows = 10 self.server.handler.num_rows = num_rows with self.test_session() as sess: reader = cloud.BigQueryReader( project_id=_PROJECT, dataset_id=_DATASET, table_id=_TABLE, num_partitions=4, columns=["int64_col", "float_col", "string_col"], timestamp_millis=1, test_end_point=("%s:%s" % (self.server.httpd.server_address[0], self.server.httpd.server_address[1]))) key, value = _SetUpQueue(reader) seen_rows = [] for row_index in range(num_rows): returned_row_id, example_proto = sess.run([key, value]) example = example_pb2.Example() example.ParseFromString(example_proto) self.assertIn("int64_col", example.features.feature) feature = example.features.feature["int64_col"] self.assertEqual(len(feature.int64_list.value), 1) int64_col = feature.int64_list.value[0] seen_rows.append(int64_col) # Create our expected Example. expected_example = example_pb2.Example() expected_example = _ConvertRowToExampleProto(_ROWS[int64_col]) # Compare. self.assertProtoEquals(example, expected_example) self.assertEqual(row_index, int(returned_row_id)) self.assertItemsEqual(seen_rows, range(num_rows)) with self.assertRaisesOpError("is closed and has insufficient elements " "\\(requested 1, current size 0\\)"): sess.run([key, value]) if __name__ == "__main__": test.main()
onestarshang/flask_super_config
refs/heads/master
venv/lib/python2.7/site-packages/werkzeug/wsgi.py
147
# -*- coding: utf-8 -*- """ werkzeug.wsgi ~~~~~~~~~~~~~ This module implements WSGI related helpers. :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import re import os import sys import posixpath import mimetypes from itertools import chain from zlib import adler32 from time import time, mktime from datetime import datetime from functools import partial, update_wrapper from werkzeug._compat import iteritems, text_type, string_types, \ implements_iterator, make_literal_wrapper, to_unicode, to_bytes, \ wsgi_get_bytes, try_coerce_native, PY2 from werkzeug._internal import _empty_stream, _encode_idna from werkzeug.http import is_resource_modified, http_date from werkzeug.urls import uri_to_iri, url_quote, url_parse, url_join def responder(f): """Marks a function as responder. Decorate a function with it and it will automatically call the return value as WSGI application. Example:: @responder def application(environ, start_response): return Response('Hello World!') """ return update_wrapper(lambda *a: f(*a)(*a[-2:]), f) def get_current_url(environ, root_only=False, strip_querystring=False, host_only=False, trusted_hosts=None): """A handy helper function that recreates the full URL as IRI for the current request or parts of it. Here an example: >>> from werkzeug.test import create_environ >>> env = create_environ("/?param=foo", "http://localhost/script") >>> get_current_url(env) 'http://localhost/script/?param=foo' >>> get_current_url(env, root_only=True) 'http://localhost/script/' >>> get_current_url(env, host_only=True) 'http://localhost/' >>> get_current_url(env, strip_querystring=True) 'http://localhost/script/' This optionally it verifies that the host is in a list of trusted hosts. If the host is not in there it will raise a :exc:`~werkzeug.exceptions.SecurityError`. Note that the string returned might contain unicode characters as the representation is an IRI not an URI. If you need an ASCII only representation you can use the :func:`~werkzeug.urls.iri_to_uri` function: >>> from werkzeug.urls import iri_to_uri >>> iri_to_uri(get_current_url(env)) 'http://localhost/script/?param=foo' :param environ: the WSGI environment to get the current URL from. :param root_only: set `True` if you only want the root URL. :param strip_querystring: set to `True` if you don't want the querystring. :param host_only: set to `True` if the host URL should be returned. :param trusted_hosts: a list of trusted hosts, see :func:`host_is_trusted` for more information. """ tmp = [environ['wsgi.url_scheme'], '://', get_host(environ, trusted_hosts)] cat = tmp.append if host_only: return uri_to_iri(''.join(tmp) + '/') cat(url_quote(wsgi_get_bytes(environ.get('SCRIPT_NAME', ''))).rstrip('/')) cat('/') if not root_only: cat(url_quote(wsgi_get_bytes(environ.get('PATH_INFO', '')).lstrip(b'/'))) if not strip_querystring: qs = get_query_string(environ) if qs: cat('?' + qs) return uri_to_iri(''.join(tmp)) def host_is_trusted(hostname, trusted_list): """Checks if a host is trusted against a list. This also takes care of port normalization. .. versionadded:: 0.9 :param hostname: the hostname to check :param trusted_list: a list of hostnames to check against. If a hostname starts with a dot it will match against all subdomains as well. """ if not hostname: return False if isinstance(trusted_list, string_types): trusted_list = [trusted_list] def _normalize(hostname): if ':' in hostname: hostname = hostname.rsplit(':', 1)[0] return _encode_idna(hostname) hostname = _normalize(hostname) for ref in trusted_list: if ref.startswith('.'): ref = ref[1:] suffix_match = True else: suffix_match = False ref = _normalize(ref) if ref == hostname: return True if suffix_match and hostname.endswith('.' + ref): return True return False def get_host(environ, trusted_hosts=None): """Return the real host for the given WSGI environment. This first checks the `X-Forwarded-Host` header, then the normal `Host` header, and finally the `SERVER_NAME` environment variable (using the first one it finds). Optionally it verifies that the host is in a list of trusted hosts. If the host is not in there it will raise a :exc:`~werkzeug.exceptions.SecurityError`. :param environ: the WSGI environment to get the host of. :param trusted_hosts: a list of trusted hosts, see :func:`host_is_trusted` for more information. """ if 'HTTP_X_FORWARDED_HOST' in environ: rv = environ['HTTP_X_FORWARDED_HOST'].split(',', 1)[0].strip() elif 'HTTP_HOST' in environ: rv = environ['HTTP_HOST'] else: rv = environ['SERVER_NAME'] if (environ['wsgi.url_scheme'], environ['SERVER_PORT']) not \ in (('https', '443'), ('http', '80')): rv += ':' + environ['SERVER_PORT'] if trusted_hosts is not None: if not host_is_trusted(rv, trusted_hosts): from werkzeug.exceptions import SecurityError raise SecurityError('Host "%s" is not trusted' % rv) return rv def get_content_length(environ): """Returns the content length from the WSGI environment as integer. If it's not available `None` is returned. .. versionadded:: 0.9 :param environ: the WSGI environ to fetch the content length from. """ content_length = environ.get('CONTENT_LENGTH') if content_length is not None: try: return max(0, int(content_length)) except (ValueError, TypeError): pass def get_input_stream(environ, safe_fallback=True): """Returns the input stream from the WSGI environment and wraps it in the most sensible way possible. The stream returned is not the raw WSGI stream in most cases but one that is safe to read from without taking into account the content length. .. versionadded:: 0.9 :param environ: the WSGI environ to fetch the stream from. :param safe: indicates weather the function should use an empty stream as safe fallback or just return the original WSGI input stream if it can't wrap it safely. The default is to return an empty string in those cases. """ stream = environ['wsgi.input'] content_length = get_content_length(environ) # A wsgi extension that tells us if the input is terminated. In # that case we return the stream unchanged as we know we can savely # read it until the end. if environ.get('wsgi.input_terminated'): return stream # If we don't have a content length we fall back to an empty stream # in case of a safe fallback, otherwise we return the stream unchanged. # The non-safe fallback is not recommended but might be useful in # some situations. if content_length is None: return safe_fallback and _empty_stream or stream # Otherwise limit the stream to the content length return LimitedStream(stream, content_length) def get_query_string(environ): """Returns the `QUERY_STRING` from the WSGI environment. This also takes care about the WSGI decoding dance on Python 3 environments as a native string. The string returned will be restricted to ASCII characters. .. versionadded:: 0.9 :param environ: the WSGI environment object to get the query string from. """ qs = wsgi_get_bytes(environ.get('QUERY_STRING', '')) # QUERY_STRING really should be ascii safe but some browsers # will send us some unicode stuff (I am looking at you IE). # In that case we want to urllib quote it badly. return try_coerce_native(url_quote(qs, safe=':&%=+$!*\'(),')) def get_path_info(environ, charset='utf-8', errors='replace'): """Returns the `PATH_INFO` from the WSGI environment and properly decodes it. This also takes care about the WSGI decoding dance on Python 3 environments. if the `charset` is set to `None` a bytestring is returned. .. versionadded:: 0.9 :param environ: the WSGI environment object to get the path from. :param charset: the charset for the path info, or `None` if no decoding should be performed. :param errors: the decoding error handling. """ path = wsgi_get_bytes(environ.get('PATH_INFO', '')) return to_unicode(path, charset, errors, allow_none_charset=True) def get_script_name(environ, charset='utf-8', errors='replace'): """Returns the `SCRIPT_NAME` from the WSGI environment and properly decodes it. This also takes care about the WSGI decoding dance on Python 3 environments. if the `charset` is set to `None` a bytestring is returned. .. versionadded:: 0.9 :param environ: the WSGI environment object to get the path from. :param charset: the charset for the path, or `None` if no decoding should be performed. :param errors: the decoding error handling. """ path = wsgi_get_bytes(environ.get('SCRIPT_NAME', '')) return to_unicode(path, charset, errors, allow_none_charset=True) def pop_path_info(environ, charset='utf-8', errors='replace'): """Removes and returns the next segment of `PATH_INFO`, pushing it onto `SCRIPT_NAME`. Returns `None` if there is nothing left on `PATH_INFO`. If the `charset` is set to `None` a bytestring is returned. If there are empty segments (``'/foo//bar``) these are ignored but properly pushed to the `SCRIPT_NAME`: >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'} >>> pop_path_info(env) 'a' >>> env['SCRIPT_NAME'] '/foo/a' >>> pop_path_info(env) 'b' >>> env['SCRIPT_NAME'] '/foo/a/b' .. versionadded:: 0.5 .. versionchanged:: 0.9 The path is now decoded and a charset and encoding parameter can be provided. :param environ: the WSGI environment that is modified. """ path = environ.get('PATH_INFO') if not path: return None script_name = environ.get('SCRIPT_NAME', '') # shift multiple leading slashes over old_path = path path = path.lstrip('/') if path != old_path: script_name += '/' * (len(old_path) - len(path)) if '/' not in path: environ['PATH_INFO'] = '' environ['SCRIPT_NAME'] = script_name + path rv = wsgi_get_bytes(path) else: segment, path = path.split('/', 1) environ['PATH_INFO'] = '/' + path environ['SCRIPT_NAME'] = script_name + segment rv = wsgi_get_bytes(segment) return to_unicode(rv, charset, errors, allow_none_charset=True) def peek_path_info(environ, charset='utf-8', errors='replace'): """Returns the next segment on the `PATH_INFO` or `None` if there is none. Works like :func:`pop_path_info` without modifying the environment: >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'} >>> peek_path_info(env) 'a' >>> peek_path_info(env) 'a' If the `charset` is set to `None` a bytestring is returned. .. versionadded:: 0.5 .. versionchanged:: 0.9 The path is now decoded and a charset and encoding parameter can be provided. :param environ: the WSGI environment that is checked. """ segments = environ.get('PATH_INFO', '').lstrip('/').split('/', 1) if segments: return to_unicode(wsgi_get_bytes(segments[0]), charset, errors, allow_none_charset=True) def extract_path_info(environ_or_baseurl, path_or_url, charset='utf-8', errors='replace', collapse_http_schemes=True): """Extracts the path info from the given URL (or WSGI environment) and path. The path info returned is a unicode string, not a bytestring suitable for a WSGI environment. The URLs might also be IRIs. If the path info could not be determined, `None` is returned. Some examples: >>> extract_path_info('http://example.com/app', '/app/hello') u'/hello' >>> extract_path_info('http://example.com/app', ... 'https://example.com/app/hello') u'/hello' >>> extract_path_info('http://example.com/app', ... 'https://example.com/app/hello', ... collapse_http_schemes=False) is None True Instead of providing a base URL you can also pass a WSGI environment. .. versionadded:: 0.6 :param environ_or_baseurl: a WSGI environment dict, a base URL or base IRI. This is the root of the application. :param path_or_url: an absolute path from the server root, a relative path (in which case it's the path info) or a full URL. Also accepts IRIs and unicode parameters. :param charset: the charset for byte data in URLs :param errors: the error handling on decode :param collapse_http_schemes: if set to `False` the algorithm does not assume that http and https on the same server point to the same resource. """ def _normalize_netloc(scheme, netloc): parts = netloc.split(u'@', 1)[-1].split(u':', 1) if len(parts) == 2: netloc, port = parts if (scheme == u'http' and port == u'80') or \ (scheme == u'https' and port == u'443'): port = None else: netloc = parts[0] port = None if port is not None: netloc += u':' + port return netloc # make sure whatever we are working on is a IRI and parse it path = uri_to_iri(path_or_url, charset, errors) if isinstance(environ_or_baseurl, dict): environ_or_baseurl = get_current_url(environ_or_baseurl, root_only=True) base_iri = uri_to_iri(environ_or_baseurl, charset, errors) base_scheme, base_netloc, base_path = url_parse(base_iri)[:3] cur_scheme, cur_netloc, cur_path, = \ url_parse(url_join(base_iri, path))[:3] # normalize the network location base_netloc = _normalize_netloc(base_scheme, base_netloc) cur_netloc = _normalize_netloc(cur_scheme, cur_netloc) # is that IRI even on a known HTTP scheme? if collapse_http_schemes: for scheme in base_scheme, cur_scheme: if scheme not in (u'http', u'https'): return None else: if not (base_scheme in (u'http', u'https') and base_scheme == cur_scheme): return None # are the netlocs compatible? if base_netloc != cur_netloc: return None # are we below the application path? base_path = base_path.rstrip(u'/') if not cur_path.startswith(base_path): return None return u'/' + cur_path[len(base_path):].lstrip(u'/') class SharedDataMiddleware(object): """A WSGI middleware that provides static content for development environments or simple server setups. Usage is quite simple:: import os from werkzeug.wsgi import SharedDataMiddleware app = SharedDataMiddleware(app, { '/shared': os.path.join(os.path.dirname(__file__), 'shared') }) The contents of the folder ``./shared`` will now be available on ``http://example.com/shared/``. This is pretty useful during development because a standalone media server is not required. One can also mount files on the root folder and still continue to use the application because the shared data middleware forwards all unhandled requests to the application, even if the requests are below one of the shared folders. If `pkg_resources` is available you can also tell the middleware to serve files from package data:: app = SharedDataMiddleware(app, { '/shared': ('myapplication', 'shared_files') }) This will then serve the ``shared_files`` folder in the `myapplication` Python package. The optional `disallow` parameter can be a list of :func:`~fnmatch.fnmatch` rules for files that are not accessible from the web. If `cache` is set to `False` no caching headers are sent. Currently the middleware does not support non ASCII filenames. If the encoding on the file system happens to be the encoding of the URI it may work but this could also be by accident. We strongly suggest using ASCII only file names for static files. The middleware will guess the mimetype using the Python `mimetype` module. If it's unable to figure out the charset it will fall back to `fallback_mimetype`. .. versionchanged:: 0.5 The cache timeout is configurable now. .. versionadded:: 0.6 The `fallback_mimetype` parameter was added. :param app: the application to wrap. If you don't want to wrap an application you can pass it :exc:`NotFound`. :param exports: a dict of exported files and folders. :param disallow: a list of :func:`~fnmatch.fnmatch` rules. :param fallback_mimetype: the fallback mimetype for unknown files. :param cache: enable or disable caching headers. :param cache_timeout: the cache timeout in seconds for the headers. """ def __init__(self, app, exports, disallow=None, cache=True, cache_timeout=60 * 60 * 12, fallback_mimetype='text/plain'): self.app = app self.exports = {} self.cache = cache self.cache_timeout = cache_timeout for key, value in iteritems(exports): if isinstance(value, tuple): loader = self.get_package_loader(*value) elif isinstance(value, string_types): if os.path.isfile(value): loader = self.get_file_loader(value) else: loader = self.get_directory_loader(value) else: raise TypeError('unknown def %r' % value) self.exports[key] = loader if disallow is not None: from fnmatch import fnmatch self.is_allowed = lambda x: not fnmatch(x, disallow) self.fallback_mimetype = fallback_mimetype def is_allowed(self, filename): """Subclasses can override this method to disallow the access to certain files. However by providing `disallow` in the constructor this method is overwritten. """ return True def _opener(self, filename): return lambda: ( open(filename, 'rb'), datetime.utcfromtimestamp(os.path.getmtime(filename)), int(os.path.getsize(filename)) ) def get_file_loader(self, filename): return lambda x: (os.path.basename(filename), self._opener(filename)) def get_package_loader(self, package, package_path): from pkg_resources import DefaultProvider, ResourceManager, \ get_provider loadtime = datetime.utcnow() provider = get_provider(package) manager = ResourceManager() filesystem_bound = isinstance(provider, DefaultProvider) def loader(path): if path is None: return None, None path = posixpath.join(package_path, path) if not provider.has_resource(path): return None, None basename = posixpath.basename(path) if filesystem_bound: return basename, self._opener( provider.get_resource_filename(manager, path)) return basename, lambda: ( provider.get_resource_stream(manager, path), loadtime, 0 ) return loader def get_directory_loader(self, directory): def loader(path): if path is not None: path = os.path.join(directory, path) else: path = directory if os.path.isfile(path): return os.path.basename(path), self._opener(path) return None, None return loader def generate_etag(self, mtime, file_size, real_filename): if not isinstance(real_filename, bytes): real_filename = real_filename.encode(sys.getfilesystemencoding()) return 'wzsdm-%d-%s-%s' % ( mktime(mtime.timetuple()), file_size, adler32(real_filename) & 0xffffffff ) def __call__(self, environ, start_response): cleaned_path = get_path_info(environ) if PY2: cleaned_path = cleaned_path.encode(sys.getfilesystemencoding()) # sanitize the path for non unix systems cleaned_path = cleaned_path.strip('/') for sep in os.sep, os.altsep: if sep and sep != '/': cleaned_path = cleaned_path.replace(sep, '/') path = '/' + '/'.join(x for x in cleaned_path.split('/') if x and x != '..') file_loader = None for search_path, loader in iteritems(self.exports): if search_path == path: real_filename, file_loader = loader(None) if file_loader is not None: break if not search_path.endswith('/'): search_path += '/' if path.startswith(search_path): real_filename, file_loader = loader(path[len(search_path):]) if file_loader is not None: break if file_loader is None or not self.is_allowed(real_filename): return self.app(environ, start_response) guessed_type = mimetypes.guess_type(real_filename) mime_type = guessed_type[0] or self.fallback_mimetype f, mtime, file_size = file_loader() headers = [('Date', http_date())] if self.cache: timeout = self.cache_timeout etag = self.generate_etag(mtime, file_size, real_filename) headers += [ ('Etag', '"%s"' % etag), ('Cache-Control', 'max-age=%d, public' % timeout) ] if not is_resource_modified(environ, etag, last_modified=mtime): f.close() start_response('304 Not Modified', headers) return [] headers.append(('Expires', http_date(time() + timeout))) else: headers.append(('Cache-Control', 'public')) headers.extend(( ('Content-Type', mime_type), ('Content-Length', str(file_size)), ('Last-Modified', http_date(mtime)) )) start_response('200 OK', headers) return wrap_file(environ, f) class DispatcherMiddleware(object): """Allows one to mount middlewares or applications in a WSGI application. This is useful if you want to combine multiple WSGI applications:: app = DispatcherMiddleware(app, { '/app2': app2, '/app3': app3 }) """ def __init__(self, app, mounts=None): self.app = app self.mounts = mounts or {} def __call__(self, environ, start_response): script = environ.get('PATH_INFO', '') path_info = '' while '/' in script: if script in self.mounts: app = self.mounts[script] break script, last_item = script.rsplit('/', 1) path_info = '/%s%s' % (last_item, path_info) else: app = self.mounts.get(script, self.app) original_script_name = environ.get('SCRIPT_NAME', '') environ['SCRIPT_NAME'] = original_script_name + script environ['PATH_INFO'] = path_info return app(environ, start_response) @implements_iterator class ClosingIterator(object): """The WSGI specification requires that all middlewares and gateways respect the `close` callback of an iterator. Because it is useful to add another close action to a returned iterator and adding a custom iterator is a boring task this class can be used for that:: return ClosingIterator(app(environ, start_response), [cleanup_session, cleanup_locals]) If there is just one close function it can be passed instead of the list. A closing iterator is not needed if the application uses response objects and finishes the processing if the response is started:: try: return response(environ, start_response) finally: cleanup_session() cleanup_locals() """ def __init__(self, iterable, callbacks=None): iterator = iter(iterable) self._next = partial(next, iterator) if callbacks is None: callbacks = [] elif callable(callbacks): callbacks = [callbacks] else: callbacks = list(callbacks) iterable_close = getattr(iterator, 'close', None) if iterable_close: callbacks.insert(0, iterable_close) self._callbacks = callbacks def __iter__(self): return self def __next__(self): return self._next() def close(self): for callback in self._callbacks: callback() def wrap_file(environ, file, buffer_size=8192): """Wraps a file. This uses the WSGI server's file wrapper if available or otherwise the generic :class:`FileWrapper`. .. versionadded:: 0.5 If the file wrapper from the WSGI server is used it's important to not iterate over it from inside the application but to pass it through unchanged. If you want to pass out a file wrapper inside a response object you have to set :attr:`~BaseResponse.direct_passthrough` to `True`. More information about file wrappers are available in :pep:`333`. :param file: a :class:`file`-like object with a :meth:`~file.read` method. :param buffer_size: number of bytes for one iteration. """ return environ.get('wsgi.file_wrapper', FileWrapper)(file, buffer_size) @implements_iterator class FileWrapper(object): """This class can be used to convert a :class:`file`-like object into an iterable. It yields `buffer_size` blocks until the file is fully read. You should not use this class directly but rather use the :func:`wrap_file` function that uses the WSGI server's file wrapper support if it's available. .. versionadded:: 0.5 If you're using this object together with a :class:`BaseResponse` you have to use the `direct_passthrough` mode. :param file: a :class:`file`-like object with a :meth:`~file.read` method. :param buffer_size: number of bytes for one iteration. """ def __init__(self, file, buffer_size=8192): self.file = file self.buffer_size = buffer_size def close(self): if hasattr(self.file, 'close'): self.file.close() def __iter__(self): return self def __next__(self): data = self.file.read(self.buffer_size) if data: return data raise StopIteration() def _make_chunk_iter(stream, limit, buffer_size): """Helper for the line and chunk iter functions.""" if isinstance(stream, (bytes, bytearray, text_type)): raise TypeError('Passed a string or byte object instead of ' 'true iterator or stream.') if not hasattr(stream, 'read'): for item in stream: if item: yield item return if not isinstance(stream, LimitedStream) and limit is not None: stream = LimitedStream(stream, limit) _read = stream.read while 1: item = _read(buffer_size) if not item: break yield item def make_line_iter(stream, limit=None, buffer_size=10 * 1024): """Safely iterates line-based over an input stream. If the input stream is not a :class:`LimitedStream` the `limit` parameter is mandatory. This uses the stream's :meth:`~file.read` method internally as opposite to the :meth:`~file.readline` method that is unsafe and can only be used in violation of the WSGI specification. The same problem applies to the `__iter__` function of the input stream which calls :meth:`~file.readline` without arguments. If you need line-by-line processing it's strongly recommended to iterate over the input stream using this helper function. .. versionchanged:: 0.8 This function now ensures that the limit was reached. .. versionadded:: 0.9 added support for iterators as input stream. :param stream: the stream or iterate to iterate over. :param limit: the limit in bytes for the stream. (Usually content length. Not necessary if the `stream` is a :class:`LimitedStream`. :param buffer_size: The optional buffer size. """ _iter = _make_chunk_iter(stream, limit, buffer_size) first_item = next(_iter, '') if not first_item: return s = make_literal_wrapper(first_item) empty = s('') cr = s('\r') lf = s('\n') crlf = s('\r\n') _iter = chain((first_item,), _iter) def _iter_basic_lines(): _join = empty.join buffer = [] while 1: new_data = next(_iter, '') if not new_data: break new_buf = [] for item in chain(buffer, new_data.splitlines(True)): new_buf.append(item) if item and item[-1:] in crlf: yield _join(new_buf) new_buf = [] buffer = new_buf if buffer: yield _join(buffer) # This hackery is necessary to merge 'foo\r' and '\n' into one item # of 'foo\r\n' if we were unlucky and we hit a chunk boundary. previous = empty for item in _iter_basic_lines(): if item == lf and previous[-1:] == cr: previous += item item = empty if previous: yield previous previous = item if previous: yield previous def make_chunk_iter(stream, separator, limit=None, buffer_size=10 * 1024): """Works like :func:`make_line_iter` but accepts a separator which divides chunks. If you want newline based processing you should use :func:`make_line_iter` instead as it supports arbitrary newline markers. .. versionadded:: 0.8 .. versionadded:: 0.9 added support for iterators as input stream. :param stream: the stream or iterate to iterate over. :param separator: the separator that divides chunks. :param limit: the limit in bytes for the stream. (Usually content length. Not necessary if the `stream` is otherwise already limited). :param buffer_size: The optional buffer size. """ _iter = _make_chunk_iter(stream, limit, buffer_size) first_item = next(_iter, '') if not first_item: return _iter = chain((first_item,), _iter) if isinstance(first_item, text_type): separator = to_unicode(separator) _split = re.compile(r'(%s)' % re.escape(separator)).split _join = u''.join else: separator = to_bytes(separator) _split = re.compile(b'(' + re.escape(separator) + b')').split _join = b''.join buffer = [] while 1: new_data = next(_iter, '') if not new_data: break chunks = _split(new_data) new_buf = [] for item in chain(buffer, chunks): if item == separator: yield _join(new_buf) new_buf = [] else: new_buf.append(item) buffer = new_buf if buffer: yield _join(buffer) @implements_iterator class LimitedStream(object): """Wraps a stream so that it doesn't read more than n bytes. If the stream is exhausted and the caller tries to get more bytes from it :func:`on_exhausted` is called which by default returns an empty string. The return value of that function is forwarded to the reader function. So if it returns an empty string :meth:`read` will return an empty string as well. The limit however must never be higher than what the stream can output. Otherwise :meth:`readlines` will try to read past the limit. .. admonition:: Note on WSGI compliance calls to :meth:`readline` and :meth:`readlines` are not WSGI compliant because it passes a size argument to the readline methods. Unfortunately the WSGI PEP is not safely implementable without a size argument to :meth:`readline` because there is no EOF marker in the stream. As a result of that the use of :meth:`readline` is discouraged. For the same reason iterating over the :class:`LimitedStream` is not portable. It internally calls :meth:`readline`. We strongly suggest using :meth:`read` only or using the :func:`make_line_iter` which safely iterates line-based over a WSGI input stream. :param stream: the stream to wrap. :param limit: the limit for the stream, must not be longer than what the string can provide if the stream does not end with `EOF` (like `wsgi.input`) """ def __init__(self, stream, limit): self._read = stream.read self._readline = stream.readline self._pos = 0 self.limit = limit def __iter__(self): return self @property def is_exhausted(self): """If the stream is exhausted this attribute is `True`.""" return self._pos >= self.limit def on_exhausted(self): """This is called when the stream tries to read past the limit. The return value of this function is returned from the reading function. """ # Read null bytes from the stream so that we get the # correct end of stream marker. return self._read(0) def on_disconnect(self): """What should happen if a disconnect is detected? The return value of this function is returned from read functions in case the client went away. By default a :exc:`~werkzeug.exceptions.ClientDisconnected` exception is raised. """ from werkzeug.exceptions import ClientDisconnected raise ClientDisconnected() def exhaust(self, chunk_size=1024 * 64): """Exhaust the stream. This consumes all the data left until the limit is reached. :param chunk_size: the size for a chunk. It will read the chunk until the stream is exhausted and throw away the results. """ to_read = self.limit - self._pos chunk = chunk_size while to_read > 0: chunk = min(to_read, chunk) self.read(chunk) to_read -= chunk def read(self, size=None): """Read `size` bytes or if size is not provided everything is read. :param size: the number of bytes read. """ if self._pos >= self.limit: return self.on_exhausted() if size is None or size == -1: # -1 is for consistence with file size = self.limit to_read = min(self.limit - self._pos, size) try: read = self._read(to_read) except (IOError, ValueError): return self.on_disconnect() if to_read and len(read) != to_read: return self.on_disconnect() self._pos += len(read) return read def readline(self, size=None): """Reads one line from the stream.""" if self._pos >= self.limit: return self.on_exhausted() if size is None: size = self.limit - self._pos else: size = min(size, self.limit - self._pos) try: line = self._readline(size) except (ValueError, IOError): return self.on_disconnect() if size and not line: return self.on_disconnect() self._pos += len(line) return line def readlines(self, size=None): """Reads a file into a list of strings. It calls :meth:`readline` until the file is read to the end. It does support the optional `size` argument if the underlaying stream supports it for `readline`. """ last_pos = self._pos result = [] if size is not None: end = min(self.limit, last_pos + size) else: end = self.limit while 1: if size is not None: size -= last_pos - self._pos if self._pos >= end: break result.append(self.readline(size)) if size is not None: last_pos = self._pos return result def tell(self): """Returns the position of the stream. .. versionadded:: 0.9 """ return self._pos def __next__(self): line = self.readline() if not line: raise StopIteration() return line
freedesktop-unofficial-mirror/pycairo
refs/heads/master
examples/cairo_snippets/snippets/curve_to.py
15
x, y = 0.1, 0.5 x1, y1 = 0.4, 0.9 x2, y2 = 0.6, 0.1 x3, y3 = 0.9, 0.5 snippet_normalize (cr, width, height) cr.move_to (x, y) cr.curve_to (x1, y1, x2, y2, x3, y3) cr.stroke () cr.set_source_rgba (1,0.2,0.2,0.6) cr.set_line_width (0.03) cr.move_to (x,y); cr.line_to (x1,y1) cr.move_to (x2,y2); cr.line_to (x3,y3) cr.stroke ()
rspavel/spack
refs/heads/develop
var/spack/repos/builtin/packages/sph2pipe/package.py
5
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Sph2pipe(CMakePackage): """Sph2pipe is a portable tool for converting SPHERE files to other formats.""" homepage = "https://www.ldc.upenn.edu/language-resources/tools/sphere-conversion-tools" url = "https://www.ldc.upenn.edu/sites/www.ldc.upenn.edu/files/ctools/sph2pipe_v2.5.tar.gz" version('2.5', sha256='5be236dc94ed0a301c5c8a369f849f76799ec7e70f25dfc0521068d9d1d4d3e3') patch('cmake.patch')
nvoron23/scikit-learn
refs/heads/master
sklearn/metrics/tests/test_pairwise.py
71
import numpy as np from numpy import linalg from scipy.sparse import dok_matrix, csr_matrix, issparse from scipy.spatial.distance import cosine, cityblock, minkowski, wminkowski from sklearn.utils.testing import assert_greater from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_raises_regexp from sklearn.utils.testing import assert_true from sklearn.externals.six import iteritems from sklearn.metrics.pairwise import euclidean_distances from sklearn.metrics.pairwise import manhattan_distances from sklearn.metrics.pairwise import linear_kernel from sklearn.metrics.pairwise import chi2_kernel, additive_chi2_kernel from sklearn.metrics.pairwise import polynomial_kernel from sklearn.metrics.pairwise import rbf_kernel from sklearn.metrics.pairwise import sigmoid_kernel from sklearn.metrics.pairwise import cosine_similarity from sklearn.metrics.pairwise import cosine_distances from sklearn.metrics.pairwise import pairwise_distances from sklearn.metrics.pairwise import pairwise_distances_argmin_min from sklearn.metrics.pairwise import pairwise_distances_argmin from sklearn.metrics.pairwise import pairwise_kernels from sklearn.metrics.pairwise import PAIRWISE_KERNEL_FUNCTIONS from sklearn.metrics.pairwise import PAIRWISE_DISTANCE_FUNCTIONS from sklearn.metrics.pairwise import PAIRED_DISTANCES from sklearn.metrics.pairwise import check_pairwise_arrays from sklearn.metrics.pairwise import check_paired_arrays from sklearn.metrics.pairwise import _parallel_pairwise from sklearn.metrics.pairwise import paired_distances from sklearn.metrics.pairwise import paired_euclidean_distances from sklearn.metrics.pairwise import paired_manhattan_distances from sklearn.preprocessing import normalize def test_pairwise_distances(): # Test the pairwise_distance helper function. rng = np.random.RandomState(0) # Euclidean distance should be equivalent to calling the function. X = rng.random_sample((5, 4)) S = pairwise_distances(X, metric="euclidean") S2 = euclidean_distances(X) assert_array_almost_equal(S, S2) # Euclidean distance, with Y != X. Y = rng.random_sample((2, 4)) S = pairwise_distances(X, Y, metric="euclidean") S2 = euclidean_distances(X, Y) assert_array_almost_equal(S, S2) # Test with tuples as X and Y X_tuples = tuple([tuple([v for v in row]) for row in X]) Y_tuples = tuple([tuple([v for v in row]) for row in Y]) S2 = pairwise_distances(X_tuples, Y_tuples, metric="euclidean") assert_array_almost_equal(S, S2) # "cityblock" uses sklearn metric, cityblock (function) is scipy.spatial. S = pairwise_distances(X, metric="cityblock") S2 = pairwise_distances(X, metric=cityblock) assert_equal(S.shape[0], S.shape[1]) assert_equal(S.shape[0], X.shape[0]) assert_array_almost_equal(S, S2) # The manhattan metric should be equivalent to cityblock. S = pairwise_distances(X, Y, metric="manhattan") S2 = pairwise_distances(X, Y, metric=cityblock) assert_equal(S.shape[0], X.shape[0]) assert_equal(S.shape[1], Y.shape[0]) assert_array_almost_equal(S, S2) # Low-level function for manhattan can divide in blocks to avoid # using too much memory during the broadcasting S3 = manhattan_distances(X, Y, size_threshold=10) assert_array_almost_equal(S, S3) # Test cosine as a string metric versus cosine callable # "cosine" uses sklearn metric, cosine (function) is scipy.spatial S = pairwise_distances(X, Y, metric="cosine") S2 = pairwise_distances(X, Y, metric=cosine) assert_equal(S.shape[0], X.shape[0]) assert_equal(S.shape[1], Y.shape[0]) assert_array_almost_equal(S, S2) # Test with sparse X and Y, # currently only supported for Euclidean, L1 and cosine. X_sparse = csr_matrix(X) Y_sparse = csr_matrix(Y) S = pairwise_distances(X_sparse, Y_sparse, metric="euclidean") S2 = euclidean_distances(X_sparse, Y_sparse) assert_array_almost_equal(S, S2) S = pairwise_distances(X_sparse, Y_sparse, metric="cosine") S2 = cosine_distances(X_sparse, Y_sparse) assert_array_almost_equal(S, S2) S = pairwise_distances(X_sparse, Y_sparse.tocsc(), metric="manhattan") S2 = manhattan_distances(X_sparse.tobsr(), Y_sparse.tocoo()) assert_array_almost_equal(S, S2) S2 = manhattan_distances(X, Y) assert_array_almost_equal(S, S2) # Test with scipy.spatial.distance metric, with a kwd kwds = {"p": 2.0} S = pairwise_distances(X, Y, metric="minkowski", **kwds) S2 = pairwise_distances(X, Y, metric=minkowski, **kwds) assert_array_almost_equal(S, S2) # same with Y = None kwds = {"p": 2.0} S = pairwise_distances(X, metric="minkowski", **kwds) S2 = pairwise_distances(X, metric=minkowski, **kwds) assert_array_almost_equal(S, S2) # Test that scipy distance metrics throw an error if sparse matrix given assert_raises(TypeError, pairwise_distances, X_sparse, metric="minkowski") assert_raises(TypeError, pairwise_distances, X, Y_sparse, metric="minkowski") # Test that a value error is raised if the metric is unkown assert_raises(ValueError, pairwise_distances, X, Y, metric="blah") def test_pairwise_precomputed(): for func in [pairwise_distances, pairwise_kernels]: # Test correct shape assert_raises_regexp(ValueError, '.* shape .*', func, np.zeros((5, 3)), metric='precomputed') # with two args assert_raises_regexp(ValueError, '.* shape .*', func, np.zeros((5, 3)), np.zeros((4, 4)), metric='precomputed') # even if shape[1] agrees (although thus second arg is spurious) assert_raises_regexp(ValueError, '.* shape .*', func, np.zeros((5, 3)), np.zeros((4, 3)), metric='precomputed') # Test not copied (if appropriate dtype) S = np.zeros((5, 5)) S2 = func(S, metric="precomputed") assert_true(S is S2) # with two args S = np.zeros((5, 3)) S2 = func(S, np.zeros((3, 3)), metric="precomputed") assert_true(S is S2) # Test always returns float dtype S = func(np.array([[1]], dtype='int'), metric='precomputed') assert_equal('f', S.dtype.kind) # Test converts list to array-like S = func([[1]], metric='precomputed') assert_true(isinstance(S, np.ndarray)) def check_pairwise_parallel(func, metric, kwds): rng = np.random.RandomState(0) for make_data in (np.array, csr_matrix): X = make_data(rng.random_sample((5, 4))) Y = make_data(rng.random_sample((3, 4))) try: S = func(X, metric=metric, n_jobs=1, **kwds) except (TypeError, ValueError) as exc: # Not all metrics support sparse input # ValueError may be triggered by bad callable if make_data is csr_matrix: assert_raises(type(exc), func, X, metric=metric, n_jobs=2, **kwds) continue else: raise S2 = func(X, metric=metric, n_jobs=2, **kwds) assert_array_almost_equal(S, S2) S = func(X, Y, metric=metric, n_jobs=1, **kwds) S2 = func(X, Y, metric=metric, n_jobs=2, **kwds) assert_array_almost_equal(S, S2) def test_pairwise_parallel(): wminkowski_kwds = {'w': np.arange(1, 5).astype('double'), 'p': 1} metrics = [(pairwise_distances, 'euclidean', {}), (pairwise_distances, wminkowski, wminkowski_kwds), (pairwise_distances, 'wminkowski', wminkowski_kwds), (pairwise_kernels, 'polynomial', {'degree': 1}), (pairwise_kernels, callable_rbf_kernel, {'gamma': .1}), ] for func, metric, kwds in metrics: yield check_pairwise_parallel, func, metric, kwds def test_pairwise_callable_nonstrict_metric(): # paired_distances should allow callable metric where metric(x, x) != 0 # Knowing that the callable is a strict metric would allow the diagonal to # be left uncalculated and set to 0. assert_equal(pairwise_distances([[1]], metric=lambda x, y: 5)[0, 0], 5) def callable_rbf_kernel(x, y, **kwds): # Callable version of pairwise.rbf_kernel. K = rbf_kernel(np.atleast_2d(x), np.atleast_2d(y), **kwds) return K def test_pairwise_kernels(): # Test the pairwise_kernels helper function. rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) Y = rng.random_sample((2, 4)) # Test with all metrics that should be in PAIRWISE_KERNEL_FUNCTIONS. test_metrics = ["rbf", "sigmoid", "polynomial", "linear", "chi2", "additive_chi2"] for metric in test_metrics: function = PAIRWISE_KERNEL_FUNCTIONS[metric] # Test with Y=None K1 = pairwise_kernels(X, metric=metric) K2 = function(X) assert_array_almost_equal(K1, K2) # Test with Y=Y K1 = pairwise_kernels(X, Y=Y, metric=metric) K2 = function(X, Y=Y) assert_array_almost_equal(K1, K2) # Test with tuples as X and Y X_tuples = tuple([tuple([v for v in row]) for row in X]) Y_tuples = tuple([tuple([v for v in row]) for row in Y]) K2 = pairwise_kernels(X_tuples, Y_tuples, metric=metric) assert_array_almost_equal(K1, K2) # Test with sparse X and Y X_sparse = csr_matrix(X) Y_sparse = csr_matrix(Y) if metric in ["chi2", "additive_chi2"]: # these don't support sparse matrices yet assert_raises(ValueError, pairwise_kernels, X_sparse, Y=Y_sparse, metric=metric) continue K1 = pairwise_kernels(X_sparse, Y=Y_sparse, metric=metric) assert_array_almost_equal(K1, K2) # Test with a callable function, with given keywords. metric = callable_rbf_kernel kwds = {} kwds['gamma'] = 0.1 K1 = pairwise_kernels(X, Y=Y, metric=metric, **kwds) K2 = rbf_kernel(X, Y=Y, **kwds) assert_array_almost_equal(K1, K2) # callable function, X=Y K1 = pairwise_kernels(X, Y=X, metric=metric, **kwds) K2 = rbf_kernel(X, Y=X, **kwds) assert_array_almost_equal(K1, K2) def test_pairwise_kernels_filter_param(): rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) Y = rng.random_sample((2, 4)) K = rbf_kernel(X, Y, gamma=0.1) params = {"gamma": 0.1, "blabla": ":)"} K2 = pairwise_kernels(X, Y, metric="rbf", filter_params=True, **params) assert_array_almost_equal(K, K2) assert_raises(TypeError, pairwise_kernels, X, Y, "rbf", **params) def test_paired_distances(): # Test the pairwise_distance helper function. rng = np.random.RandomState(0) # Euclidean distance should be equivalent to calling the function. X = rng.random_sample((5, 4)) # Euclidean distance, with Y != X. Y = rng.random_sample((5, 4)) for metric, func in iteritems(PAIRED_DISTANCES): S = paired_distances(X, Y, metric=metric) S2 = func(X, Y) assert_array_almost_equal(S, S2) S3 = func(csr_matrix(X), csr_matrix(Y)) assert_array_almost_equal(S, S3) if metric in PAIRWISE_DISTANCE_FUNCTIONS: # Check the the pairwise_distances implementation # gives the same value distances = PAIRWISE_DISTANCE_FUNCTIONS[metric](X, Y) distances = np.diag(distances) assert_array_almost_equal(distances, S) # Check the callable implementation S = paired_distances(X, Y, metric='manhattan') S2 = paired_distances(X, Y, metric=lambda x, y: np.abs(x - y).sum(axis=0)) assert_array_almost_equal(S, S2) # Test that a value error is raised when the lengths of X and Y should not # differ Y = rng.random_sample((3, 4)) assert_raises(ValueError, paired_distances, X, Y) def test_pairwise_distances_argmin_min(): # Check pairwise minimum distances computation for any metric X = [[0], [1]] Y = [[-1], [2]] Xsp = dok_matrix(X) Ysp = csr_matrix(Y, dtype=np.float32) # euclidean metric D, E = pairwise_distances_argmin_min(X, Y, metric="euclidean") D2 = pairwise_distances_argmin(X, Y, metric="euclidean") assert_array_almost_equal(D, [0, 1]) assert_array_almost_equal(D2, [0, 1]) assert_array_almost_equal(D, [0, 1]) assert_array_almost_equal(E, [1., 1.]) # sparse matrix case Dsp, Esp = pairwise_distances_argmin_min(Xsp, Ysp, metric="euclidean") assert_array_equal(Dsp, D) assert_array_equal(Esp, E) # We don't want np.matrix here assert_equal(type(Dsp), np.ndarray) assert_equal(type(Esp), np.ndarray) # Non-euclidean sklearn metric D, E = pairwise_distances_argmin_min(X, Y, metric="manhattan") D2 = pairwise_distances_argmin(X, Y, metric="manhattan") assert_array_almost_equal(D, [0, 1]) assert_array_almost_equal(D2, [0, 1]) assert_array_almost_equal(E, [1., 1.]) D, E = pairwise_distances_argmin_min(Xsp, Ysp, metric="manhattan") D2 = pairwise_distances_argmin(Xsp, Ysp, metric="manhattan") assert_array_almost_equal(D, [0, 1]) assert_array_almost_equal(E, [1., 1.]) # Non-euclidean Scipy distance (callable) D, E = pairwise_distances_argmin_min(X, Y, metric=minkowski, metric_kwargs={"p": 2}) assert_array_almost_equal(D, [0, 1]) assert_array_almost_equal(E, [1., 1.]) # Non-euclidean Scipy distance (string) D, E = pairwise_distances_argmin_min(X, Y, metric="minkowski", metric_kwargs={"p": 2}) assert_array_almost_equal(D, [0, 1]) assert_array_almost_equal(E, [1., 1.]) # Compare with naive implementation rng = np.random.RandomState(0) X = rng.randn(97, 149) Y = rng.randn(111, 149) dist = pairwise_distances(X, Y, metric="manhattan") dist_orig_ind = dist.argmin(axis=0) dist_orig_val = dist[dist_orig_ind, range(len(dist_orig_ind))] dist_chunked_ind, dist_chunked_val = pairwise_distances_argmin_min( X, Y, axis=0, metric="manhattan", batch_size=50) np.testing.assert_almost_equal(dist_orig_ind, dist_chunked_ind, decimal=7) np.testing.assert_almost_equal(dist_orig_val, dist_chunked_val, decimal=7) def test_euclidean_distances(): # Check the pairwise Euclidean distances computation X = [[0]] Y = [[1], [2]] D = euclidean_distances(X, Y) assert_array_almost_equal(D, [[1., 2.]]) X = csr_matrix(X) Y = csr_matrix(Y) D = euclidean_distances(X, Y) assert_array_almost_equal(D, [[1., 2.]]) rng = np.random.RandomState(0) X = rng.random_sample((10, 4)) Y = rng.random_sample((20, 4)) X_norm_sq = (X ** 2).sum(axis=1).reshape(1, -1) Y_norm_sq = (Y ** 2).sum(axis=1).reshape(1, -1) # check that we still get the right answers with {X,Y}_norm_squared D1 = euclidean_distances(X, Y) D2 = euclidean_distances(X, Y, X_norm_squared=X_norm_sq) D3 = euclidean_distances(X, Y, Y_norm_squared=Y_norm_sq) D4 = euclidean_distances(X, Y, X_norm_squared=X_norm_sq, Y_norm_squared=Y_norm_sq) assert_array_almost_equal(D2, D1) assert_array_almost_equal(D3, D1) assert_array_almost_equal(D4, D1) # check we get the wrong answer with wrong {X,Y}_norm_squared X_norm_sq *= 0.5 Y_norm_sq *= 0.5 wrong_D = euclidean_distances(X, Y, X_norm_squared=np.zeros_like(X_norm_sq), Y_norm_squared=np.zeros_like(Y_norm_sq)) assert_greater(np.max(np.abs(wrong_D - D1)), .01) # Paired distances def test_paired_euclidean_distances(): # Check the paired Euclidean distances computation X = [[0], [0]] Y = [[1], [2]] D = paired_euclidean_distances(X, Y) assert_array_almost_equal(D, [1., 2.]) def test_paired_manhattan_distances(): # Check the paired manhattan distances computation X = [[0], [0]] Y = [[1], [2]] D = paired_manhattan_distances(X, Y) assert_array_almost_equal(D, [1., 2.]) def test_chi_square_kernel(): rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) Y = rng.random_sample((10, 4)) K_add = additive_chi2_kernel(X, Y) gamma = 0.1 K = chi2_kernel(X, Y, gamma=gamma) assert_equal(K.dtype, np.float) for i, x in enumerate(X): for j, y in enumerate(Y): chi2 = -np.sum((x - y) ** 2 / (x + y)) chi2_exp = np.exp(gamma * chi2) assert_almost_equal(K_add[i, j], chi2) assert_almost_equal(K[i, j], chi2_exp) # check diagonal is ones for data with itself K = chi2_kernel(Y) assert_array_equal(np.diag(K), 1) # check off-diagonal is < 1 but > 0: assert_true(np.all(K > 0)) assert_true(np.all(K - np.diag(np.diag(K)) < 1)) # check that float32 is preserved X = rng.random_sample((5, 4)).astype(np.float32) Y = rng.random_sample((10, 4)).astype(np.float32) K = chi2_kernel(X, Y) assert_equal(K.dtype, np.float32) # check integer type gets converted, # check that zeros are handled X = rng.random_sample((10, 4)).astype(np.int32) K = chi2_kernel(X, X) assert_true(np.isfinite(K).all()) assert_equal(K.dtype, np.float) # check that kernel of similar things is greater than dissimilar ones X = [[.3, .7], [1., 0]] Y = [[0, 1], [.9, .1]] K = chi2_kernel(X, Y) assert_greater(K[0, 0], K[0, 1]) assert_greater(K[1, 1], K[1, 0]) # test negative input assert_raises(ValueError, chi2_kernel, [[0, -1]]) assert_raises(ValueError, chi2_kernel, [[0, -1]], [[-1, -1]]) assert_raises(ValueError, chi2_kernel, [[0, 1]], [[-1, -1]]) # different n_features in X and Y assert_raises(ValueError, chi2_kernel, [[0, 1]], [[.2, .2, .6]]) # sparse matrices assert_raises(ValueError, chi2_kernel, csr_matrix(X), csr_matrix(Y)) assert_raises(ValueError, additive_chi2_kernel, csr_matrix(X), csr_matrix(Y)) def test_kernel_symmetry(): # Valid kernels should be symmetric rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) for kernel in (linear_kernel, polynomial_kernel, rbf_kernel, sigmoid_kernel, cosine_similarity): K = kernel(X, X) assert_array_almost_equal(K, K.T, 15) def test_kernel_sparse(): rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) X_sparse = csr_matrix(X) for kernel in (linear_kernel, polynomial_kernel, rbf_kernel, sigmoid_kernel, cosine_similarity): K = kernel(X, X) K2 = kernel(X_sparse, X_sparse) assert_array_almost_equal(K, K2) def test_linear_kernel(): rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) K = linear_kernel(X, X) # the diagonal elements of a linear kernel are their squared norm assert_array_almost_equal(K.flat[::6], [linalg.norm(x) ** 2 for x in X]) def test_rbf_kernel(): rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) K = rbf_kernel(X, X) # the diagonal elements of a rbf kernel are 1 assert_array_almost_equal(K.flat[::6], np.ones(5)) def test_cosine_similarity_sparse_output(): # Test if cosine_similarity correctly produces sparse output. rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) Y = rng.random_sample((3, 4)) Xcsr = csr_matrix(X) Ycsr = csr_matrix(Y) K1 = cosine_similarity(Xcsr, Ycsr, dense_output=False) assert_true(issparse(K1)) K2 = pairwise_kernels(Xcsr, Y=Ycsr, metric="cosine") assert_array_almost_equal(K1.todense(), K2) def test_cosine_similarity(): # Test the cosine_similarity. rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) Y = rng.random_sample((3, 4)) Xcsr = csr_matrix(X) Ycsr = csr_matrix(Y) for X_, Y_ in ((X, None), (X, Y), (Xcsr, None), (Xcsr, Ycsr)): # Test that the cosine is kernel is equal to a linear kernel when data # has been previously normalized by L2-norm. K1 = pairwise_kernels(X_, Y=Y_, metric="cosine") X_ = normalize(X_) if Y_ is not None: Y_ = normalize(Y_) K2 = pairwise_kernels(X_, Y=Y_, metric="linear") assert_array_almost_equal(K1, K2) def test_check_dense_matrices(): # Ensure that pairwise array check works for dense matrices. # Check that if XB is None, XB is returned as reference to XA XA = np.resize(np.arange(40), (5, 8)) XA_checked, XB_checked = check_pairwise_arrays(XA, None) assert_true(XA_checked is XB_checked) assert_array_equal(XA, XA_checked) def test_check_XB_returned(): # Ensure that if XA and XB are given correctly, they return as equal. # Check that if XB is not None, it is returned equal. # Note that the second dimension of XB is the same as XA. XA = np.resize(np.arange(40), (5, 8)) XB = np.resize(np.arange(32), (4, 8)) XA_checked, XB_checked = check_pairwise_arrays(XA, XB) assert_array_equal(XA, XA_checked) assert_array_equal(XB, XB_checked) XB = np.resize(np.arange(40), (5, 8)) XA_checked, XB_checked = check_paired_arrays(XA, XB) assert_array_equal(XA, XA_checked) assert_array_equal(XB, XB_checked) def test_check_different_dimensions(): # Ensure an error is raised if the dimensions are different. XA = np.resize(np.arange(45), (5, 9)) XB = np.resize(np.arange(32), (4, 8)) assert_raises(ValueError, check_pairwise_arrays, XA, XB) XB = np.resize(np.arange(4 * 9), (4, 9)) assert_raises(ValueError, check_paired_arrays, XA, XB) def test_check_invalid_dimensions(): # Ensure an error is raised on 1D input arrays. # The modified tests are not 1D. In the old test, the array was internally # converted to 2D anyways XA = np.arange(45).reshape(9, 5) XB = np.arange(32).reshape(4, 8) assert_raises(ValueError, check_pairwise_arrays, XA, XB) XA = np.arange(45).reshape(9, 5) XB = np.arange(32).reshape(4, 8) assert_raises(ValueError, check_pairwise_arrays, XA, XB) def test_check_sparse_arrays(): # Ensures that checks return valid sparse matrices. rng = np.random.RandomState(0) XA = rng.random_sample((5, 4)) XA_sparse = csr_matrix(XA) XB = rng.random_sample((5, 4)) XB_sparse = csr_matrix(XB) XA_checked, XB_checked = check_pairwise_arrays(XA_sparse, XB_sparse) # compare their difference because testing csr matrices for # equality with '==' does not work as expected. assert_true(issparse(XA_checked)) assert_equal(abs(XA_sparse - XA_checked).sum(), 0) assert_true(issparse(XB_checked)) assert_equal(abs(XB_sparse - XB_checked).sum(), 0) XA_checked, XA_2_checked = check_pairwise_arrays(XA_sparse, XA_sparse) assert_true(issparse(XA_checked)) assert_equal(abs(XA_sparse - XA_checked).sum(), 0) assert_true(issparse(XA_2_checked)) assert_equal(abs(XA_2_checked - XA_checked).sum(), 0) def tuplify(X): # Turns a numpy matrix (any n-dimensional array) into tuples. s = X.shape if len(s) > 1: # Tuplify each sub-array in the input. return tuple(tuplify(row) for row in X) else: # Single dimension input, just return tuple of contents. return tuple(r for r in X) def test_check_tuple_input(): # Ensures that checks return valid tuples. rng = np.random.RandomState(0) XA = rng.random_sample((5, 4)) XA_tuples = tuplify(XA) XB = rng.random_sample((5, 4)) XB_tuples = tuplify(XB) XA_checked, XB_checked = check_pairwise_arrays(XA_tuples, XB_tuples) assert_array_equal(XA_tuples, XA_checked) assert_array_equal(XB_tuples, XB_checked) def test_check_preserve_type(): # Ensures that type float32 is preserved. XA = np.resize(np.arange(40), (5, 8)).astype(np.float32) XB = np.resize(np.arange(40), (5, 8)).astype(np.float32) XA_checked, XB_checked = check_pairwise_arrays(XA, None) assert_equal(XA_checked.dtype, np.float32) # both float32 XA_checked, XB_checked = check_pairwise_arrays(XA, XB) assert_equal(XA_checked.dtype, np.float32) assert_equal(XB_checked.dtype, np.float32) # mismatched A XA_checked, XB_checked = check_pairwise_arrays(XA.astype(np.float), XB) assert_equal(XA_checked.dtype, np.float) assert_equal(XB_checked.dtype, np.float) # mismatched B XA_checked, XB_checked = check_pairwise_arrays(XA, XB.astype(np.float)) assert_equal(XA_checked.dtype, np.float) assert_equal(XB_checked.dtype, np.float)
JayvicWen/Crawler
refs/heads/master
jianlimoban/jianlimoban/items.py
2
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy class JianlimobanItem(scrapy.Item): # define the fields for your item here like: name = scrapy.Field() url = scrapy.Field() page = scrapy.Field()
sparkslabs/kamaelia
refs/heads/master
Code/Python/Kamaelia/Examples/SimpleGraphicalApps/TextBox/ConsoleReader_TextDisplayer_Demo.py
6
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # 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 Kamaelia.Chassis.Pipeline import Pipeline from Kamaelia.Util.Console import ConsoleReader from Kamaelia.UI.Pygame.Text import Textbox, TextDisplayer Pipeline( ConsoleReader(), TextDisplayer() ).run()
ryanpdwyer/jittermodel
refs/heads/master
jittermodel/tests/test_plot.py
1
# -*- coding: utf-8 -*- import numpy as np import matplotlib # Force matplotlib to not use any Xwindows backend. # See http://stackoverflow.com/a/3054314 matplotlib.use('Agg') from nose.tools import eq_ import unittest from jittermodel import u, silentremove from jittermodel.base import Cantilever, Transistor, Experiment from jittermodel.plot import reformat_properties, GeneratePlotData, unpickle from jittermodel.tests import expected_failure class Test_reformat_properties(unittest.TestCase): @staticmethod def test_reformat_properties(): properties = {'color': ('b', 'g'), 'ls': ('-', '--')} exp_reformatted = [{'color': 'b', 'ls': '-'}, {'color': 'g', 'ls': '--'}] eq_(exp_reformatted, reformat_properties(properties)) class TestGeneratePlotData(unittest.TestCase): filename = 'test-generate-plot-data.pkl' figname = 'test-generate-plot-data-plot.png' def setUp(self): # If I actually care what is executed, replace these with objects where # every possible parameter is specified. cant = Cantilever() trans = Transistor() expt = Experiment() self.gpd = GeneratePlotData(cant, trans, expt, 'd', (40*u.nm, 500*u.nm)) def tearDown(self): silentremove(self.filename) silentremove(self.figname) def test_plot_linear_scale(self): # Setup the plotting object without actually calling the plotting # function, because we don't want to waste time actually calculating # friction values. self.gpd.x_var = 'd' self.gpd.y_var = 'friction' self.gpd.multi_plot_var = 'V_g' self.gpd.multi_plot_values = [1*u.V] self.gpd.x_scale = 'linear' self.gpd.n_pts = 50 self.gpd.x = np.linspace(40, 500, 50) # Generic x data self.gpd.y = self.gpd.x * 2 # Generate y data self.gpd.make_plot(figname=self.figname, tight_layout=False) def test_pickle_GeneratePlotData_with_no_plot_data(self): """The simulation has not been run yet, so the pickling should work fine.""" self.gpd.pickle(self.filename) unpickle(self.filename)
rbarlow/pulp
refs/heads/master
server/test/unit/server/db/migration_packages/raise_exception/0002_oh_no.py
17
def migrate(): raise Exception("Bet you didn't see this coming.")
steebchen/youtube-dl
refs/heads/master
youtube_dl/extractor/stretchinternet.py
18
from __future__ import unicode_literals from .common import InfoExtractor from ..utils import int_or_none class StretchInternetIE(InfoExtractor): _VALID_URL = r'https?://portal\.stretchinternet\.com/[^/]+/portal\.htm\?.*?\beventId=(?P<id>\d+)' _TEST = { 'url': 'https://portal.stretchinternet.com/umary/portal.htm?eventId=313900&streamType=video', 'info_dict': { 'id': '313900', 'ext': 'mp4', 'title': 'Augustana (S.D.) Baseball vs University of Mary', 'description': 'md5:7578478614aae3bdd4a90f578f787438', 'timestamp': 1490468400, 'upload_date': '20170325', } } def _real_extract(self, url): video_id = self._match_id(url) stream = self._download_json( 'https://neo-client.stretchinternet.com/streamservice/v1/media/stream/v%s' % video_id, video_id) video_url = 'https://%s' % stream['source'] event = self._download_json( 'https://neo-client.stretchinternet.com/portal-ws/getEvent.json', video_id, query={ 'clientID': 99997, 'eventID': video_id, 'token': 'asdf', })['event'] title = event.get('title') or event['mobileTitle'] description = event.get('customText') timestamp = int_or_none(event.get('longtime')) return { 'id': video_id, 'title': title, 'description': description, 'timestamp': timestamp, 'url': video_url, }
sander76/home-assistant
refs/heads/dev
homeassistant/components/currencylayer/sensor.py
5
"""Support for currencylayer.com exchange rates service.""" from datetime import timedelta import logging import requests import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ( ATTR_ATTRIBUTION, CONF_API_KEY, CONF_BASE, CONF_NAME, CONF_QUOTE, ) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) _RESOURCE = "http://apilayer.net/api/live" ATTRIBUTION = "Data provided by currencylayer.com" DEFAULT_BASE = "USD" DEFAULT_NAME = "CurrencyLayer Sensor" ICON = "mdi:currency" SCAN_INTERVAL = timedelta(hours=4) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_API_KEY): cv.string, vol.Required(CONF_QUOTE): vol.All(cv.ensure_list, [cv.string]), vol.Optional(CONF_BASE, default=DEFAULT_BASE): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Currencylayer sensor.""" base = config[CONF_BASE] api_key = config[CONF_API_KEY] parameters = {"source": base, "access_key": api_key, "format": 1} rest = CurrencylayerData(_RESOURCE, parameters) response = requests.get(_RESOURCE, params=parameters, timeout=10) sensors = [] for variable in config[CONF_QUOTE]: sensors.append(CurrencylayerSensor(rest, base, variable)) if "error" in response.json(): return False add_entities(sensors, True) class CurrencylayerSensor(SensorEntity): """Implementing the Currencylayer sensor.""" def __init__(self, rest, base, quote): """Initialize the sensor.""" self.rest = rest self._quote = quote self._base = base self._state = None @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return self._quote @property def name(self): """Return the name of the sensor.""" return self._base @property def icon(self): """Return the icon to use in the frontend, if any.""" return ICON @property def state(self): """Return the state of the sensor.""" return self._state @property def extra_state_attributes(self): """Return the state attributes of the sensor.""" return {ATTR_ATTRIBUTION: ATTRIBUTION} def update(self): """Update current date.""" self.rest.update() value = self.rest.data if value is not None: self._state = round(value[f"{self._base}{self._quote}"], 4) class CurrencylayerData: """Get data from Currencylayer.org.""" def __init__(self, resource, parameters): """Initialize the data object.""" self._resource = resource self._parameters = parameters self.data = None def update(self): """Get the latest data from Currencylayer.""" try: result = requests.get(self._resource, params=self._parameters, timeout=10) if "error" in result.json(): raise ValueError(result.json()["error"]["info"]) self.data = result.json()["quotes"] _LOGGER.debug("Currencylayer data updated: %s", result.json()["timestamp"]) except ValueError as err: _LOGGER.error("Check Currencylayer API %s", err.args) self.data = None
snyderks/advent-solutions
refs/heads/master
Day9.py
1
# Day 9: http://adventofcode.com/2016/day/9 # Problem: Given a sequence of characters with repeat markers denoted by # parentheses, such as (10x2) -- repeat the next 10 characters twice. # If another repeat sequence is included in a previous one, it is not counted. import time import re start = time.time() f = open("inputs/Day9.txt", "r") repeat = re.compile("(?:\()(\d+)(?:x)(\d+)(?:\))") letters = f.readline() decompressed = "" while len(letters) > 0: match = repeat.search(letters) if match is not None: if match.start(0) > 0: decompressed += letters[:match.start(0)] amt = int(match.group(1)) times = int(match.group(2)) endIndex = match.end(0) if endIndex + amt < len(letters): decompressed += (letters[endIndex: endIndex + amt] * times) letters = letters[endIndex + amt:] else: decompressed += (letters[endIndex:] * times) letters = "" else: decompressed += letters letters = "" decompressed = decompressed.strip() print("Decompressed to: " + str(len(decompressed)) + " characters") # Part 2: Decompress with everything. EVERYTHING. ALL THE EXPAND MARKERS # Note: the below isn't really mine. Couldn't get the answer so I had to look # up hints. f = open("inputs/Day9.txt", "r") letters = f.readline().strip() decompressedLength = 0 def decompress(s): if "(" not in s: return len(s) chars = 0 while "(" in s: chars += s.find("(") s = s[s.find("("):] marker = s[1:s.find(")")].split("x") s = s[s.find(")") + 1:] chars += decompress(s[:int(marker[0])]) * int(marker[1]) s = s[int(marker[0]):] chars += len(s) return chars print("Length: " + str(decompress(letters)))
kenshay/ImageScripter
refs/heads/master
ProgramData/SystemFiles/Python/Lib/site-packages/elan/Pools/System Tabs/11_Ups_Check_Pages_OLD.py
2
from ImageScripter import * from elan import * #UPS################################################# Say("Checking the ups page") Configurator.ups.Click() Configurator.upspage.SetThreshold(.98) Configurator.upspage.Wait(seconds=10) Say("Checking the ups page looks great") Configurator.communicationdevices.Click() Configurator.upscommunicationdevicespage.SetThreshold(.98) Configurator.upscommunicationdevicespage.Wait(seconds=10) Configurator.upspowersupplies.Click() Configurator.upspowersuppliespage.SetThreshold(.98) Configurator.upspowersuppliespage.Wait(seconds=10) ###UPS Right Click Configurator.system.Click() Configurator.ups.Click() Configurator.communicationdevices.RightClick() Configurator.communicationdevicesrightclickmenu.Wait() Configurator.grey.Click() Configurator.system.Click() Configurator.ups.Click() Configurator.upspowersupplies.RightClick() Configurator.upspowersuppliesrightclickmenu.Wait() Configurator.grey.Click() ######################################################Window ###################################Communication Devices Configurator.system.Click() Configurator.ups.Click() Configurator.communicationdevices.RightClick() Configurator.addnewcommunicationdevice.RealClick() Configurator.addnewcommunicationdevicewindow.Wait() Add.PushButton.Click('Cancel') Press('enter') Configurator.system.Click() Configurator.ups.Click() ###################################UPS POWER SUPPLIES Configurator.system.Click() Configurator.ups.Click() Configurator.upspowersupplies.RightClick() Configurator.addnewupspowersupply.RealClick() Configurator.addnewupspowersupplywindow.Wait() Add.PushButton.Click('Cancel') Press('enter') ###Reset Configurator.media.Click() Configurator.system.Click()
ever0409/payton
refs/heads/master
nitro.py
1
@bot.message_handler(commands=['nitro']) def nitro(m): cid = m.chat.id markup = types.InlineKeyboardMarkup() ret_msg = bot.send_message(cid, "Write Soon ```{}```", disable_notification=True, reply_markup=markup) assert ret_msg.message_id
aldenso/MyBooks
refs/heads/master
db_upgrade.py
1
#!../myvirtualenv/bin/python from migrate.versioning import api from config import SQLALCHEMY_DATABASE_URI from config import SQLALCHEMY_MIGRATE_REPO api.upgrade(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO) v = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO) print('Current database version: ' + str(v))
fuselock/odoo
refs/heads/8.0
addons/hw_escpos/__init__.py
385
# -*- 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 controllers import escpos # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
becm/meson
refs/heads/master
test cases/common/132 build by default targets in tests/write_file.py
14
#!/usr/bin/env python3 import sys with open(sys.argv[1], 'w') as f: f.write('Test')
ESS-LLP/erpnext-medical
refs/heads/develop
erpnext/patches/v11_0/move_leave_approvers_from_employee.py
5
import frappe from frappe import _ from frappe.model.utils.rename_field import rename_field def execute(): frappe.reload_doc("hr", "doctype", "department_approver") frappe.reload_doc("hr", "doctype", "employee") frappe.reload_doc("hr", "doctype", "department") if frappe.db.has_column('Department', 'leave_approver'): rename_field('Department', "leave_approver", "leave_approvers") if frappe.db.has_column('Department', 'expense_approver'): rename_field('Department', "expense_approver", "expense_approvers") if not frappe.db.table_exists("Employee Leave Approver"): return approvers = frappe.db.sql("""select distinct app.leave_approver, emp.department from `tabEmployee Leave Approver` app, `tabEmployee` emp where app.parenttype = 'Employee' and emp.name = app.parent """, as_dict=True) for record in approvers: if record.department: department = frappe.get_doc("Department", record.department) if not department: return if not len(department.leave_approvers): department.append("leave_approvers",{ "approver": record.leave_approver }).db_insert()
waytai/django
refs/heads/master
django/contrib/gis/geometry/regex.py
657
import re # Regular expression for recognizing HEXEWKB and WKT. A prophylactic measure # to prevent potentially malicious input from reaching the underlying C # library. Not a substitute for good Web security programming practices. hex_regex = re.compile(r'^[0-9A-F]+$', re.I) wkt_regex = re.compile(r'^(SRID=(?P<srid>\-?\d+);)?' r'(?P<wkt>' r'(?P<type>POINT|LINESTRING|LINEARRING|POLYGON|MULTIPOINT|' r'MULTILINESTRING|MULTIPOLYGON|GEOMETRYCOLLECTION)' r'[ACEGIMLONPSRUTYZ\d,\.\-\(\) ]+)$', re.I) json_regex = re.compile(r'^(\s+)?\{.*}(\s+)?$', re.DOTALL)
rhots/automation
refs/heads/master
automation/slack.py
1
import os from slackclient import SlackClient class Slack: """Slack allows you to send messages to a specified Slack channel.""" def __init__(self): slack_api_token = os.environ["SLACK_API_TOKEN"] self._client = SlackClient(slack_api_token) def send_message(self, channel, message): self._client.api_call( "chat.postMessage", channel=channel, text=message)
boone/ansible-modules-core
refs/heads/devel
cloud/amazon/ec2_asg.py
27
#!/usr/bin/python # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. DOCUMENTATION = """ --- module: ec2_asg short_description: Create or delete AWS Autoscaling Groups description: - Can create or delete AWS Autoscaling Groups - Works with the ec2_lc module to manage Launch Configurations version_added: "1.6" author: "Gareth Rushgrove (@garethr)" options: state: description: - register or deregister the instance required: true choices: ['present', 'absent'] name: description: - Unique name for group to be created or deleted required: true load_balancers: description: - List of ELB names to use for the group required: false availability_zones: description: - List of availability zone names in which to create the group. Defaults to all the availability zones in the region if vpc_zone_identifier is not set. required: false launch_config_name: description: - Name of the Launch configuration to use for the group. See the ec2_lc module for managing these. required: true min_size: description: - Minimum number of instances in group required: false max_size: description: - Maximum number of instances in group required: false desired_capacity: description: - Desired number of instances in group required: false replace_all_instances: description: - In a rolling fashion, replace all instances with an old launch configuration with one from the current launch configuration. required: false version_added: "1.8" default: False replace_batch_size: description: - Number of instances you'd like to replace at a time. Used with replace_all_instances. required: false version_added: "1.8" default: 1 replace_instances: description: - List of instance_ids belonging to the named ASG that you would like to terminate and be replaced with instances matching the current launch configuration. required: false version_added: "1.8" default: None lc_check: description: - Check to make sure instances that are being replaced with replace_instances do not aready have the current launch_config. required: false version_added: "1.8" default: True region: description: - The AWS region to use. If not specified then the value of the EC2_REGION environment variable, if any, is used. required: false aliases: ['aws_region', 'ec2_region'] vpc_zone_identifier: description: - List of VPC subnets to use required: false default: None tags: description: - A list of tags to add to the Auto Scale Group. Optional key is 'propagate_at_launch', which defaults to true. required: false default: None version_added: "1.7" health_check_period: description: - Length of time in seconds after a new EC2 instance comes into service that Auto Scaling starts checking its health. required: false default: 500 seconds version_added: "1.7" health_check_type: description: - The service you want the health status from, Amazon EC2 or Elastic Load Balancer. required: false default: EC2 version_added: "1.7" choices: ['EC2', 'ELB'] default_cooldown: description: - The number of seconds after a scaling activity completes before another can begin. required: false default: 300 seconds version_added: "2.0" wait_timeout: description: - how long before wait instances to become viable when replaced. Used in concjunction with instance_ids option. default: 300 version_added: "1.8" wait_for_instances: description: - Wait for the ASG instances to be in a ready state before exiting. If instances are behind an ELB, it will wait until the ELB determines all instances have a lifecycle_state of "InService" and a health_status of "Healthy". version_added: "1.9" default: yes required: False termination_policies: description: - An ordered list of criteria used for selecting instances to be removed from the Auto Scaling group when reducing capacity. - For 'Default', when used to create a new autoscaling group, the "Default" value is used. When used to change an existent autoscaling group, the current termination policies are mantained required: false default: Default choices: ['OldestInstance', 'NewestInstance', 'OldestLaunchConfiguration', 'ClosestToNextInstanceHour', 'Default'] version_added: "2.0" extends_documentation_fragment: aws """ EXAMPLES = ''' # Basic configuration - ec2_asg: name: special load_balancers: [ 'lb1', 'lb2' ] availability_zones: [ 'eu-west-1a', 'eu-west-1b' ] launch_config_name: 'lc-1' min_size: 1 max_size: 10 desired_capacity: 5 vpc_zone_identifier: [ 'subnet-abcd1234', 'subnet-1a2b3c4d' ] tags: - environment: production propagate_at_launch: no # Rolling ASG Updates Below is an example of how to assign a new launch config to an ASG and terminate old instances. All instances in "myasg" that do not have the launch configuration named "my_new_lc" will be terminated in a rolling fashion with instances using the current launch configuration, "my_new_lc". This could also be considered a rolling deploy of a pre-baked AMI. If this is a newly created group, the instances will not be replaced since all instances will have the current launch configuration. - name: create launch config ec2_lc: name: my_new_lc image_id: ami-lkajsf key_name: mykey region: us-east-1 security_groups: sg-23423 instance_type: m1.small assign_public_ip: yes - ec2_asg: name: myasg launch_config_name: my_new_lc health_check_period: 60 health_check_type: ELB replace_all_instances: yes min_size: 5 max_size: 5 desired_capacity: 5 region: us-east-1 To only replace a couple of instances instead of all of them, supply a list to "replace_instances": - ec2_asg: name: myasg launch_config_name: my_new_lc health_check_period: 60 health_check_type: ELB replace_instances: - i-b345231 - i-24c2931 min_size: 5 max_size: 5 desired_capacity: 5 region: us-east-1 ''' import time import logging as log from ansible.module_utils.basic import * from ansible.module_utils.ec2 import * log.getLogger('boto').setLevel(log.CRITICAL) #log.basicConfig(filename='/tmp/ansible_ec2_asg.log',level=log.DEBUG, format='%(asctime)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') try: import boto.ec2.autoscale from boto.ec2.autoscale import AutoScaleConnection, AutoScalingGroup, Tag from boto.exception import BotoServerError HAS_BOTO = True except ImportError: HAS_BOTO = False ASG_ATTRIBUTES = ('availability_zones', 'default_cooldown', 'desired_capacity', 'health_check_period', 'health_check_type', 'launch_config_name', 'load_balancers', 'max_size', 'min_size', 'name', 'placement_group', 'termination_policies', 'vpc_zone_identifier') INSTANCE_ATTRIBUTES = ('instance_id', 'health_status', 'lifecycle_state', 'launch_config_name') def enforce_required_arguments(module): ''' As many arguments are not required for autoscale group deletion they cannot be mandatory arguments for the module, so we enforce them here ''' missing_args = [] for arg in ('min_size', 'max_size', 'launch_config_name'): if module.params[arg] is None: missing_args.append(arg) if missing_args: module.fail_json(msg="Missing required arguments for autoscaling group create/update: %s" % ",".join(missing_args)) def get_properties(autoscaling_group): properties = dict((attr, getattr(autoscaling_group, attr)) for attr in ASG_ATTRIBUTES) # Ugly hack to make this JSON-serializable. We take a list of boto Tag # objects and replace them with a dict-representation. Needed because the # tags are included in ansible's return value (which is jsonified) if 'tags' in properties and isinstance(properties['tags'], list): serializable_tags = {} for tag in properties['tags']: serializable_tags[tag.key] = [tag.value, tag.propagate_at_launch] properties['tags'] = serializable_tags properties['healthy_instances'] = 0 properties['in_service_instances'] = 0 properties['unhealthy_instances'] = 0 properties['pending_instances'] = 0 properties['viable_instances'] = 0 properties['terminating_instances'] = 0 if autoscaling_group.instances: properties['instances'] = [i.instance_id for i in autoscaling_group.instances] instance_facts = {} for i in autoscaling_group.instances: instance_facts[i.instance_id] = {'health_status': i.health_status, 'lifecycle_state': i.lifecycle_state, 'launch_config_name': i.launch_config_name } if i.health_status == 'Healthy' and i.lifecycle_state == 'InService': properties['viable_instances'] += 1 if i.health_status == 'Healthy': properties['healthy_instances'] += 1 else: properties['unhealthy_instances'] += 1 if i.lifecycle_state == 'InService': properties['in_service_instances'] += 1 if i.lifecycle_state == 'Terminating': properties['terminating_instances'] += 1 if i.lifecycle_state == 'Pending': properties['pending_instances'] += 1 properties['instance_facts'] = instance_facts properties['load_balancers'] = autoscaling_group.load_balancers if getattr(autoscaling_group, "tags", None): properties['tags'] = dict((t.key, t.value) for t in autoscaling_group.tags) return properties def elb_dreg(asg_connection, module, group_name, instance_id): region, ec2_url, aws_connect_params = get_aws_connection_info(module) as_group = asg_connection.get_all_groups(names=[group_name])[0] wait_timeout = module.params.get('wait_timeout') props = get_properties(as_group) count = 1 if as_group.load_balancers and as_group.health_check_type == 'ELB': try: elb_connection = connect_to_aws(boto.ec2.elb, region, **aws_connect_params) except boto.exception.NoAuthHandlerFound, e: module.fail_json(msg=str(e)) else: return exists = True for lb in as_group.load_balancers: elb_connection.deregister_instances(lb, instance_id) log.debug("De-registering {0} from ELB {1}".format(instance_id, lb)) wait_timeout = time.time() + wait_timeout while wait_timeout > time.time() and count > 0: count = 0 for lb in as_group.load_balancers: lb_instances = elb_connection.describe_instance_health(lb) for i in lb_instances: if i.instance_id == instance_id and i.state == "InService": count += 1 log.debug("{0}: {1}, {2}".format(i.instance_id, i.state, i.description)) time.sleep(10) if wait_timeout <= time.time(): # waiting took too long module.fail_json(msg = "Waited too long for instance to deregister. {0}".format(time.asctime())) def elb_healthy(asg_connection, elb_connection, module, group_name): healthy_instances = [] as_group = asg_connection.get_all_groups(names=[group_name])[0] props = get_properties(as_group) # get healthy, inservice instances from ASG instances = [] for instance, settings in props['instance_facts'].items(): if settings['lifecycle_state'] == 'InService' and settings['health_status'] == 'Healthy': instances.append(instance) log.debug("ASG considers the following instances InService and Healthy: {0}".format(instances)) log.debug("ELB instance status:") for lb in as_group.load_balancers: # we catch a race condition that sometimes happens if the instance exists in the ASG # but has not yet show up in the ELB try: lb_instances = elb_connection.describe_instance_health(lb, instances=instances) except boto.exception.InvalidInstance, e: pass for i in lb_instances: if i.state == "InService": healthy_instances.append(i.instance_id) log.debug("{0}: {1}".format(i.instance_id, i.state)) return len(healthy_instances) def wait_for_elb(asg_connection, module, group_name): region, ec2_url, aws_connect_params = get_aws_connection_info(module) wait_timeout = module.params.get('wait_timeout') # if the health_check_type is ELB, we want to query the ELBs directly for instance # status as to avoid health_check_grace period that is awarded to ASG instances as_group = asg_connection.get_all_groups(names=[group_name])[0] if as_group.load_balancers and as_group.health_check_type == 'ELB': log.debug("Waiting for ELB to consider intances healthy.") try: elb_connection = connect_to_aws(boto.ec2.elb, region, **aws_connect_params) except boto.exception.NoAuthHandlerFound, e: module.fail_json(msg=str(e)) wait_timeout = time.time() + wait_timeout healthy_instances = elb_healthy(asg_connection, elb_connection, module, group_name) while healthy_instances < as_group.min_size and wait_timeout > time.time(): healthy_instances = elb_healthy(asg_connection, elb_connection, module, group_name) log.debug("ELB thinks {0} instances are healthy.".format(healthy_instances)) time.sleep(10) if wait_timeout <= time.time(): # waiting took too long module.fail_json(msg = "Waited too long for ELB instances to be healthy. %s" % time.asctime()) log.debug("Waiting complete. ELB thinks {0} instances are healthy.".format(healthy_instances)) def create_autoscaling_group(connection, module): group_name = module.params.get('name') load_balancers = module.params['load_balancers'] availability_zones = module.params['availability_zones'] launch_config_name = module.params.get('launch_config_name') min_size = module.params['min_size'] max_size = module.params['max_size'] desired_capacity = module.params.get('desired_capacity') vpc_zone_identifier = module.params.get('vpc_zone_identifier') set_tags = module.params.get('tags') health_check_period = module.params.get('health_check_period') health_check_type = module.params.get('health_check_type') default_cooldown = module.params.get('default_cooldown') wait_for_instances = module.params.get('wait_for_instances') as_groups = connection.get_all_groups(names=[group_name]) wait_timeout = module.params.get('wait_timeout') termination_policies = module.params.get('termination_policies') if not vpc_zone_identifier and not availability_zones: region, ec2_url, aws_connect_params = get_aws_connection_info(module) try: ec2_connection = connect_to_aws(boto.ec2, region, **aws_connect_params) except (boto.exception.NoAuthHandlerFound, StandardError), e: module.fail_json(msg=str(e)) elif vpc_zone_identifier: vpc_zone_identifier = ','.join(vpc_zone_identifier) asg_tags = [] for tag in set_tags: for k,v in tag.iteritems(): if k !='propagate_at_launch': asg_tags.append(Tag(key=k, value=v, propagate_at_launch=bool(tag.get('propagate_at_launch', True)), resource_id=group_name)) if not as_groups: if not vpc_zone_identifier and not availability_zones: availability_zones = module.params['availability_zones'] = [zone.name for zone in ec2_connection.get_all_zones()] enforce_required_arguments(module) launch_configs = connection.get_all_launch_configurations(names=[launch_config_name]) ag = AutoScalingGroup( group_name=group_name, load_balancers=load_balancers, availability_zones=availability_zones, launch_config=launch_configs[0], min_size=min_size, max_size=max_size, desired_capacity=desired_capacity, vpc_zone_identifier=vpc_zone_identifier, connection=connection, tags=asg_tags, health_check_period=health_check_period, health_check_type=health_check_type, default_cooldown=default_cooldown, termination_policies=termination_policies) try: connection.create_auto_scaling_group(ag) if wait_for_instances == True: wait_for_new_inst(module, connection, group_name, wait_timeout, desired_capacity, 'viable_instances') wait_for_elb(connection, module, group_name) as_group = connection.get_all_groups(names=[group_name])[0] asg_properties = get_properties(as_group) changed = True return(changed, asg_properties) except BotoServerError, e: module.fail_json(msg=str(e)) else: as_group = as_groups[0] changed = False for attr in ASG_ATTRIBUTES: if module.params.get(attr, None) is not None: module_attr = module.params.get(attr) if attr == 'vpc_zone_identifier': module_attr = ','.join(module_attr) group_attr = getattr(as_group, attr) # we do this because AWS and the module may return the same list # sorted differently try: module_attr.sort() except: pass try: group_attr.sort() except: pass if group_attr != module_attr: changed = True setattr(as_group, attr, module_attr) if len(set_tags) > 0: have_tags = {} want_tags = {} for tag in asg_tags: want_tags[tag.key] = [tag.value, tag.propagate_at_launch] dead_tags = [] for tag in as_group.tags: have_tags[tag.key] = [tag.value, tag.propagate_at_launch] if not tag.key in want_tags: changed = True dead_tags.append(tag) if dead_tags != []: connection.delete_tags(dead_tags) if have_tags != want_tags: changed = True connection.create_or_update_tags(asg_tags) # handle loadbalancers separately because None != [] load_balancers = module.params.get('load_balancers') or [] if load_balancers and as_group.load_balancers != load_balancers: changed = True as_group.load_balancers = module.params.get('load_balancers') if changed: try: as_group.update() except BotoServerError, e: module.fail_json(msg=str(e)) if wait_for_instances == True: wait_for_new_inst(module, connection, group_name, wait_timeout, desired_capacity, 'viable_instances') wait_for_elb(connection, module, group_name) try: as_group = connection.get_all_groups(names=[group_name])[0] asg_properties = get_properties(as_group) except BotoServerError, e: module.fail_json(msg=str(e)) return(changed, asg_properties) def delete_autoscaling_group(connection, module): group_name = module.params.get('name') groups = connection.get_all_groups(names=[group_name]) if groups: group = groups[0] group.max_size = 0 group.min_size = 0 group.desired_capacity = 0 group.update() instances = True while instances: tmp_groups = connection.get_all_groups(names=[group_name]) if tmp_groups: tmp_group = tmp_groups[0] if not tmp_group.instances: instances = False time.sleep(10) group.delete() while len(connection.get_all_groups(names=[group_name])): time.sleep(5) changed=True return changed else: changed=False return changed def get_chunks(l, n): for i in xrange(0, len(l), n): yield l[i:i+n] def update_size(group, max_size, min_size, dc): log.debug("setting ASG sizes") log.debug("minimum size: {0}, desired_capacity: {1}, max size: {2}".format(min_size, dc, max_size )) group.max_size = max_size group.min_size = min_size group.desired_capacity = dc group.update() def replace(connection, module): batch_size = module.params.get('replace_batch_size') wait_timeout = module.params.get('wait_timeout') group_name = module.params.get('name') max_size = module.params.get('max_size') min_size = module.params.get('min_size') desired_capacity = module.params.get('desired_capacity') lc_check = module.params.get('lc_check') replace_instances = module.params.get('replace_instances') as_group = connection.get_all_groups(names=[group_name])[0] wait_for_new_inst(module, connection, group_name, wait_timeout, as_group.min_size, 'viable_instances') props = get_properties(as_group) instances = props['instances'] if replace_instances: instances = replace_instances # check to see if instances are replaceable if checking launch configs new_instances, old_instances = get_instances_by_lc(props, lc_check, instances) num_new_inst_needed = desired_capacity - len(new_instances) if lc_check: if num_new_inst_needed == 0 and old_instances: log.debug("No new instances needed, but old instances are present. Removing old instances") terminate_batch(connection, module, old_instances, instances, True) as_group = connection.get_all_groups(names=[group_name])[0] props = get_properties(as_group) changed = True return(changed, props) # we don't want to spin up extra instances if not necessary if num_new_inst_needed < batch_size: log.debug("Overriding batch size to {0}".format(num_new_inst_needed)) batch_size = num_new_inst_needed if not old_instances: changed = False return(changed, props) # set temporary settings and wait for them to be reached # This should get overriden if the number of instances left is less than the batch size. as_group = connection.get_all_groups(names=[group_name])[0] update_size(as_group, max_size + batch_size, min_size + batch_size, desired_capacity + batch_size) wait_for_new_inst(module, connection, group_name, wait_timeout, as_group.min_size, 'viable_instances') wait_for_elb(connection, module, group_name) as_group = connection.get_all_groups(names=[group_name])[0] props = get_properties(as_group) instances = props['instances'] if replace_instances: instances = replace_instances log.debug("beginning main loop") for i in get_chunks(instances, batch_size): # break out of this loop if we have enough new instances break_early, desired_size, term_instances = terminate_batch(connection, module, i, instances, False) wait_for_term_inst(connection, module, term_instances) wait_for_new_inst(module, connection, group_name, wait_timeout, desired_size, 'viable_instances') wait_for_elb(connection, module, group_name) as_group = connection.get_all_groups(names=[group_name])[0] if break_early: log.debug("breaking loop") break update_size(as_group, max_size, min_size, desired_capacity) as_group = connection.get_all_groups(names=[group_name])[0] asg_properties = get_properties(as_group) log.debug("Rolling update complete.") changed=True return(changed, asg_properties) def get_instances_by_lc(props, lc_check, initial_instances): new_instances = [] old_instances = [] # old instances are those that have the old launch config if lc_check: for i in props['instances']: if props['instance_facts'][i]['launch_config_name'] == props['launch_config_name']: new_instances.append(i) else: old_instances.append(i) else: log.debug("Comparing initial instances with current: {0}".format(initial_instances)) for i in props['instances']: if i not in initial_instances: new_instances.append(i) else: old_instances.append(i) log.debug("New instances: {0}, {1}".format(len(new_instances), new_instances)) log.debug("Old instances: {0}, {1}".format(len(old_instances), old_instances)) return new_instances, old_instances def list_purgeable_instances(props, lc_check, replace_instances, initial_instances): instances_to_terminate = [] instances = ( inst_id for inst_id in replace_instances if inst_id in props['instances']) # check to make sure instances given are actually in the given ASG # and they have a non-current launch config if lc_check: for i in instances: if props['instance_facts'][i]['launch_config_name'] != props['launch_config_name']: instances_to_terminate.append(i) else: for i in instances: if i in initial_instances: instances_to_terminate.append(i) return instances_to_terminate def terminate_batch(connection, module, replace_instances, initial_instances, leftovers=False): batch_size = module.params.get('replace_batch_size') min_size = module.params.get('min_size') desired_capacity = module.params.get('desired_capacity') group_name = module.params.get('name') wait_timeout = int(module.params.get('wait_timeout')) lc_check = module.params.get('lc_check') decrement_capacity = False break_loop = False as_group = connection.get_all_groups(names=[group_name])[0] props = get_properties(as_group) desired_size = as_group.min_size new_instances, old_instances = get_instances_by_lc(props, lc_check, initial_instances) num_new_inst_needed = desired_capacity - len(new_instances) # check to make sure instances given are actually in the given ASG # and they have a non-current launch config instances_to_terminate = list_purgeable_instances(props, lc_check, replace_instances, initial_instances) log.debug("new instances needed: {0}".format(num_new_inst_needed)) log.debug("new instances: {0}".format(new_instances)) log.debug("old instances: {0}".format(old_instances)) log.debug("batch instances: {0}".format(",".join(instances_to_terminate))) if num_new_inst_needed == 0: decrement_capacity = True if as_group.min_size != min_size: as_group.min_size = min_size as_group.update() log.debug("Updating minimum size back to original of {0}".format(min_size)) #if are some leftover old instances, but we are already at capacity with new ones # we don't want to decrement capacity if leftovers: decrement_capacity = False break_loop = True instances_to_terminate = old_instances desired_size = min_size log.debug("No new instances needed") if num_new_inst_needed < batch_size and num_new_inst_needed !=0 : instances_to_terminate = instances_to_terminate[:num_new_inst_needed] decrement_capacity = False break_loop = False log.debug("{0} new instances needed".format(num_new_inst_needed)) log.debug("decrementing capacity: {0}".format(decrement_capacity)) for instance_id in instances_to_terminate: elb_dreg(connection, module, group_name, instance_id) log.debug("terminating instance: {0}".format(instance_id)) connection.terminate_instance(instance_id, decrement_capacity=decrement_capacity) # we wait to make sure the machines we marked as Unhealthy are # no longer in the list return break_loop, desired_size, instances_to_terminate def wait_for_term_inst(connection, module, term_instances): batch_size = module.params.get('replace_batch_size') wait_timeout = module.params.get('wait_timeout') group_name = module.params.get('name') lc_check = module.params.get('lc_check') as_group = connection.get_all_groups(names=[group_name])[0] props = get_properties(as_group) count = 1 wait_timeout = time.time() + wait_timeout while wait_timeout > time.time() and count > 0: log.debug("waiting for instances to terminate") count = 0 as_group = connection.get_all_groups(names=[group_name])[0] props = get_properties(as_group) instance_facts = props['instance_facts'] instances = ( i for i in instance_facts if i in term_instances) for i in instances: lifecycle = instance_facts[i]['lifecycle_state'] health = instance_facts[i]['health_status'] log.debug("Instance {0} has state of {1},{2}".format(i,lifecycle,health )) if lifecycle == 'Terminating' or healthy == 'Unhealthy': count += 1 time.sleep(10) if wait_timeout <= time.time(): # waiting took too long module.fail_json(msg = "Waited too long for old instances to terminate. %s" % time.asctime()) def wait_for_new_inst(module, connection, group_name, wait_timeout, desired_size, prop): # make sure we have the latest stats after that last loop. as_group = connection.get_all_groups(names=[group_name])[0] props = get_properties(as_group) log.debug("Waiting for {0} = {1}, currently {2}".format(prop, desired_size, props[prop])) # now we make sure that we have enough instances in a viable state wait_timeout = time.time() + wait_timeout while wait_timeout > time.time() and desired_size > props[prop]: log.debug("Waiting for {0} = {1}, currently {2}".format(prop, desired_size, props[prop])) time.sleep(10) as_group = connection.get_all_groups(names=[group_name])[0] props = get_properties(as_group) if wait_timeout <= time.time(): # waiting took too long module.fail_json(msg = "Waited too long for new instances to become viable. %s" % time.asctime()) log.debug("Reached {0}: {1}".format(prop, desired_size)) return props def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict( name=dict(required=True, type='str'), load_balancers=dict(type='list'), availability_zones=dict(type='list'), launch_config_name=dict(type='str'), min_size=dict(type='int'), max_size=dict(type='int'), desired_capacity=dict(type='int'), vpc_zone_identifier=dict(type='list'), replace_batch_size=dict(type='int', default=1), replace_all_instances=dict(type='bool', default=False), replace_instances=dict(type='list', default=[]), lc_check=dict(type='bool', default=True), wait_timeout=dict(type='int', default=300), state=dict(default='present', choices=['present', 'absent']), tags=dict(type='list', default=[]), health_check_period=dict(type='int', default=300), health_check_type=dict(default='EC2', choices=['EC2', 'ELB']), default_cooldown=dict(type='int', default=300), wait_for_instances=dict(type='bool', default=True), termination_policies=dict(type='list', default='Default') ), ) module = AnsibleModule( argument_spec=argument_spec, mutually_exclusive = [['replace_all_instances', 'replace_instances']] ) if not HAS_BOTO: module.fail_json(msg='boto required for this module') state = module.params.get('state') replace_instances = module.params.get('replace_instances') replace_all_instances = module.params.get('replace_all_instances') region, ec2_url, aws_connect_params = get_aws_connection_info(module) try: connection = connect_to_aws(boto.ec2.autoscale, region, **aws_connect_params) if not connection: module.fail_json(msg="failed to connect to AWS for the given region: %s" % str(region)) except boto.exception.NoAuthHandlerFound, e: module.fail_json(msg=str(e)) changed = create_changed = replace_changed = False if state == 'present': create_changed, asg_properties=create_autoscaling_group(connection, module) elif state == 'absent': changed = delete_autoscaling_group(connection, module) module.exit_json( changed = changed ) if replace_all_instances or replace_instances: replace_changed, asg_properties=replace(connection, module) if create_changed or replace_changed: changed = True module.exit_json( changed = changed, **asg_properties ) main()
Kamik423/uni_plan
refs/heads/master
plan/plan/lib/python3.4/site-packages/setuptools/command/easy_install.py
75
#!/usr/bin/env python """ Easy Install ------------ A tool for doing automatic download/extract/build of distutils-based Python packages. For detailed documentation, see the accompanying EasyInstall.txt file, or visit the `EasyInstall home page`__. __ https://setuptools.readthedocs.io/en/latest/easy_install.html """ from glob import glob from distutils.util import get_platform from distutils.util import convert_path, subst_vars from distutils.errors import ( DistutilsArgError, DistutilsOptionError, DistutilsError, DistutilsPlatformError, ) from distutils.command.install import INSTALL_SCHEMES, SCHEME_KEYS from distutils import log, dir_util from distutils.command.build_scripts import first_line_re from distutils.spawn import find_executable import sys import os import zipimport import shutil import tempfile import zipfile import re import stat import random import textwrap import warnings import site import struct import contextlib import subprocess import shlex import io from setuptools.extern import six from setuptools.extern.six.moves import configparser, map from setuptools import Command from setuptools.sandbox import run_setup from setuptools.py31compat import get_path, get_config_vars from setuptools.py27compat import rmtree_safe from setuptools.command import setopt from setuptools.archive_util import unpack_archive from setuptools.package_index import ( PackageIndex, parse_requirement_arg, URL_SCHEME, ) from setuptools.command import bdist_egg, egg_info from pkg_resources import ( yield_lines, normalize_path, resource_string, ensure_directory, get_distribution, find_distributions, Environment, Requirement, Distribution, PathMetadata, EggMetadata, WorkingSet, DistributionNotFound, VersionConflict, DEVELOP_DIST, ) import pkg_resources.py31compat # Turn on PEP440Warnings warnings.filterwarnings("default", category=pkg_resources.PEP440Warning) __all__ = [ 'samefile', 'easy_install', 'PthDistributions', 'extract_wininst_cfg', 'main', 'get_exe_prefixes', ] def is_64bit(): return struct.calcsize("P") == 8 def samefile(p1, p2): """ Determine if two paths reference the same file. Augments os.path.samefile to work on Windows and suppresses errors if the path doesn't exist. """ both_exist = os.path.exists(p1) and os.path.exists(p2) use_samefile = hasattr(os.path, 'samefile') and both_exist if use_samefile: return os.path.samefile(p1, p2) norm_p1 = os.path.normpath(os.path.normcase(p1)) norm_p2 = os.path.normpath(os.path.normcase(p2)) return norm_p1 == norm_p2 if six.PY2: def _to_ascii(s): return s def isascii(s): try: six.text_type(s, 'ascii') return True except UnicodeError: return False else: def _to_ascii(s): return s.encode('ascii') def isascii(s): try: s.encode('ascii') return True except UnicodeError: return False _one_liner = lambda text: textwrap.dedent(text).strip().replace('\n', '; ') class easy_install(Command): """Manage a download/build/install process""" description = "Find/get/install Python packages" command_consumes_arguments = True user_options = [ ('prefix=', None, "installation prefix"), ("zip-ok", "z", "install package as a zipfile"), ("multi-version", "m", "make apps have to require() a version"), ("upgrade", "U", "force upgrade (searches PyPI for latest versions)"), ("install-dir=", "d", "install package to DIR"), ("script-dir=", "s", "install scripts to DIR"), ("exclude-scripts", "x", "Don't install scripts"), ("always-copy", "a", "Copy all needed packages to install dir"), ("index-url=", "i", "base URL of Python Package Index"), ("find-links=", "f", "additional URL(s) to search for packages"), ("build-directory=", "b", "download/extract/build in DIR; keep the results"), ('optimize=', 'O', "also compile with optimization: -O1 for \"python -O\", " "-O2 for \"python -OO\", and -O0 to disable [default: -O0]"), ('record=', None, "filename in which to record list of installed files"), ('always-unzip', 'Z', "don't install as a zipfile, no matter what"), ('site-dirs=', 'S', "list of directories where .pth files work"), ('editable', 'e', "Install specified packages in editable form"), ('no-deps', 'N', "don't install dependencies"), ('allow-hosts=', 'H', "pattern(s) that hostnames must match"), ('local-snapshots-ok', 'l', "allow building eggs from local checkouts"), ('version', None, "print version information and exit"), ('no-find-links', None, "Don't load find-links defined in packages being installed") ] boolean_options = [ 'zip-ok', 'multi-version', 'exclude-scripts', 'upgrade', 'always-copy', 'editable', 'no-deps', 'local-snapshots-ok', 'version' ] if site.ENABLE_USER_SITE: help_msg = "install in user site-package '%s'" % site.USER_SITE user_options.append(('user', None, help_msg)) boolean_options.append('user') negative_opt = {'always-unzip': 'zip-ok'} create_index = PackageIndex def initialize_options(self): # the --user option seems to be an opt-in one, # so the default should be False. self.user = 0 self.zip_ok = self.local_snapshots_ok = None self.install_dir = self.script_dir = self.exclude_scripts = None self.index_url = None self.find_links = None self.build_directory = None self.args = None self.optimize = self.record = None self.upgrade = self.always_copy = self.multi_version = None self.editable = self.no_deps = self.allow_hosts = None self.root = self.prefix = self.no_report = None self.version = None self.install_purelib = None # for pure module distributions self.install_platlib = None # non-pure (dists w/ extensions) self.install_headers = None # for C/C++ headers self.install_lib = None # set to either purelib or platlib self.install_scripts = None self.install_data = None self.install_base = None self.install_platbase = None if site.ENABLE_USER_SITE: self.install_userbase = site.USER_BASE self.install_usersite = site.USER_SITE else: self.install_userbase = None self.install_usersite = None self.no_find_links = None # Options not specifiable via command line self.package_index = None self.pth_file = self.always_copy_from = None self.site_dirs = None self.installed_projects = {} self.sitepy_installed = False # Always read easy_install options, even if we are subclassed, or have # an independent instance created. This ensures that defaults will # always come from the standard configuration file(s)' "easy_install" # section, even if this is a "develop" or "install" command, or some # other embedding. self._dry_run = None self.verbose = self.distribution.verbose self.distribution._set_command_options( self, self.distribution.get_option_dict('easy_install') ) def delete_blockers(self, blockers): extant_blockers = ( filename for filename in blockers if os.path.exists(filename) or os.path.islink(filename) ) list(map(self._delete_path, extant_blockers)) def _delete_path(self, path): log.info("Deleting %s", path) if self.dry_run: return is_tree = os.path.isdir(path) and not os.path.islink(path) remover = rmtree if is_tree else os.unlink remover(path) @staticmethod def _render_version(): """ Render the Setuptools version and installation details, then exit. """ ver = sys.version[:3] dist = get_distribution('setuptools') tmpl = 'setuptools {dist.version} from {dist.location} (Python {ver})' print(tmpl.format(**locals())) raise SystemExit() def finalize_options(self): self.version and self._render_version() py_version = sys.version.split()[0] prefix, exec_prefix = get_config_vars('prefix', 'exec_prefix') self.config_vars = { 'dist_name': self.distribution.get_name(), 'dist_version': self.distribution.get_version(), 'dist_fullname': self.distribution.get_fullname(), 'py_version': py_version, 'py_version_short': py_version[0:3], 'py_version_nodot': py_version[0] + py_version[2], 'sys_prefix': prefix, 'prefix': prefix, 'sys_exec_prefix': exec_prefix, 'exec_prefix': exec_prefix, # Only python 3.2+ has abiflags 'abiflags': getattr(sys, 'abiflags', ''), } if site.ENABLE_USER_SITE: self.config_vars['userbase'] = self.install_userbase self.config_vars['usersite'] = self.install_usersite self._fix_install_dir_for_user_site() self.expand_basedirs() self.expand_dirs() self._expand( 'install_dir', 'script_dir', 'build_directory', 'site_dirs', ) # If a non-default installation directory was specified, default the # script directory to match it. if self.script_dir is None: self.script_dir = self.install_dir if self.no_find_links is None: self.no_find_links = False # Let install_dir get set by install_lib command, which in turn # gets its info from the install command, and takes into account # --prefix and --home and all that other crud. self.set_undefined_options( 'install_lib', ('install_dir', 'install_dir') ) # Likewise, set default script_dir from 'install_scripts.install_dir' self.set_undefined_options( 'install_scripts', ('install_dir', 'script_dir') ) if self.user and self.install_purelib: self.install_dir = self.install_purelib self.script_dir = self.install_scripts # default --record from the install command self.set_undefined_options('install', ('record', 'record')) # Should this be moved to the if statement below? It's not used # elsewhere normpath = map(normalize_path, sys.path) self.all_site_dirs = get_site_dirs() if self.site_dirs is not None: site_dirs = [ os.path.expanduser(s.strip()) for s in self.site_dirs.split(',') ] for d in site_dirs: if not os.path.isdir(d): log.warn("%s (in --site-dirs) does not exist", d) elif normalize_path(d) not in normpath: raise DistutilsOptionError( d + " (in --site-dirs) is not on sys.path" ) else: self.all_site_dirs.append(normalize_path(d)) if not self.editable: self.check_site_dir() self.index_url = self.index_url or "https://pypi.python.org/simple" self.shadow_path = self.all_site_dirs[:] for path_item in self.install_dir, normalize_path(self.script_dir): if path_item not in self.shadow_path: self.shadow_path.insert(0, path_item) if self.allow_hosts is not None: hosts = [s.strip() for s in self.allow_hosts.split(',')] else: hosts = ['*'] if self.package_index is None: self.package_index = self.create_index( self.index_url, search_path=self.shadow_path, hosts=hosts, ) self.local_index = Environment(self.shadow_path + sys.path) if self.find_links is not None: if isinstance(self.find_links, six.string_types): self.find_links = self.find_links.split() else: self.find_links = [] if self.local_snapshots_ok: self.package_index.scan_egg_links(self.shadow_path + sys.path) if not self.no_find_links: self.package_index.add_find_links(self.find_links) self.set_undefined_options('install_lib', ('optimize', 'optimize')) if not isinstance(self.optimize, int): try: self.optimize = int(self.optimize) if not (0 <= self.optimize <= 2): raise ValueError except ValueError: raise DistutilsOptionError("--optimize must be 0, 1, or 2") if self.editable and not self.build_directory: raise DistutilsArgError( "Must specify a build directory (-b) when using --editable" ) if not self.args: raise DistutilsArgError( "No urls, filenames, or requirements specified (see --help)") self.outputs = [] def _fix_install_dir_for_user_site(self): """ Fix the install_dir if "--user" was used. """ if not self.user or not site.ENABLE_USER_SITE: return self.create_home_path() if self.install_userbase is None: msg = "User base directory is not specified" raise DistutilsPlatformError(msg) self.install_base = self.install_platbase = self.install_userbase scheme_name = os.name.replace('posix', 'unix') + '_user' self.select_scheme(scheme_name) def _expand_attrs(self, attrs): for attr in attrs: val = getattr(self, attr) if val is not None: if os.name == 'posix' or os.name == 'nt': val = os.path.expanduser(val) val = subst_vars(val, self.config_vars) setattr(self, attr, val) def expand_basedirs(self): """Calls `os.path.expanduser` on install_base, install_platbase and root.""" self._expand_attrs(['install_base', 'install_platbase', 'root']) def expand_dirs(self): """Calls `os.path.expanduser` on install dirs.""" dirs = [ 'install_purelib', 'install_platlib', 'install_lib', 'install_headers', 'install_scripts', 'install_data', ] self._expand_attrs(dirs) def run(self): if self.verbose != self.distribution.verbose: log.set_verbosity(self.verbose) try: for spec in self.args: self.easy_install(spec, not self.no_deps) if self.record: outputs = self.outputs if self.root: # strip any package prefix root_len = len(self.root) for counter in range(len(outputs)): outputs[counter] = outputs[counter][root_len:] from distutils import file_util self.execute( file_util.write_file, (self.record, outputs), "writing list of installed files to '%s'" % self.record ) self.warn_deprecated_options() finally: log.set_verbosity(self.distribution.verbose) def pseudo_tempname(self): """Return a pseudo-tempname base in the install directory. This code is intentionally naive; if a malicious party can write to the target directory you're already in deep doodoo. """ try: pid = os.getpid() except Exception: pid = random.randint(0, sys.maxsize) return os.path.join(self.install_dir, "test-easy-install-%s" % pid) def warn_deprecated_options(self): pass def check_site_dir(self): """Verify that self.install_dir is .pth-capable dir, if needed""" instdir = normalize_path(self.install_dir) pth_file = os.path.join(instdir, 'easy-install.pth') # Is it a configured, PYTHONPATH, implicit, or explicit site dir? is_site_dir = instdir in self.all_site_dirs if not is_site_dir and not self.multi_version: # No? Then directly test whether it does .pth file processing is_site_dir = self.check_pth_processing() else: # make sure we can write to target dir testfile = self.pseudo_tempname() + '.write-test' test_exists = os.path.exists(testfile) try: if test_exists: os.unlink(testfile) open(testfile, 'w').close() os.unlink(testfile) except (OSError, IOError): self.cant_write_to_target() if not is_site_dir and not self.multi_version: # Can't install non-multi to non-site dir raise DistutilsError(self.no_default_version_msg()) if is_site_dir: if self.pth_file is None: self.pth_file = PthDistributions(pth_file, self.all_site_dirs) else: self.pth_file = None if instdir not in map(normalize_path, _pythonpath()): # only PYTHONPATH dirs need a site.py, so pretend it's there self.sitepy_installed = True elif self.multi_version and not os.path.exists(pth_file): self.sitepy_installed = True # don't need site.py in this case self.pth_file = None # and don't create a .pth file self.install_dir = instdir __cant_write_msg = textwrap.dedent(""" can't create or remove files in install directory The following error occurred while trying to add or remove files in the installation directory: %s The installation directory you specified (via --install-dir, --prefix, or the distutils default setting) was: %s """).lstrip() __not_exists_id = textwrap.dedent(""" This directory does not currently exist. Please create it and try again, or choose a different installation directory (using the -d or --install-dir option). """).lstrip() __access_msg = textwrap.dedent(""" Perhaps your account does not have write access to this directory? If the installation directory is a system-owned directory, you may need to sign in as the administrator or "root" account. If you do not have administrative access to this machine, you may wish to choose a different installation directory, preferably one that is listed in your PYTHONPATH environment variable. For information on other options, you may wish to consult the documentation at: https://setuptools.readthedocs.io/en/latest/easy_install.html Please make the appropriate changes for your system and try again. """).lstrip() def cant_write_to_target(self): msg = self.__cant_write_msg % (sys.exc_info()[1], self.install_dir,) if not os.path.exists(self.install_dir): msg += '\n' + self.__not_exists_id else: msg += '\n' + self.__access_msg raise DistutilsError(msg) def check_pth_processing(self): """Empirically verify whether .pth files are supported in inst. dir""" instdir = self.install_dir log.info("Checking .pth file support in %s", instdir) pth_file = self.pseudo_tempname() + ".pth" ok_file = pth_file + '.ok' ok_exists = os.path.exists(ok_file) tmpl = _one_liner(""" import os f = open({ok_file!r}, 'w') f.write('OK') f.close() """) + '\n' try: if ok_exists: os.unlink(ok_file) dirname = os.path.dirname(ok_file) pkg_resources.py31compat.makedirs(dirname, exist_ok=True) f = open(pth_file, 'w') except (OSError, IOError): self.cant_write_to_target() else: try: f.write(tmpl.format(**locals())) f.close() f = None executable = sys.executable if os.name == 'nt': dirname, basename = os.path.split(executable) alt = os.path.join(dirname, 'pythonw.exe') use_alt = ( basename.lower() == 'python.exe' and os.path.exists(alt) ) if use_alt: # use pythonw.exe to avoid opening a console window executable = alt from distutils.spawn import spawn spawn([executable, '-E', '-c', 'pass'], 0) if os.path.exists(ok_file): log.info( "TEST PASSED: %s appears to support .pth files", instdir ) return True finally: if f: f.close() if os.path.exists(ok_file): os.unlink(ok_file) if os.path.exists(pth_file): os.unlink(pth_file) if not self.multi_version: log.warn("TEST FAILED: %s does NOT support .pth files", instdir) return False def install_egg_scripts(self, dist): """Write all the scripts for `dist`, unless scripts are excluded""" if not self.exclude_scripts and dist.metadata_isdir('scripts'): for script_name in dist.metadata_listdir('scripts'): if dist.metadata_isdir('scripts/' + script_name): # The "script" is a directory, likely a Python 3 # __pycache__ directory, so skip it. continue self.install_script( dist, script_name, dist.get_metadata('scripts/' + script_name) ) self.install_wrapper_scripts(dist) def add_output(self, path): if os.path.isdir(path): for base, dirs, files in os.walk(path): for filename in files: self.outputs.append(os.path.join(base, filename)) else: self.outputs.append(path) def not_editable(self, spec): if self.editable: raise DistutilsArgError( "Invalid argument %r: you can't use filenames or URLs " "with --editable (except via the --find-links option)." % (spec,) ) def check_editable(self, spec): if not self.editable: return if os.path.exists(os.path.join(self.build_directory, spec.key)): raise DistutilsArgError( "%r already exists in %s; can't do a checkout there" % (spec.key, self.build_directory) ) @contextlib.contextmanager def _tmpdir(self): tmpdir = tempfile.mkdtemp(prefix=six.u("easy_install-")) try: # cast to str as workaround for #709 and #710 and #712 yield str(tmpdir) finally: os.path.exists(tmpdir) and rmtree(rmtree_safe(tmpdir)) def easy_install(self, spec, deps=False): if not self.editable: self.install_site_py() with self._tmpdir() as tmpdir: if not isinstance(spec, Requirement): if URL_SCHEME(spec): # It's a url, download it to tmpdir and process self.not_editable(spec) dl = self.package_index.download(spec, tmpdir) return self.install_item(None, dl, tmpdir, deps, True) elif os.path.exists(spec): # Existing file or directory, just process it directly self.not_editable(spec) return self.install_item(None, spec, tmpdir, deps, True) else: spec = parse_requirement_arg(spec) self.check_editable(spec) dist = self.package_index.fetch_distribution( spec, tmpdir, self.upgrade, self.editable, not self.always_copy, self.local_index ) if dist is None: msg = "Could not find suitable distribution for %r" % spec if self.always_copy: msg += " (--always-copy skips system and development eggs)" raise DistutilsError(msg) elif dist.precedence == DEVELOP_DIST: # .egg-info dists don't need installing, just process deps self.process_distribution(spec, dist, deps, "Using") return dist else: return self.install_item(spec, dist.location, tmpdir, deps) def install_item(self, spec, download, tmpdir, deps, install_needed=False): # Installation is also needed if file in tmpdir or is not an egg install_needed = install_needed or self.always_copy install_needed = install_needed or os.path.dirname(download) == tmpdir install_needed = install_needed or not download.endswith('.egg') install_needed = install_needed or ( self.always_copy_from is not None and os.path.dirname(normalize_path(download)) == normalize_path(self.always_copy_from) ) if spec and not install_needed: # at this point, we know it's a local .egg, we just don't know if # it's already installed. for dist in self.local_index[spec.project_name]: if dist.location == download: break else: install_needed = True # it's not in the local index log.info("Processing %s", os.path.basename(download)) if install_needed: dists = self.install_eggs(spec, download, tmpdir) for dist in dists: self.process_distribution(spec, dist, deps) else: dists = [self.egg_distribution(download)] self.process_distribution(spec, dists[0], deps, "Using") if spec is not None: for dist in dists: if dist in spec: return dist def select_scheme(self, name): """Sets the install directories by applying the install schemes.""" # it's the caller's problem if they supply a bad name! scheme = INSTALL_SCHEMES[name] for key in SCHEME_KEYS: attrname = 'install_' + key if getattr(self, attrname) is None: setattr(self, attrname, scheme[key]) def process_distribution(self, requirement, dist, deps=True, *info): self.update_pth(dist) self.package_index.add(dist) if dist in self.local_index[dist.key]: self.local_index.remove(dist) self.local_index.add(dist) self.install_egg_scripts(dist) self.installed_projects[dist.key] = dist log.info(self.installation_report(requirement, dist, *info)) if (dist.has_metadata('dependency_links.txt') and not self.no_find_links): self.package_index.add_find_links( dist.get_metadata_lines('dependency_links.txt') ) if not deps and not self.always_copy: return elif requirement is not None and dist.key != requirement.key: log.warn("Skipping dependencies for %s", dist) return # XXX this is not the distribution we were looking for elif requirement is None or dist not in requirement: # if we wound up with a different version, resolve what we've got distreq = dist.as_requirement() requirement = Requirement(str(distreq)) log.info("Processing dependencies for %s", requirement) try: distros = WorkingSet([]).resolve( [requirement], self.local_index, self.easy_install ) except DistributionNotFound as e: raise DistutilsError(str(e)) except VersionConflict as e: raise DistutilsError(e.report()) if self.always_copy or self.always_copy_from: # Force all the relevant distros to be copied or activated for dist in distros: if dist.key not in self.installed_projects: self.easy_install(dist.as_requirement()) log.info("Finished processing dependencies for %s", requirement) def should_unzip(self, dist): if self.zip_ok is not None: return not self.zip_ok if dist.has_metadata('not-zip-safe'): return True if not dist.has_metadata('zip-safe'): return True return False def maybe_move(self, spec, dist_filename, setup_base): dst = os.path.join(self.build_directory, spec.key) if os.path.exists(dst): msg = ( "%r already exists in %s; build directory %s will not be kept" ) log.warn(msg, spec.key, self.build_directory, setup_base) return setup_base if os.path.isdir(dist_filename): setup_base = dist_filename else: if os.path.dirname(dist_filename) == setup_base: os.unlink(dist_filename) # get it out of the tmp dir contents = os.listdir(setup_base) if len(contents) == 1: dist_filename = os.path.join(setup_base, contents[0]) if os.path.isdir(dist_filename): # if the only thing there is a directory, move it instead setup_base = dist_filename ensure_directory(dst) shutil.move(setup_base, dst) return dst def install_wrapper_scripts(self, dist): if self.exclude_scripts: return for args in ScriptWriter.best().get_args(dist): self.write_script(*args) def install_script(self, dist, script_name, script_text, dev_path=None): """Generate a legacy script wrapper and install it""" spec = str(dist.as_requirement()) is_script = is_python_script(script_text, script_name) if is_script: body = self._load_template(dev_path) % locals() script_text = ScriptWriter.get_header(script_text) + body self.write_script(script_name, _to_ascii(script_text), 'b') @staticmethod def _load_template(dev_path): """ There are a couple of template scripts in the package. This function loads one of them and prepares it for use. """ # See https://github.com/pypa/setuptools/issues/134 for info # on script file naming and downstream issues with SVR4 name = 'script.tmpl' if dev_path: name = name.replace('.tmpl', ' (dev).tmpl') raw_bytes = resource_string('setuptools', name) return raw_bytes.decode('utf-8') def write_script(self, script_name, contents, mode="t", blockers=()): """Write an executable file to the scripts directory""" self.delete_blockers( # clean up old .py/.pyw w/o a script [os.path.join(self.script_dir, x) for x in blockers] ) log.info("Installing %s script to %s", script_name, self.script_dir) target = os.path.join(self.script_dir, script_name) self.add_output(target) mask = current_umask() if not self.dry_run: ensure_directory(target) if os.path.exists(target): os.unlink(target) with open(target, "w" + mode) as f: f.write(contents) chmod(target, 0o777 - mask) def install_eggs(self, spec, dist_filename, tmpdir): # .egg dirs or files are already built, so just return them if dist_filename.lower().endswith('.egg'): return [self.install_egg(dist_filename, tmpdir)] elif dist_filename.lower().endswith('.exe'): return [self.install_exe(dist_filename, tmpdir)] # Anything else, try to extract and build setup_base = tmpdir if os.path.isfile(dist_filename) and not dist_filename.endswith('.py'): unpack_archive(dist_filename, tmpdir, self.unpack_progress) elif os.path.isdir(dist_filename): setup_base = os.path.abspath(dist_filename) if (setup_base.startswith(tmpdir) # something we downloaded and self.build_directory and spec is not None): setup_base = self.maybe_move(spec, dist_filename, setup_base) # Find the setup.py file setup_script = os.path.join(setup_base, 'setup.py') if not os.path.exists(setup_script): setups = glob(os.path.join(setup_base, '*', 'setup.py')) if not setups: raise DistutilsError( "Couldn't find a setup script in %s" % os.path.abspath(dist_filename) ) if len(setups) > 1: raise DistutilsError( "Multiple setup scripts in %s" % os.path.abspath(dist_filename) ) setup_script = setups[0] # Now run it, and return the result if self.editable: log.info(self.report_editable(spec, setup_script)) return [] else: return self.build_and_install(setup_script, setup_base) def egg_distribution(self, egg_path): if os.path.isdir(egg_path): metadata = PathMetadata(egg_path, os.path.join(egg_path, 'EGG-INFO')) else: metadata = EggMetadata(zipimport.zipimporter(egg_path)) return Distribution.from_filename(egg_path, metadata=metadata) def install_egg(self, egg_path, tmpdir): destination = os.path.join( self.install_dir, os.path.basename(egg_path), ) destination = os.path.abspath(destination) if not self.dry_run: ensure_directory(destination) dist = self.egg_distribution(egg_path) if not samefile(egg_path, destination): if os.path.isdir(destination) and not os.path.islink(destination): dir_util.remove_tree(destination, dry_run=self.dry_run) elif os.path.exists(destination): self.execute( os.unlink, (destination,), "Removing " + destination, ) try: new_dist_is_zipped = False if os.path.isdir(egg_path): if egg_path.startswith(tmpdir): f, m = shutil.move, "Moving" else: f, m = shutil.copytree, "Copying" elif self.should_unzip(dist): self.mkpath(destination) f, m = self.unpack_and_compile, "Extracting" else: new_dist_is_zipped = True if egg_path.startswith(tmpdir): f, m = shutil.move, "Moving" else: f, m = shutil.copy2, "Copying" self.execute( f, (egg_path, destination), (m + " %s to %s") % ( os.path.basename(egg_path), os.path.dirname(destination) ), ) update_dist_caches( destination, fix_zipimporter_caches=new_dist_is_zipped, ) except Exception: update_dist_caches(destination, fix_zipimporter_caches=False) raise self.add_output(destination) return self.egg_distribution(destination) def install_exe(self, dist_filename, tmpdir): # See if it's valid, get data cfg = extract_wininst_cfg(dist_filename) if cfg is None: raise DistutilsError( "%s is not a valid distutils Windows .exe" % dist_filename ) # Create a dummy distribution object until we build the real distro dist = Distribution( None, project_name=cfg.get('metadata', 'name'), version=cfg.get('metadata', 'version'), platform=get_platform(), ) # Convert the .exe to an unpacked egg egg_path = os.path.join(tmpdir, dist.egg_name() + '.egg') dist.location = egg_path egg_tmp = egg_path + '.tmp' _egg_info = os.path.join(egg_tmp, 'EGG-INFO') pkg_inf = os.path.join(_egg_info, 'PKG-INFO') ensure_directory(pkg_inf) # make sure EGG-INFO dir exists dist._provider = PathMetadata(egg_tmp, _egg_info) # XXX self.exe_to_egg(dist_filename, egg_tmp) # Write EGG-INFO/PKG-INFO if not os.path.exists(pkg_inf): f = open(pkg_inf, 'w') f.write('Metadata-Version: 1.0\n') for k, v in cfg.items('metadata'): if k != 'target_version': f.write('%s: %s\n' % (k.replace('_', '-').title(), v)) f.close() script_dir = os.path.join(_egg_info, 'scripts') # delete entry-point scripts to avoid duping self.delete_blockers([ os.path.join(script_dir, args[0]) for args in ScriptWriter.get_args(dist) ]) # Build .egg file from tmpdir bdist_egg.make_zipfile( egg_path, egg_tmp, verbose=self.verbose, dry_run=self.dry_run, ) # install the .egg return self.install_egg(egg_path, tmpdir) def exe_to_egg(self, dist_filename, egg_tmp): """Extract a bdist_wininst to the directories an egg would use""" # Check for .pth file and set up prefix translations prefixes = get_exe_prefixes(dist_filename) to_compile = [] native_libs = [] top_level = {} def process(src, dst): s = src.lower() for old, new in prefixes: if s.startswith(old): src = new + src[len(old):] parts = src.split('/') dst = os.path.join(egg_tmp, *parts) dl = dst.lower() if dl.endswith('.pyd') or dl.endswith('.dll'): parts[-1] = bdist_egg.strip_module(parts[-1]) top_level[os.path.splitext(parts[0])[0]] = 1 native_libs.append(src) elif dl.endswith('.py') and old != 'SCRIPTS/': top_level[os.path.splitext(parts[0])[0]] = 1 to_compile.append(dst) return dst if not src.endswith('.pth'): log.warn("WARNING: can't process %s", src) return None # extract, tracking .pyd/.dll->native_libs and .py -> to_compile unpack_archive(dist_filename, egg_tmp, process) stubs = [] for res in native_libs: if res.lower().endswith('.pyd'): # create stubs for .pyd's parts = res.split('/') resource = parts[-1] parts[-1] = bdist_egg.strip_module(parts[-1]) + '.py' pyfile = os.path.join(egg_tmp, *parts) to_compile.append(pyfile) stubs.append(pyfile) bdist_egg.write_stub(resource, pyfile) self.byte_compile(to_compile) # compile .py's bdist_egg.write_safety_flag( os.path.join(egg_tmp, 'EGG-INFO'), bdist_egg.analyze_egg(egg_tmp, stubs)) # write zip-safety flag for name in 'top_level', 'native_libs': if locals()[name]: txt = os.path.join(egg_tmp, 'EGG-INFO', name + '.txt') if not os.path.exists(txt): f = open(txt, 'w') f.write('\n'.join(locals()[name]) + '\n') f.close() __mv_warning = textwrap.dedent(""" Because this distribution was installed --multi-version, before you can import modules from this package in an application, you will need to 'import pkg_resources' and then use a 'require()' call similar to one of these examples, in order to select the desired version: pkg_resources.require("%(name)s") # latest installed version pkg_resources.require("%(name)s==%(version)s") # this exact version pkg_resources.require("%(name)s>=%(version)s") # this version or higher """).lstrip() __id_warning = textwrap.dedent(""" Note also that the installation directory must be on sys.path at runtime for this to work. (e.g. by being the application's script directory, by being on PYTHONPATH, or by being added to sys.path by your code.) """) def installation_report(self, req, dist, what="Installed"): """Helpful installation message for display to package users""" msg = "\n%(what)s %(eggloc)s%(extras)s" if self.multi_version and not self.no_report: msg += '\n' + self.__mv_warning if self.install_dir not in map(normalize_path, sys.path): msg += '\n' + self.__id_warning eggloc = dist.location name = dist.project_name version = dist.version extras = '' # TODO: self.report_extras(req, dist) return msg % locals() __editable_msg = textwrap.dedent(""" Extracted editable version of %(spec)s to %(dirname)s If it uses setuptools in its setup script, you can activate it in "development" mode by going to that directory and running:: %(python)s setup.py develop See the setuptools documentation for the "develop" command for more info. """).lstrip() def report_editable(self, spec, setup_script): dirname = os.path.dirname(setup_script) python = sys.executable return '\n' + self.__editable_msg % locals() def run_setup(self, setup_script, setup_base, args): sys.modules.setdefault('distutils.command.bdist_egg', bdist_egg) sys.modules.setdefault('distutils.command.egg_info', egg_info) args = list(args) if self.verbose > 2: v = 'v' * (self.verbose - 1) args.insert(0, '-' + v) elif self.verbose < 2: args.insert(0, '-q') if self.dry_run: args.insert(0, '-n') log.info( "Running %s %s", setup_script[len(setup_base) + 1:], ' '.join(args) ) try: run_setup(setup_script, args) except SystemExit as v: raise DistutilsError("Setup script exited with %s" % (v.args[0],)) def build_and_install(self, setup_script, setup_base): args = ['bdist_egg', '--dist-dir'] dist_dir = tempfile.mkdtemp( prefix='egg-dist-tmp-', dir=os.path.dirname(setup_script) ) try: self._set_fetcher_options(os.path.dirname(setup_script)) args.append(dist_dir) self.run_setup(setup_script, setup_base, args) all_eggs = Environment([dist_dir]) eggs = [] for key in all_eggs: for dist in all_eggs[key]: eggs.append(self.install_egg(dist.location, setup_base)) if not eggs and not self.dry_run: log.warn("No eggs found in %s (setup script problem?)", dist_dir) return eggs finally: rmtree(dist_dir) log.set_verbosity(self.verbose) # restore our log verbosity def _set_fetcher_options(self, base): """ When easy_install is about to run bdist_egg on a source dist, that source dist might have 'setup_requires' directives, requiring additional fetching. Ensure the fetcher options given to easy_install are available to that command as well. """ # find the fetch options from easy_install and write them out # to the setup.cfg file. ei_opts = self.distribution.get_option_dict('easy_install').copy() fetch_directives = ( 'find_links', 'site_dirs', 'index_url', 'optimize', 'site_dirs', 'allow_hosts', ) fetch_options = {} for key, val in ei_opts.items(): if key not in fetch_directives: continue fetch_options[key.replace('_', '-')] = val[1] # create a settings dictionary suitable for `edit_config` settings = dict(easy_install=fetch_options) cfg_filename = os.path.join(base, 'setup.cfg') setopt.edit_config(cfg_filename, settings) def update_pth(self, dist): if self.pth_file is None: return for d in self.pth_file[dist.key]: # drop old entries if self.multi_version or d.location != dist.location: log.info("Removing %s from easy-install.pth file", d) self.pth_file.remove(d) if d.location in self.shadow_path: self.shadow_path.remove(d.location) if not self.multi_version: if dist.location in self.pth_file.paths: log.info( "%s is already the active version in easy-install.pth", dist, ) else: log.info("Adding %s to easy-install.pth file", dist) self.pth_file.add(dist) # add new entry if dist.location not in self.shadow_path: self.shadow_path.append(dist.location) if not self.dry_run: self.pth_file.save() if dist.key == 'setuptools': # Ensure that setuptools itself never becomes unavailable! # XXX should this check for latest version? filename = os.path.join(self.install_dir, 'setuptools.pth') if os.path.islink(filename): os.unlink(filename) f = open(filename, 'wt') f.write(self.pth_file.make_relative(dist.location) + '\n') f.close() def unpack_progress(self, src, dst): # Progress filter for unpacking log.debug("Unpacking %s to %s", src, dst) return dst # only unpack-and-compile skips files for dry run def unpack_and_compile(self, egg_path, destination): to_compile = [] to_chmod = [] def pf(src, dst): if dst.endswith('.py') and not src.startswith('EGG-INFO/'): to_compile.append(dst) elif dst.endswith('.dll') or dst.endswith('.so'): to_chmod.append(dst) self.unpack_progress(src, dst) return not self.dry_run and dst or None unpack_archive(egg_path, destination, pf) self.byte_compile(to_compile) if not self.dry_run: for f in to_chmod: mode = ((os.stat(f)[stat.ST_MODE]) | 0o555) & 0o7755 chmod(f, mode) def byte_compile(self, to_compile): if sys.dont_write_bytecode: self.warn('byte-compiling is disabled, skipping.') return from distutils.util import byte_compile try: # try to make the byte compile messages quieter log.set_verbosity(self.verbose - 1) byte_compile(to_compile, optimize=0, force=1, dry_run=self.dry_run) if self.optimize: byte_compile( to_compile, optimize=self.optimize, force=1, dry_run=self.dry_run, ) finally: log.set_verbosity(self.verbose) # restore original verbosity __no_default_msg = textwrap.dedent(""" bad install directory or PYTHONPATH You are attempting to install a package to a directory that is not on PYTHONPATH and which Python does not read ".pth" files from. The installation directory you specified (via --install-dir, --prefix, or the distutils default setting) was: %s and your PYTHONPATH environment variable currently contains: %r Here are some of your options for correcting the problem: * You can choose a different installation directory, i.e., one that is on PYTHONPATH or supports .pth files * You can add the installation directory to the PYTHONPATH environment variable. (It must then also be on PYTHONPATH whenever you run Python and want to use the package(s) you are installing.) * You can set up the installation directory to support ".pth" files by using one of the approaches described here: https://setuptools.readthedocs.io/en/latest/easy_install.html#custom-installation-locations Please make the appropriate changes for your system and try again.""").lstrip() def no_default_version_msg(self): template = self.__no_default_msg return template % (self.install_dir, os.environ.get('PYTHONPATH', '')) def install_site_py(self): """Make sure there's a site.py in the target dir, if needed""" if self.sitepy_installed: return # already did it, or don't need to sitepy = os.path.join(self.install_dir, "site.py") source = resource_string("setuptools", "site-patch.py") source = source.decode('utf-8') current = "" if os.path.exists(sitepy): log.debug("Checking existing site.py in %s", self.install_dir) with io.open(sitepy) as strm: current = strm.read() if not current.startswith('def __boot():'): raise DistutilsError( "%s is not a setuptools-generated site.py; please" " remove it." % sitepy ) if current != source: log.info("Creating %s", sitepy) if not self.dry_run: ensure_directory(sitepy) with io.open(sitepy, 'w', encoding='utf-8') as strm: strm.write(source) self.byte_compile([sitepy]) self.sitepy_installed = True def create_home_path(self): """Create directories under ~.""" if not self.user: return home = convert_path(os.path.expanduser("~")) for name, path in six.iteritems(self.config_vars): if path.startswith(home) and not os.path.isdir(path): self.debug_print("os.makedirs('%s', 0o700)" % path) os.makedirs(path, 0o700) INSTALL_SCHEMES = dict( posix=dict( install_dir='$base/lib/python$py_version_short/site-packages', script_dir='$base/bin', ), ) DEFAULT_SCHEME = dict( install_dir='$base/Lib/site-packages', script_dir='$base/Scripts', ) def _expand(self, *attrs): config_vars = self.get_finalized_command('install').config_vars if self.prefix: # Set default install_dir/scripts from --prefix config_vars = config_vars.copy() config_vars['base'] = self.prefix scheme = self.INSTALL_SCHEMES.get(os.name, self.DEFAULT_SCHEME) for attr, val in scheme.items(): if getattr(self, attr, None) is None: setattr(self, attr, val) from distutils.util import subst_vars for attr in attrs: val = getattr(self, attr) if val is not None: val = subst_vars(val, config_vars) if os.name == 'posix': val = os.path.expanduser(val) setattr(self, attr, val) def _pythonpath(): items = os.environ.get('PYTHONPATH', '').split(os.pathsep) return filter(None, items) def get_site_dirs(): """ Return a list of 'site' dirs """ sitedirs = [] # start with PYTHONPATH sitedirs.extend(_pythonpath()) prefixes = [sys.prefix] if sys.exec_prefix != sys.prefix: prefixes.append(sys.exec_prefix) for prefix in prefixes: if prefix: if sys.platform in ('os2emx', 'riscos'): sitedirs.append(os.path.join(prefix, "Lib", "site-packages")) elif os.sep == '/': sitedirs.extend([ os.path.join( prefix, "lib", "python" + sys.version[:3], "site-packages", ), os.path.join(prefix, "lib", "site-python"), ]) else: sitedirs.extend([ prefix, os.path.join(prefix, "lib", "site-packages"), ]) if sys.platform == 'darwin': # for framework builds *only* we add the standard Apple # locations. Currently only per-user, but /Library and # /Network/Library could be added too if 'Python.framework' in prefix: home = os.environ.get('HOME') if home: home_sp = os.path.join( home, 'Library', 'Python', sys.version[:3], 'site-packages', ) sitedirs.append(home_sp) lib_paths = get_path('purelib'), get_path('platlib') for site_lib in lib_paths: if site_lib not in sitedirs: sitedirs.append(site_lib) if site.ENABLE_USER_SITE: sitedirs.append(site.USER_SITE) try: sitedirs.extend(site.getsitepackages()) except AttributeError: pass sitedirs = list(map(normalize_path, sitedirs)) return sitedirs def expand_paths(inputs): """Yield sys.path directories that might contain "old-style" packages""" seen = {} for dirname in inputs: dirname = normalize_path(dirname) if dirname in seen: continue seen[dirname] = 1 if not os.path.isdir(dirname): continue files = os.listdir(dirname) yield dirname, files for name in files: if not name.endswith('.pth'): # We only care about the .pth files continue if name in ('easy-install.pth', 'setuptools.pth'): # Ignore .pth files that we control continue # Read the .pth file f = open(os.path.join(dirname, name)) lines = list(yield_lines(f)) f.close() # Yield existing non-dupe, non-import directory lines from it for line in lines: if not line.startswith("import"): line = normalize_path(line.rstrip()) if line not in seen: seen[line] = 1 if not os.path.isdir(line): continue yield line, os.listdir(line) def extract_wininst_cfg(dist_filename): """Extract configuration data from a bdist_wininst .exe Returns a configparser.RawConfigParser, or None """ f = open(dist_filename, 'rb') try: endrec = zipfile._EndRecData(f) if endrec is None: return None prepended = (endrec[9] - endrec[5]) - endrec[6] if prepended < 12: # no wininst data here return None f.seek(prepended - 12) tag, cfglen, bmlen = struct.unpack("<iii", f.read(12)) if tag not in (0x1234567A, 0x1234567B): return None # not a valid tag f.seek(prepended - (12 + cfglen)) init = {'version': '', 'target_version': ''} cfg = configparser.RawConfigParser(init) try: part = f.read(cfglen) # Read up to the first null byte. config = part.split(b'\0', 1)[0] # Now the config is in bytes, but for RawConfigParser, it should # be text, so decode it. config = config.decode(sys.getfilesystemencoding()) cfg.readfp(six.StringIO(config)) except configparser.Error: return None if not cfg.has_section('metadata') or not cfg.has_section('Setup'): return None return cfg finally: f.close() def get_exe_prefixes(exe_filename): """Get exe->egg path translations for a given .exe file""" prefixes = [ ('PURELIB/', ''), ('PLATLIB/pywin32_system32', ''), ('PLATLIB/', ''), ('SCRIPTS/', 'EGG-INFO/scripts/'), ('DATA/lib/site-packages', ''), ] z = zipfile.ZipFile(exe_filename) try: for info in z.infolist(): name = info.filename parts = name.split('/') if len(parts) == 3 and parts[2] == 'PKG-INFO': if parts[1].endswith('.egg-info'): prefixes.insert(0, ('/'.join(parts[:2]), 'EGG-INFO/')) break if len(parts) != 2 or not name.endswith('.pth'): continue if name.endswith('-nspkg.pth'): continue if parts[0].upper() in ('PURELIB', 'PLATLIB'): contents = z.read(name) if six.PY3: contents = contents.decode() for pth in yield_lines(contents): pth = pth.strip().replace('\\', '/') if not pth.startswith('import'): prefixes.append((('%s/%s/' % (parts[0], pth)), '')) finally: z.close() prefixes = [(x.lower(), y) for x, y in prefixes] prefixes.sort() prefixes.reverse() return prefixes class PthDistributions(Environment): """A .pth file with Distribution paths in it""" dirty = False def __init__(self, filename, sitedirs=()): self.filename = filename self.sitedirs = list(map(normalize_path, sitedirs)) self.basedir = normalize_path(os.path.dirname(self.filename)) self._load() Environment.__init__(self, [], None, None) for path in yield_lines(self.paths): list(map(self.add, find_distributions(path, True))) def _load(self): self.paths = [] saw_import = False seen = dict.fromkeys(self.sitedirs) if os.path.isfile(self.filename): f = open(self.filename, 'rt') for line in f: if line.startswith('import'): saw_import = True continue path = line.rstrip() self.paths.append(path) if not path.strip() or path.strip().startswith('#'): continue # skip non-existent paths, in case somebody deleted a package # manually, and duplicate paths as well path = self.paths[-1] = normalize_path( os.path.join(self.basedir, path) ) if not os.path.exists(path) or path in seen: self.paths.pop() # skip it self.dirty = True # we cleaned up, so we're dirty now :) continue seen[path] = 1 f.close() if self.paths and not saw_import: self.dirty = True # ensure anything we touch has import wrappers while self.paths and not self.paths[-1].strip(): self.paths.pop() def save(self): """Write changed .pth file back to disk""" if not self.dirty: return rel_paths = list(map(self.make_relative, self.paths)) if rel_paths: log.debug("Saving %s", self.filename) lines = self._wrap_lines(rel_paths) data = '\n'.join(lines) + '\n' if os.path.islink(self.filename): os.unlink(self.filename) with open(self.filename, 'wt') as f: f.write(data) elif os.path.exists(self.filename): log.debug("Deleting empty %s", self.filename) os.unlink(self.filename) self.dirty = False @staticmethod def _wrap_lines(lines): return lines def add(self, dist): """Add `dist` to the distribution map""" new_path = ( dist.location not in self.paths and ( dist.location not in self.sitedirs or # account for '.' being in PYTHONPATH dist.location == os.getcwd() ) ) if new_path: self.paths.append(dist.location) self.dirty = True Environment.add(self, dist) def remove(self, dist): """Remove `dist` from the distribution map""" while dist.location in self.paths: self.paths.remove(dist.location) self.dirty = True Environment.remove(self, dist) def make_relative(self, path): npath, last = os.path.split(normalize_path(path)) baselen = len(self.basedir) parts = [last] sep = os.altsep == '/' and '/' or os.sep while len(npath) >= baselen: if npath == self.basedir: parts.append(os.curdir) parts.reverse() return sep.join(parts) npath, last = os.path.split(npath) parts.append(last) else: return path class RewritePthDistributions(PthDistributions): @classmethod def _wrap_lines(cls, lines): yield cls.prelude for line in lines: yield line yield cls.postlude prelude = _one_liner(""" import sys sys.__plen = len(sys.path) """) postlude = _one_liner(""" import sys new = sys.path[sys.__plen:] del sys.path[sys.__plen:] p = getattr(sys, '__egginsert', 0) sys.path[p:p] = new sys.__egginsert = p + len(new) """) if os.environ.get('SETUPTOOLS_SYS_PATH_TECHNIQUE', 'raw') == 'rewrite': PthDistributions = RewritePthDistributions def _first_line_re(): """ Return a regular expression based on first_line_re suitable for matching strings. """ if isinstance(first_line_re.pattern, str): return first_line_re # first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern. return re.compile(first_line_re.pattern.decode()) def auto_chmod(func, arg, exc): if func in [os.unlink, os.remove] and os.name == 'nt': chmod(arg, stat.S_IWRITE) return func(arg) et, ev, _ = sys.exc_info() six.reraise(et, (ev[0], ev[1] + (" %s %s" % (func, arg)))) def update_dist_caches(dist_path, fix_zipimporter_caches): """ Fix any globally cached `dist_path` related data `dist_path` should be a path of a newly installed egg distribution (zipped or unzipped). sys.path_importer_cache contains finder objects that have been cached when importing data from the original distribution. Any such finders need to be cleared since the replacement distribution might be packaged differently, e.g. a zipped egg distribution might get replaced with an unzipped egg folder or vice versa. Having the old finders cached may then cause Python to attempt loading modules from the replacement distribution using an incorrect loader. zipimport.zipimporter objects are Python loaders charged with importing data packaged inside zip archives. If stale loaders referencing the original distribution, are left behind, they can fail to load modules from the replacement distribution. E.g. if an old zipimport.zipimporter instance is used to load data from a new zipped egg archive, it may cause the operation to attempt to locate the requested data in the wrong location - one indicated by the original distribution's zip archive directory information. Such an operation may then fail outright, e.g. report having read a 'bad local file header', or even worse, it may fail silently & return invalid data. zipimport._zip_directory_cache contains cached zip archive directory information for all existing zipimport.zipimporter instances and all such instances connected to the same archive share the same cached directory information. If asked, and the underlying Python implementation allows it, we can fix all existing zipimport.zipimporter instances instead of having to track them down and remove them one by one, by updating their shared cached zip archive directory information. This, of course, assumes that the replacement distribution is packaged as a zipped egg. If not asked to fix existing zipimport.zipimporter instances, we still do our best to clear any remaining zipimport.zipimporter related cached data that might somehow later get used when attempting to load data from the new distribution and thus cause such load operations to fail. Note that when tracking down such remaining stale data, we can not catch every conceivable usage from here, and we clear only those that we know of and have found to cause problems if left alive. Any remaining caches should be updated by whomever is in charge of maintaining them, i.e. they should be ready to handle us replacing their zip archives with new distributions at runtime. """ # There are several other known sources of stale zipimport.zipimporter # instances that we do not clear here, but might if ever given a reason to # do so: # * Global setuptools pkg_resources.working_set (a.k.a. 'master working # set') may contain distributions which may in turn contain their # zipimport.zipimporter loaders. # * Several zipimport.zipimporter loaders held by local variables further # up the function call stack when running the setuptools installation. # * Already loaded modules may have their __loader__ attribute set to the # exact loader instance used when importing them. Python 3.4 docs state # that this information is intended mostly for introspection and so is # not expected to cause us problems. normalized_path = normalize_path(dist_path) _uncache(normalized_path, sys.path_importer_cache) if fix_zipimporter_caches: _replace_zip_directory_cache_data(normalized_path) else: # Here, even though we do not want to fix existing and now stale # zipimporter cache information, we still want to remove it. Related to # Python's zip archive directory information cache, we clear each of # its stale entries in two phases: # 1. Clear the entry so attempting to access zip archive information # via any existing stale zipimport.zipimporter instances fails. # 2. Remove the entry from the cache so any newly constructed # zipimport.zipimporter instances do not end up using old stale # zip archive directory information. # This whole stale data removal step does not seem strictly necessary, # but has been left in because it was done before we started replacing # the zip archive directory information cache content if possible, and # there are no relevant unit tests that we can depend on to tell us if # this is really needed. _remove_and_clear_zip_directory_cache_data(normalized_path) def _collect_zipimporter_cache_entries(normalized_path, cache): """ Return zipimporter cache entry keys related to a given normalized path. Alternative path spellings (e.g. those using different character case or those using alternative path separators) related to the same path are included. Any sub-path entries are included as well, i.e. those corresponding to zip archives embedded in other zip archives. """ result = [] prefix_len = len(normalized_path) for p in cache: np = normalize_path(p) if (np.startswith(normalized_path) and np[prefix_len:prefix_len + 1] in (os.sep, '')): result.append(p) return result def _update_zipimporter_cache(normalized_path, cache, updater=None): """ Update zipimporter cache data for a given normalized path. Any sub-path entries are processed as well, i.e. those corresponding to zip archives embedded in other zip archives. Given updater is a callable taking a cache entry key and the original entry (after already removing the entry from the cache), and expected to update the entry and possibly return a new one to be inserted in its place. Returning None indicates that the entry should not be replaced with a new one. If no updater is given, the cache entries are simply removed without any additional processing, the same as if the updater simply returned None. """ for p in _collect_zipimporter_cache_entries(normalized_path, cache): # N.B. pypy's custom zipimport._zip_directory_cache implementation does # not support the complete dict interface: # * Does not support item assignment, thus not allowing this function # to be used only for removing existing cache entries. # * Does not support the dict.pop() method, forcing us to use the # get/del patterns instead. For more detailed information see the # following links: # https://github.com/pypa/setuptools/issues/202#issuecomment-202913420 # https://bitbucket.org/pypy/pypy/src/dd07756a34a41f674c0cacfbc8ae1d4cc9ea2ae4/pypy/module/zipimport/interp_zipimport.py#cl-99 old_entry = cache[p] del cache[p] new_entry = updater and updater(p, old_entry) if new_entry is not None: cache[p] = new_entry def _uncache(normalized_path, cache): _update_zipimporter_cache(normalized_path, cache) def _remove_and_clear_zip_directory_cache_data(normalized_path): def clear_and_remove_cached_zip_archive_directory_data(path, old_entry): old_entry.clear() _update_zipimporter_cache( normalized_path, zipimport._zip_directory_cache, updater=clear_and_remove_cached_zip_archive_directory_data) # PyPy Python implementation does not allow directly writing to the # zipimport._zip_directory_cache and so prevents us from attempting to correct # its content. The best we can do there is clear the problematic cache content # and have PyPy repopulate it as needed. The downside is that if there are any # stale zipimport.zipimporter instances laying around, attempting to use them # will fail due to not having its zip archive directory information available # instead of being automatically corrected to use the new correct zip archive # directory information. if '__pypy__' in sys.builtin_module_names: _replace_zip_directory_cache_data = \ _remove_and_clear_zip_directory_cache_data else: def _replace_zip_directory_cache_data(normalized_path): def replace_cached_zip_archive_directory_data(path, old_entry): # N.B. In theory, we could load the zip directory information just # once for all updated path spellings, and then copy it locally and # update its contained path strings to contain the correct # spelling, but that seems like a way too invasive move (this cache # structure is not officially documented anywhere and could in # theory change with new Python releases) for no significant # benefit. old_entry.clear() zipimport.zipimporter(path) old_entry.update(zipimport._zip_directory_cache[path]) return old_entry _update_zipimporter_cache( normalized_path, zipimport._zip_directory_cache, updater=replace_cached_zip_archive_directory_data) def is_python(text, filename='<string>'): "Is this string a valid Python script?" try: compile(text, filename, 'exec') except (SyntaxError, TypeError): return False else: return True def is_sh(executable): """Determine if the specified executable is a .sh (contains a #! line)""" try: with io.open(executable, encoding='latin-1') as fp: magic = fp.read(2) except (OSError, IOError): return executable return magic == '#!' def nt_quote_arg(arg): """Quote a command line argument according to Windows parsing rules""" return subprocess.list2cmdline([arg]) def is_python_script(script_text, filename): """Is this text, as a whole, a Python script? (as opposed to shell/bat/etc. """ if filename.endswith('.py') or filename.endswith('.pyw'): return True # extension says it's Python if is_python(script_text, filename): return True # it's syntactically valid Python if script_text.startswith('#!'): # It begins with a '#!' line, so check if 'python' is in it somewhere return 'python' in script_text.splitlines()[0].lower() return False # Not any Python I can recognize try: from os import chmod as _chmod except ImportError: # Jython compatibility def _chmod(*args): pass def chmod(path, mode): log.debug("changing mode of %s to %o", path, mode) try: _chmod(path, mode) except os.error as e: log.debug("chmod failed: %s", e) class CommandSpec(list): """ A command spec for a #! header, specified as a list of arguments akin to those passed to Popen. """ options = [] split_args = dict() @classmethod def best(cls): """ Choose the best CommandSpec class based on environmental conditions. """ return cls @classmethod def _sys_executable(cls): _default = os.path.normpath(sys.executable) return os.environ.get('__PYVENV_LAUNCHER__', _default) @classmethod def from_param(cls, param): """ Construct a CommandSpec from a parameter to build_scripts, which may be None. """ if isinstance(param, cls): return param if isinstance(param, list): return cls(param) if param is None: return cls.from_environment() # otherwise, assume it's a string. return cls.from_string(param) @classmethod def from_environment(cls): return cls([cls._sys_executable()]) @classmethod def from_string(cls, string): """ Construct a command spec from a simple string representing a command line parseable by shlex.split. """ items = shlex.split(string, **cls.split_args) return cls(items) def install_options(self, script_text): self.options = shlex.split(self._extract_options(script_text)) cmdline = subprocess.list2cmdline(self) if not isascii(cmdline): self.options[:0] = ['-x'] @staticmethod def _extract_options(orig_script): """ Extract any options from the first line of the script. """ first = (orig_script + '\n').splitlines()[0] match = _first_line_re().match(first) options = match.group(1) or '' if match else '' return options.strip() def as_header(self): return self._render(self + list(self.options)) @staticmethod def _strip_quotes(item): _QUOTES = '"\'' for q in _QUOTES: if item.startswith(q) and item.endswith(q): return item[1:-1] return item @staticmethod def _render(items): cmdline = subprocess.list2cmdline( CommandSpec._strip_quotes(item.strip()) for item in items) return '#!' + cmdline + '\n' # For pbr compat; will be removed in a future version. sys_executable = CommandSpec._sys_executable() class WindowsCommandSpec(CommandSpec): split_args = dict(posix=False) class ScriptWriter(object): """ Encapsulates behavior around writing entry point scripts for console and gui apps. """ template = textwrap.dedent(r""" # EASY-INSTALL-ENTRY-SCRIPT: %(spec)r,%(group)r,%(name)r __requires__ = %(spec)r import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit( load_entry_point(%(spec)r, %(group)r, %(name)r)() ) """).lstrip() command_spec_class = CommandSpec @classmethod def get_script_args(cls, dist, executable=None, wininst=False): # for backward compatibility warnings.warn("Use get_args", DeprecationWarning) writer = (WindowsScriptWriter if wininst else ScriptWriter).best() header = cls.get_script_header("", executable, wininst) return writer.get_args(dist, header) @classmethod def get_script_header(cls, script_text, executable=None, wininst=False): # for backward compatibility warnings.warn("Use get_header", DeprecationWarning) if wininst: executable = "python.exe" cmd = cls.command_spec_class.best().from_param(executable) cmd.install_options(script_text) return cmd.as_header() @classmethod def get_args(cls, dist, header=None): """ Yield write_script() argument tuples for a distribution's console_scripts and gui_scripts entry points. """ if header is None: header = cls.get_header() spec = str(dist.as_requirement()) for type_ in 'console', 'gui': group = type_ + '_scripts' for name, ep in dist.get_entry_map(group).items(): cls._ensure_safe_name(name) script_text = cls.template % locals() args = cls._get_script_args(type_, name, header, script_text) for res in args: yield res @staticmethod def _ensure_safe_name(name): """ Prevent paths in *_scripts entry point names. """ has_path_sep = re.search(r'[\\/]', name) if has_path_sep: raise ValueError("Path separators not allowed in script names") @classmethod def get_writer(cls, force_windows): # for backward compatibility warnings.warn("Use best", DeprecationWarning) return WindowsScriptWriter.best() if force_windows else cls.best() @classmethod def best(cls): """ Select the best ScriptWriter for this environment. """ if sys.platform == 'win32' or (os.name == 'java' and os._name == 'nt'): return WindowsScriptWriter.best() else: return cls @classmethod def _get_script_args(cls, type_, name, header, script_text): # Simply write the stub with no extension. yield (name, header + script_text) @classmethod def get_header(cls, script_text="", executable=None): """Create a #! line, getting options (if any) from script_text""" cmd = cls.command_spec_class.best().from_param(executable) cmd.install_options(script_text) return cmd.as_header() class WindowsScriptWriter(ScriptWriter): command_spec_class = WindowsCommandSpec @classmethod def get_writer(cls): # for backward compatibility warnings.warn("Use best", DeprecationWarning) return cls.best() @classmethod def best(cls): """ Select the best ScriptWriter suitable for Windows """ writer_lookup = dict( executable=WindowsExecutableLauncherWriter, natural=cls, ) # for compatibility, use the executable launcher by default launcher = os.environ.get('SETUPTOOLS_LAUNCHER', 'executable') return writer_lookup[launcher] @classmethod def _get_script_args(cls, type_, name, header, script_text): "For Windows, add a .py extension" ext = dict(console='.pya', gui='.pyw')[type_] if ext not in os.environ['PATHEXT'].lower().split(';'): msg = ( "{ext} not listed in PATHEXT; scripts will not be " "recognized as executables." ).format(**locals()) warnings.warn(msg, UserWarning) old = ['.pya', '.py', '-script.py', '.pyc', '.pyo', '.pyw', '.exe'] old.remove(ext) header = cls._adjust_header(type_, header) blockers = [name + x for x in old] yield name + ext, header + script_text, 't', blockers @classmethod def _adjust_header(cls, type_, orig_header): """ Make sure 'pythonw' is used for gui and and 'python' is used for console (regardless of what sys.executable is). """ pattern = 'pythonw.exe' repl = 'python.exe' if type_ == 'gui': pattern, repl = repl, pattern pattern_ob = re.compile(re.escape(pattern), re.IGNORECASE) new_header = pattern_ob.sub(string=orig_header, repl=repl) return new_header if cls._use_header(new_header) else orig_header @staticmethod def _use_header(new_header): """ Should _adjust_header use the replaced header? On non-windows systems, always use. On Windows systems, only use the replaced header if it resolves to an executable on the system. """ clean_header = new_header[2:-1].strip('"') return sys.platform != 'win32' or find_executable(clean_header) class WindowsExecutableLauncherWriter(WindowsScriptWriter): @classmethod def _get_script_args(cls, type_, name, header, script_text): """ For Windows, add a .py extension and an .exe launcher """ if type_ == 'gui': launcher_type = 'gui' ext = '-script.pyw' old = ['.pyw'] else: launcher_type = 'cli' ext = '-script.py' old = ['.py', '.pyc', '.pyo'] hdr = cls._adjust_header(type_, header) blockers = [name + x for x in old] yield (name + ext, hdr + script_text, 't', blockers) yield ( name + '.exe', get_win_launcher(launcher_type), 'b' # write in binary mode ) if not is_64bit(): # install a manifest for the launcher to prevent Windows # from detecting it as an installer (which it will for # launchers like easy_install.exe). Consider only # adding a manifest for launchers detected as installers. # See Distribute #143 for details. m_name = name + '.exe.manifest' yield (m_name, load_launcher_manifest(name), 't') # for backward-compatibility get_script_args = ScriptWriter.get_script_args get_script_header = ScriptWriter.get_script_header def get_win_launcher(type): """ Load the Windows launcher (executable) suitable for launching a script. `type` should be either 'cli' or 'gui' Returns the executable as a byte string. """ launcher_fn = '%s.exe' % type if is_64bit(): launcher_fn = launcher_fn.replace(".", "-64.") else: launcher_fn = launcher_fn.replace(".", "-32.") return resource_string('setuptools', launcher_fn) def load_launcher_manifest(name): manifest = pkg_resources.resource_string(__name__, 'launcher manifest.xml') if six.PY2: return manifest % vars() else: return manifest.decode('utf-8') % vars() def rmtree(path, ignore_errors=False, onerror=auto_chmod): return shutil.rmtree(path, ignore_errors, onerror) def current_umask(): tmp = os.umask(0o022) os.umask(tmp) return tmp def bootstrap(): # This function is called when setuptools*.egg is run using /bin/sh import setuptools argv0 = os.path.dirname(setuptools.__path__[0]) sys.argv[0] = argv0 sys.argv.append(argv0) main() def main(argv=None, **kw): from setuptools import setup from setuptools.dist import Distribution class DistributionWithoutHelpCommands(Distribution): common_usage = "" def _show_help(self, *args, **kw): with _patch_usage(): Distribution._show_help(self, *args, **kw) if argv is None: argv = sys.argv[1:] with _patch_usage(): setup( script_args=['-q', 'easy_install', '-v'] + argv, script_name=sys.argv[0] or 'easy_install', distclass=DistributionWithoutHelpCommands, **kw ) @contextlib.contextmanager def _patch_usage(): import distutils.core USAGE = textwrap.dedent(""" usage: %(script)s [options] requirement_or_url ... or: %(script)s --help """).lstrip() def gen_usage(script_name): return USAGE % dict( script=os.path.basename(script_name), ) saved = distutils.core.gen_usage distutils.core.gen_usage = gen_usage try: yield finally: distutils.core.gen_usage = saved
Omegaphora/external_chromium-trace
refs/heads/lp5.1
trace-viewer/third_party/closure_linter/closure_linter/errorrecord.py
135
#!/usr/bin/env python # Copyright 2012 The Closure Linter 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. """A simple, pickle-serializable class to represent a lint error.""" import gflags as flags from closure_linter import errors from closure_linter.common import erroroutput FLAGS = flags.FLAGS class ErrorRecord(object): """Record-keeping struct that can be serialized back from a process. Attributes: path: Path to the file. error_string: Error string for the user. new_error: Whether this is a "new error" (see errors.NEW_ERRORS). """ def __init__(self, path, error_string, new_error): self.path = path self.error_string = error_string self.new_error = new_error def MakeErrorRecord(path, error): """Make an error record with correctly formatted error string. Errors are not able to be serialized (pickled) over processes because of their pointers to the complex token/context graph. We use an intermediary serializable class to pass back just the relevant information. Args: path: Path of file the error was found in. error: An error.Error instance. Returns: _ErrorRecord instance. """ new_error = error.code in errors.NEW_ERRORS if FLAGS.unix_mode: error_string = erroroutput.GetUnixErrorOutput(path, error, new_error) else: error_string = erroroutput.GetErrorOutput(error, new_error) return ErrorRecord(path, error_string, new_error)
ehashman/oh-mainline
refs/heads/master
vendor/packages/PyYaml/tests/lib3/test_constructor.py
57
import yaml import pprint import datetime import yaml.tokens def execute(code): global value exec(code) return value def _make_objects(): global MyLoader, MyDumper, MyTestClass1, MyTestClass2, MyTestClass3, YAMLObject1, YAMLObject2, \ AnObject, AnInstance, AState, ACustomState, InitArgs, InitArgsWithState, \ NewArgs, NewArgsWithState, Reduce, ReduceWithState, MyInt, MyList, MyDict, \ FixedOffset, today, execute class MyLoader(yaml.Loader): pass class MyDumper(yaml.Dumper): pass class MyTestClass1: def __init__(self, x, y=0, z=0): self.x = x self.y = y self.z = z def __eq__(self, other): if isinstance(other, MyTestClass1): return self.__class__, self.__dict__ == other.__class__, other.__dict__ else: return False def construct1(constructor, node): mapping = constructor.construct_mapping(node) return MyTestClass1(**mapping) def represent1(representer, native): return representer.represent_mapping("!tag1", native.__dict__) yaml.add_constructor("!tag1", construct1, Loader=MyLoader) yaml.add_representer(MyTestClass1, represent1, Dumper=MyDumper) class MyTestClass2(MyTestClass1, yaml.YAMLObject): yaml_loader = MyLoader yaml_dumper = MyDumper yaml_tag = "!tag2" def from_yaml(cls, constructor, node): x = constructor.construct_yaml_int(node) return cls(x=x) from_yaml = classmethod(from_yaml) def to_yaml(cls, representer, native): return representer.represent_scalar(cls.yaml_tag, str(native.x)) to_yaml = classmethod(to_yaml) class MyTestClass3(MyTestClass2): yaml_tag = "!tag3" def from_yaml(cls, constructor, node): mapping = constructor.construct_mapping(node) if '=' in mapping: x = mapping['='] del mapping['='] mapping['x'] = x return cls(**mapping) from_yaml = classmethod(from_yaml) def to_yaml(cls, representer, native): return representer.represent_mapping(cls.yaml_tag, native.__dict__) to_yaml = classmethod(to_yaml) class YAMLObject1(yaml.YAMLObject): yaml_loader = MyLoader yaml_dumper = MyDumper yaml_tag = '!foo' def __init__(self, my_parameter=None, my_another_parameter=None): self.my_parameter = my_parameter self.my_another_parameter = my_another_parameter def __eq__(self, other): if isinstance(other, YAMLObject1): return self.__class__, self.__dict__ == other.__class__, other.__dict__ else: return False class YAMLObject2(yaml.YAMLObject): yaml_loader = MyLoader yaml_dumper = MyDumper yaml_tag = '!bar' def __init__(self, foo=1, bar=2, baz=3): self.foo = foo self.bar = bar self.baz = baz def __getstate__(self): return {1: self.foo, 2: self.bar, 3: self.baz} def __setstate__(self, state): self.foo = state[1] self.bar = state[2] self.baz = state[3] def __eq__(self, other): if isinstance(other, YAMLObject2): return self.__class__, self.__dict__ == other.__class__, other.__dict__ else: return False class AnObject: def __new__(cls, foo=None, bar=None, baz=None): self = object.__new__(cls) self.foo = foo self.bar = bar self.baz = baz return self def __cmp__(self, other): return cmp((type(self), self.foo, self.bar, self.baz), (type(other), other.foo, other.bar, other.baz)) def __eq__(self, other): return type(self) is type(other) and \ (self.foo, self.bar, self.baz) == (other.foo, other.bar, other.baz) class AnInstance: def __init__(self, foo=None, bar=None, baz=None): self.foo = foo self.bar = bar self.baz = baz def __cmp__(self, other): return cmp((type(self), self.foo, self.bar, self.baz), (type(other), other.foo, other.bar, other.baz)) def __eq__(self, other): return type(self) is type(other) and \ (self.foo, self.bar, self.baz) == (other.foo, other.bar, other.baz) class AState(AnInstance): def __getstate__(self): return { '_foo': self.foo, '_bar': self.bar, '_baz': self.baz, } def __setstate__(self, state): self.foo = state['_foo'] self.bar = state['_bar'] self.baz = state['_baz'] class ACustomState(AnInstance): def __getstate__(self): return (self.foo, self.bar, self.baz) def __setstate__(self, state): self.foo, self.bar, self.baz = state class NewArgs(AnObject): def __getnewargs__(self): return (self.foo, self.bar, self.baz) def __getstate__(self): return {} class NewArgsWithState(AnObject): def __getnewargs__(self): return (self.foo, self.bar) def __getstate__(self): return self.baz def __setstate__(self, state): self.baz = state InitArgs = NewArgs InitArgsWithState = NewArgsWithState class Reduce(AnObject): def __reduce__(self): return self.__class__, (self.foo, self.bar, self.baz) class ReduceWithState(AnObject): def __reduce__(self): return self.__class__, (self.foo, self.bar), self.baz def __setstate__(self, state): self.baz = state class MyInt(int): def __eq__(self, other): return type(self) is type(other) and int(self) == int(other) class MyList(list): def __init__(self, n=1): self.extend([None]*n) def __eq__(self, other): return type(self) is type(other) and list(self) == list(other) class MyDict(dict): def __init__(self, n=1): for k in range(n): self[k] = None def __eq__(self, other): return type(self) is type(other) and dict(self) == dict(other) class FixedOffset(datetime.tzinfo): def __init__(self, offset, name): self.__offset = datetime.timedelta(minutes=offset) self.__name = name def utcoffset(self, dt): return self.__offset def tzname(self, dt): return self.__name def dst(self, dt): return datetime.timedelta(0) today = datetime.date.today() def _load_code(expression): return eval(expression) def _serialize_value(data): if isinstance(data, list): return '[%s]' % ', '.join(map(_serialize_value, data)) elif isinstance(data, dict): items = [] for key, value in data.items(): key = _serialize_value(key) value = _serialize_value(value) items.append("%s: %s" % (key, value)) items.sort() return '{%s}' % ', '.join(items) elif isinstance(data, datetime.datetime): return repr(data.utctimetuple()) elif isinstance(data, float) and data != data: return '?' else: return str(data) def test_constructor_types(data_filename, code_filename, verbose=False): _make_objects() native1 = None native2 = None try: native1 = list(yaml.load_all(open(data_filename, 'rb'), Loader=MyLoader)) if len(native1) == 1: native1 = native1[0] native2 = _load_code(open(code_filename, 'rb').read()) try: if native1 == native2: return except TypeError: pass if verbose: print("SERIALIZED NATIVE1:") print(_serialize_value(native1)) print("SERIALIZED NATIVE2:") print(_serialize_value(native2)) assert _serialize_value(native1) == _serialize_value(native2), (native1, native2) finally: if verbose: print("NATIVE1:") pprint.pprint(native1) print("NATIVE2:") pprint.pprint(native2) test_constructor_types.unittest = ['.data', '.code'] if __name__ == '__main__': import sys, test_constructor sys.modules['test_constructor'] = sys.modules['__main__'] import test_appliance test_appliance.run(globals())
jagguli/intellij-community
refs/heads/master
python/testData/inspections/PyUnresolvedReferencesInspection/unusedUnresolvedModuleImported.py
68
<warning descr="Unused import statement">import <error descr="No module named spam">spam</error></warning>
jfindleyderegt/au_trap
refs/heads/master
test_threshold.py
1
import os, glob, cv2 import numpy as np import pylab im_simple = '/home/faedrus/Documents/au_trap/20141031/1414763725.88.png' im_complex = '/home/faedrus/Documents/au_trap/20141031/1414769658.04.png' img = cv2.imread(im_complex, 0) (height, width) = img.shape ret,thresh1 = cv2.threshold(img, 127, 255,cv2.THRESH_BINARY) ret,thresh2 = cv2.threshold(img, 127, 255,cv2.THRESH_BINARY_INV) ret,thresh3 = cv2.threshold(img, 127, 255,cv2.THRESH_TRUNC) ret,thresh4 = cv2.threshold(img, 127, 255,cv2.THRESH_TOZERO) ret,thresh5 = cv2.threshold(img, 127, 255,cv2.THRESH_TOZERO_INV) cv2.namedWindow('original', cv2.WINDOW_NORMAL) cv2.namedWindow('thresh_binary', cv2.WINDOW_NORMAL) cv2.namedWindow('thresh_binary_inv', cv2.WINDOW_NORMAL) cv2.namedWindow('thresh_trunc', cv2.WINDOW_NORMAL) cv2.namedWindow('thresh_tozero', cv2.WINDOW_NORMAL) cv2.namedWindow('thresh_tozero_inv', cv2.WINDOW_NORMAL) cv2.imshow('original', img) cv2.imshow('thresh_binary', thresh1) cv2.imshow('thresh_binary_inv', thresh2) cv2.imshow('thresh_trunc', thresh3) cv2.imshow('thresh_tozero', thresh4) cv2.imshow('thresh_tozero_inv', thresh5) cv2.waitKey(0) cv2.destroyAllWindows()
agaldona/odoo-addons
refs/heads/master
stock_visible_cost/models/res_config.py
4
# -*- encoding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models, fields class StockConfigSettings(models.TransientModel): _inherit = 'stock.config.settings' group_stock_visible_cost = fields.Boolean( string='Make visible costs in stock', implied_group='stock_visible_cost.group_visible_cost', help='Checking this will show cost in some stock objects')
andyfaff/scipy
refs/heads/master
benchmarks/benchmarks/go_benchmark_functions/go_funcs_I.py
21
# -*- coding: utf-8 -*- from numpy import sin, sum from .go_benchmark import Benchmark class Infinity(Benchmark): r""" Infinity objective function. This class defines the Infinity [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Infinity}}(x) = \sum_{i=1}^{n} x_i^{6} \left [ \sin\left ( \frac{1}{x_i} \right ) + 2 \right ] Here, :math:`n` represents the number of dimensions and :math:`x_i \in [-1, 1]` for :math:`i = 1, ..., n`. *Global optimum*: :math:`f(x) = 0` for :math:`x_i = 0` for :math:`i = 1, ..., n` .. [1] Gavana, A. Global Optimization Benchmarks and AMPGO retrieved 2015 """ def __init__(self, dimensions=2): Benchmark.__init__(self, dimensions) self._bounds = list(zip([-1.0] * self.N, [1.0] * self.N)) self.global_optimum = [[1e-16 for _ in range(self.N)]] self.fglob = 0.0 self.change_dimensionality = True def fun(self, x, *args): self.nfev += 1 return sum(x ** 6.0 * (sin(1.0 / x) + 2.0))
Dandandan/wikiprogramming
refs/heads/master
jsrepl/build/extern/python/unclosured/lib/python2.7/encodings/cp1255.py
593
""" Python Character Mapping Codec cp1255 generated from 'MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1255.TXT' with gencodec.py. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_table) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_table)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_table)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return codecs.CodecInfo( name='cp1255', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Table decoding_table = ( u'\x00' # 0x00 -> NULL u'\x01' # 0x01 -> START OF HEADING u'\x02' # 0x02 -> START OF TEXT u'\x03' # 0x03 -> END OF TEXT u'\x04' # 0x04 -> END OF TRANSMISSION u'\x05' # 0x05 -> ENQUIRY u'\x06' # 0x06 -> ACKNOWLEDGE u'\x07' # 0x07 -> BELL u'\x08' # 0x08 -> BACKSPACE u'\t' # 0x09 -> HORIZONTAL TABULATION u'\n' # 0x0A -> LINE FEED u'\x0b' # 0x0B -> VERTICAL TABULATION u'\x0c' # 0x0C -> FORM FEED u'\r' # 0x0D -> CARRIAGE RETURN u'\x0e' # 0x0E -> SHIFT OUT u'\x0f' # 0x0F -> SHIFT IN u'\x10' # 0x10 -> DATA LINK ESCAPE u'\x11' # 0x11 -> DEVICE CONTROL ONE u'\x12' # 0x12 -> DEVICE CONTROL TWO u'\x13' # 0x13 -> DEVICE CONTROL THREE u'\x14' # 0x14 -> DEVICE CONTROL FOUR u'\x15' # 0x15 -> NEGATIVE ACKNOWLEDGE u'\x16' # 0x16 -> SYNCHRONOUS IDLE u'\x17' # 0x17 -> END OF TRANSMISSION BLOCK u'\x18' # 0x18 -> CANCEL u'\x19' # 0x19 -> END OF MEDIUM u'\x1a' # 0x1A -> SUBSTITUTE u'\x1b' # 0x1B -> ESCAPE u'\x1c' # 0x1C -> FILE SEPARATOR u'\x1d' # 0x1D -> GROUP SEPARATOR u'\x1e' # 0x1E -> RECORD SEPARATOR u'\x1f' # 0x1F -> UNIT SEPARATOR u' ' # 0x20 -> SPACE u'!' # 0x21 -> EXCLAMATION MARK u'"' # 0x22 -> QUOTATION MARK u'#' # 0x23 -> NUMBER SIGN u'$' # 0x24 -> DOLLAR SIGN u'%' # 0x25 -> PERCENT SIGN u'&' # 0x26 -> AMPERSAND u"'" # 0x27 -> APOSTROPHE u'(' # 0x28 -> LEFT PARENTHESIS u')' # 0x29 -> RIGHT PARENTHESIS u'*' # 0x2A -> ASTERISK u'+' # 0x2B -> PLUS SIGN u',' # 0x2C -> COMMA u'-' # 0x2D -> HYPHEN-MINUS u'.' # 0x2E -> FULL STOP u'/' # 0x2F -> SOLIDUS u'0' # 0x30 -> DIGIT ZERO u'1' # 0x31 -> DIGIT ONE u'2' # 0x32 -> DIGIT TWO u'3' # 0x33 -> DIGIT THREE u'4' # 0x34 -> DIGIT FOUR u'5' # 0x35 -> DIGIT FIVE u'6' # 0x36 -> DIGIT SIX u'7' # 0x37 -> DIGIT SEVEN u'8' # 0x38 -> DIGIT EIGHT u'9' # 0x39 -> DIGIT NINE u':' # 0x3A -> COLON u';' # 0x3B -> SEMICOLON u'<' # 0x3C -> LESS-THAN SIGN u'=' # 0x3D -> EQUALS SIGN u'>' # 0x3E -> GREATER-THAN SIGN u'?' # 0x3F -> QUESTION MARK u'@' # 0x40 -> COMMERCIAL AT u'A' # 0x41 -> LATIN CAPITAL LETTER A u'B' # 0x42 -> LATIN CAPITAL LETTER B u'C' # 0x43 -> LATIN CAPITAL LETTER C u'D' # 0x44 -> LATIN CAPITAL LETTER D u'E' # 0x45 -> LATIN CAPITAL LETTER E u'F' # 0x46 -> LATIN CAPITAL LETTER F u'G' # 0x47 -> LATIN CAPITAL LETTER G u'H' # 0x48 -> LATIN CAPITAL LETTER H u'I' # 0x49 -> LATIN CAPITAL LETTER I u'J' # 0x4A -> LATIN CAPITAL LETTER J u'K' # 0x4B -> LATIN CAPITAL LETTER K u'L' # 0x4C -> LATIN CAPITAL LETTER L u'M' # 0x4D -> LATIN CAPITAL LETTER M u'N' # 0x4E -> LATIN CAPITAL LETTER N u'O' # 0x4F -> LATIN CAPITAL LETTER O u'P' # 0x50 -> LATIN CAPITAL LETTER P u'Q' # 0x51 -> LATIN CAPITAL LETTER Q u'R' # 0x52 -> LATIN CAPITAL LETTER R u'S' # 0x53 -> LATIN CAPITAL LETTER S u'T' # 0x54 -> LATIN CAPITAL LETTER T u'U' # 0x55 -> LATIN CAPITAL LETTER U u'V' # 0x56 -> LATIN CAPITAL LETTER V u'W' # 0x57 -> LATIN CAPITAL LETTER W u'X' # 0x58 -> LATIN CAPITAL LETTER X u'Y' # 0x59 -> LATIN CAPITAL LETTER Y u'Z' # 0x5A -> LATIN CAPITAL LETTER Z u'[' # 0x5B -> LEFT SQUARE BRACKET u'\\' # 0x5C -> REVERSE SOLIDUS u']' # 0x5D -> RIGHT SQUARE BRACKET u'^' # 0x5E -> CIRCUMFLEX ACCENT u'_' # 0x5F -> LOW LINE u'`' # 0x60 -> GRAVE ACCENT u'a' # 0x61 -> LATIN SMALL LETTER A u'b' # 0x62 -> LATIN SMALL LETTER B u'c' # 0x63 -> LATIN SMALL LETTER C u'd' # 0x64 -> LATIN SMALL LETTER D u'e' # 0x65 -> LATIN SMALL LETTER E u'f' # 0x66 -> LATIN SMALL LETTER F u'g' # 0x67 -> LATIN SMALL LETTER G u'h' # 0x68 -> LATIN SMALL LETTER H u'i' # 0x69 -> LATIN SMALL LETTER I u'j' # 0x6A -> LATIN SMALL LETTER J u'k' # 0x6B -> LATIN SMALL LETTER K u'l' # 0x6C -> LATIN SMALL LETTER L u'm' # 0x6D -> LATIN SMALL LETTER M u'n' # 0x6E -> LATIN SMALL LETTER N u'o' # 0x6F -> LATIN SMALL LETTER O u'p' # 0x70 -> LATIN SMALL LETTER P u'q' # 0x71 -> LATIN SMALL LETTER Q u'r' # 0x72 -> LATIN SMALL LETTER R u's' # 0x73 -> LATIN SMALL LETTER S u't' # 0x74 -> LATIN SMALL LETTER T u'u' # 0x75 -> LATIN SMALL LETTER U u'v' # 0x76 -> LATIN SMALL LETTER V u'w' # 0x77 -> LATIN SMALL LETTER W u'x' # 0x78 -> LATIN SMALL LETTER X u'y' # 0x79 -> LATIN SMALL LETTER Y u'z' # 0x7A -> LATIN SMALL LETTER Z u'{' # 0x7B -> LEFT CURLY BRACKET u'|' # 0x7C -> VERTICAL LINE u'}' # 0x7D -> RIGHT CURLY BRACKET u'~' # 0x7E -> TILDE u'\x7f' # 0x7F -> DELETE u'\u20ac' # 0x80 -> EURO SIGN u'\ufffe' # 0x81 -> UNDEFINED u'\u201a' # 0x82 -> SINGLE LOW-9 QUOTATION MARK u'\u0192' # 0x83 -> LATIN SMALL LETTER F WITH HOOK u'\u201e' # 0x84 -> DOUBLE LOW-9 QUOTATION MARK u'\u2026' # 0x85 -> HORIZONTAL ELLIPSIS u'\u2020' # 0x86 -> DAGGER u'\u2021' # 0x87 -> DOUBLE DAGGER u'\u02c6' # 0x88 -> MODIFIER LETTER CIRCUMFLEX ACCENT u'\u2030' # 0x89 -> PER MILLE SIGN u'\ufffe' # 0x8A -> UNDEFINED u'\u2039' # 0x8B -> SINGLE LEFT-POINTING ANGLE QUOTATION MARK u'\ufffe' # 0x8C -> UNDEFINED u'\ufffe' # 0x8D -> UNDEFINED u'\ufffe' # 0x8E -> UNDEFINED u'\ufffe' # 0x8F -> UNDEFINED u'\ufffe' # 0x90 -> UNDEFINED u'\u2018' # 0x91 -> LEFT SINGLE QUOTATION MARK u'\u2019' # 0x92 -> RIGHT SINGLE QUOTATION MARK u'\u201c' # 0x93 -> LEFT DOUBLE QUOTATION MARK u'\u201d' # 0x94 -> RIGHT DOUBLE QUOTATION MARK u'\u2022' # 0x95 -> BULLET u'\u2013' # 0x96 -> EN DASH u'\u2014' # 0x97 -> EM DASH u'\u02dc' # 0x98 -> SMALL TILDE u'\u2122' # 0x99 -> TRADE MARK SIGN u'\ufffe' # 0x9A -> UNDEFINED u'\u203a' # 0x9B -> SINGLE RIGHT-POINTING ANGLE QUOTATION MARK u'\ufffe' # 0x9C -> UNDEFINED u'\ufffe' # 0x9D -> UNDEFINED u'\ufffe' # 0x9E -> UNDEFINED u'\ufffe' # 0x9F -> UNDEFINED u'\xa0' # 0xA0 -> NO-BREAK SPACE u'\xa1' # 0xA1 -> INVERTED EXCLAMATION MARK u'\xa2' # 0xA2 -> CENT SIGN u'\xa3' # 0xA3 -> POUND SIGN u'\u20aa' # 0xA4 -> NEW SHEQEL SIGN u'\xa5' # 0xA5 -> YEN SIGN u'\xa6' # 0xA6 -> BROKEN BAR u'\xa7' # 0xA7 -> SECTION SIGN u'\xa8' # 0xA8 -> DIAERESIS u'\xa9' # 0xA9 -> COPYRIGHT SIGN u'\xd7' # 0xAA -> MULTIPLICATION SIGN u'\xab' # 0xAB -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK u'\xac' # 0xAC -> NOT SIGN u'\xad' # 0xAD -> SOFT HYPHEN u'\xae' # 0xAE -> REGISTERED SIGN u'\xaf' # 0xAF -> MACRON u'\xb0' # 0xB0 -> DEGREE SIGN u'\xb1' # 0xB1 -> PLUS-MINUS SIGN u'\xb2' # 0xB2 -> SUPERSCRIPT TWO u'\xb3' # 0xB3 -> SUPERSCRIPT THREE u'\xb4' # 0xB4 -> ACUTE ACCENT u'\xb5' # 0xB5 -> MICRO SIGN u'\xb6' # 0xB6 -> PILCROW SIGN u'\xb7' # 0xB7 -> MIDDLE DOT u'\xb8' # 0xB8 -> CEDILLA u'\xb9' # 0xB9 -> SUPERSCRIPT ONE u'\xf7' # 0xBA -> DIVISION SIGN u'\xbb' # 0xBB -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK u'\xbc' # 0xBC -> VULGAR FRACTION ONE QUARTER u'\xbd' # 0xBD -> VULGAR FRACTION ONE HALF u'\xbe' # 0xBE -> VULGAR FRACTION THREE QUARTERS u'\xbf' # 0xBF -> INVERTED QUESTION MARK u'\u05b0' # 0xC0 -> HEBREW POINT SHEVA u'\u05b1' # 0xC1 -> HEBREW POINT HATAF SEGOL u'\u05b2' # 0xC2 -> HEBREW POINT HATAF PATAH u'\u05b3' # 0xC3 -> HEBREW POINT HATAF QAMATS u'\u05b4' # 0xC4 -> HEBREW POINT HIRIQ u'\u05b5' # 0xC5 -> HEBREW POINT TSERE u'\u05b6' # 0xC6 -> HEBREW POINT SEGOL u'\u05b7' # 0xC7 -> HEBREW POINT PATAH u'\u05b8' # 0xC8 -> HEBREW POINT QAMATS u'\u05b9' # 0xC9 -> HEBREW POINT HOLAM u'\ufffe' # 0xCA -> UNDEFINED u'\u05bb' # 0xCB -> HEBREW POINT QUBUTS u'\u05bc' # 0xCC -> HEBREW POINT DAGESH OR MAPIQ u'\u05bd' # 0xCD -> HEBREW POINT METEG u'\u05be' # 0xCE -> HEBREW PUNCTUATION MAQAF u'\u05bf' # 0xCF -> HEBREW POINT RAFE u'\u05c0' # 0xD0 -> HEBREW PUNCTUATION PASEQ u'\u05c1' # 0xD1 -> HEBREW POINT SHIN DOT u'\u05c2' # 0xD2 -> HEBREW POINT SIN DOT u'\u05c3' # 0xD3 -> HEBREW PUNCTUATION SOF PASUQ u'\u05f0' # 0xD4 -> HEBREW LIGATURE YIDDISH DOUBLE VAV u'\u05f1' # 0xD5 -> HEBREW LIGATURE YIDDISH VAV YOD u'\u05f2' # 0xD6 -> HEBREW LIGATURE YIDDISH DOUBLE YOD u'\u05f3' # 0xD7 -> HEBREW PUNCTUATION GERESH u'\u05f4' # 0xD8 -> HEBREW PUNCTUATION GERSHAYIM u'\ufffe' # 0xD9 -> UNDEFINED u'\ufffe' # 0xDA -> UNDEFINED u'\ufffe' # 0xDB -> UNDEFINED u'\ufffe' # 0xDC -> UNDEFINED u'\ufffe' # 0xDD -> UNDEFINED u'\ufffe' # 0xDE -> UNDEFINED u'\ufffe' # 0xDF -> UNDEFINED u'\u05d0' # 0xE0 -> HEBREW LETTER ALEF u'\u05d1' # 0xE1 -> HEBREW LETTER BET u'\u05d2' # 0xE2 -> HEBREW LETTER GIMEL u'\u05d3' # 0xE3 -> HEBREW LETTER DALET u'\u05d4' # 0xE4 -> HEBREW LETTER HE u'\u05d5' # 0xE5 -> HEBREW LETTER VAV u'\u05d6' # 0xE6 -> HEBREW LETTER ZAYIN u'\u05d7' # 0xE7 -> HEBREW LETTER HET u'\u05d8' # 0xE8 -> HEBREW LETTER TET u'\u05d9' # 0xE9 -> HEBREW LETTER YOD u'\u05da' # 0xEA -> HEBREW LETTER FINAL KAF u'\u05db' # 0xEB -> HEBREW LETTER KAF u'\u05dc' # 0xEC -> HEBREW LETTER LAMED u'\u05dd' # 0xED -> HEBREW LETTER FINAL MEM u'\u05de' # 0xEE -> HEBREW LETTER MEM u'\u05df' # 0xEF -> HEBREW LETTER FINAL NUN u'\u05e0' # 0xF0 -> HEBREW LETTER NUN u'\u05e1' # 0xF1 -> HEBREW LETTER SAMEKH u'\u05e2' # 0xF2 -> HEBREW LETTER AYIN u'\u05e3' # 0xF3 -> HEBREW LETTER FINAL PE u'\u05e4' # 0xF4 -> HEBREW LETTER PE u'\u05e5' # 0xF5 -> HEBREW LETTER FINAL TSADI u'\u05e6' # 0xF6 -> HEBREW LETTER TSADI u'\u05e7' # 0xF7 -> HEBREW LETTER QOF u'\u05e8' # 0xF8 -> HEBREW LETTER RESH u'\u05e9' # 0xF9 -> HEBREW LETTER SHIN u'\u05ea' # 0xFA -> HEBREW LETTER TAV u'\ufffe' # 0xFB -> UNDEFINED u'\ufffe' # 0xFC -> UNDEFINED u'\u200e' # 0xFD -> LEFT-TO-RIGHT MARK u'\u200f' # 0xFE -> RIGHT-TO-LEFT MARK u'\ufffe' # 0xFF -> UNDEFINED ) ### Encoding table encoding_table=codecs.charmap_build(decoding_table)
maximinus/grateful-dead-songs
refs/heads/master
gdsongs/shows/management/commands/clearsets.py
1
from django.core.management.base import BaseCommand, CommandError from songs.models import Song from shows.models import PlayedSong, PlayedSet, Show, ShowDate class Command(BaseCommand): help = 'Remove all PlayedSongs, PlayedSets and Shows from the database' def handle(self, *args, **options): # get numbers dates = len(ShowDate.objects.all()) shows = len(Show.objects.all()) sets = len(PlayedSet.objects.all()) songs = len(PlayedSong.objects.all()) # remove backwards PlayedSong.objects.all().delete() PlayedSet.objects.all().delete() ShowDate.objects.all().delete() Show.objects.all().delete() print('Deleted {0} songs, {1} sets, {2} shows and {3} dates.'.format(songs, sets, shows, dates))
varunarya10/contrail-sandesh
refs/heads/master
library/python/pysandesh/sandesh_base.py
3
# # Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. # # # Sandesh # import os import gevent import pkgutil import importlib import trace from work_queue import WorkQueue from sandesh_logger import SandeshLogger from sandesh_client import SandeshClient from sandesh_http import SandeshHttp from sandesh_uve import SandeshUVETypeMaps, SandeshUVEPerTypeMap from sandesh_stats import SandeshStats from sandesh_trace import SandeshTraceRequestRunner from util import * from gen_py.sandesh.ttypes import SandeshType, SandeshLevel from gen_py.sandesh.constants import * class Sandesh(object): _DEFAULT_LOG_FILE = SandeshLogger._DEFAULT_LOG_FILE _DEFAULT_SYSLOG_FACILITY = SandeshLogger._DEFAULT_SYSLOG_FACILITY class SandeshRole: INVALID = 0 GENERATOR = 1 COLLECTOR = 2 # end class SandeshRole def __init__(self): self._context = '' self._scope = '' self._module = '' self._source = '' self._node_type = '' self._instance_id = '' self._timestamp = 0 self._versionsig = 0 self._type = 0 self._hints = 0 self._client_context = '' self._client = None self._role = self.SandeshRole.INVALID self._logger = None self._level = SandeshLevel.INVALID self._category = '' self._send_queue_enabled = True self._http_server = None # end __init__ # Public functions def init_generator(self, module, source, node_type, instance_id, collectors, client_context, http_port, sandesh_req_uve_pkg_list=None, discovery_client=None): self._role = self.SandeshRole.GENERATOR self._module = module self._source = source self._node_type = node_type self._instance_id = instance_id self._client_context = client_context self._collectors = collectors self._rcv_queue = WorkQueue(self._process_rx_sandesh) self._init_logger(source + ':' + module + ':' + node_type + ':' \ + instance_id) self._stats = SandeshStats() self._trace = trace.Trace() self._sandesh_request_dict = {} self._uve_type_maps = SandeshUVETypeMaps() if sandesh_req_uve_pkg_list is None: sandesh_req_uve_pkg_list = [] # Initialize the request handling # Import here to break the cyclic import dependency import sandesh_req_impl sandesh_req_impl = sandesh_req_impl.SandeshReqImpl(self) sandesh_req_uve_pkg_list.append('pysandesh.gen_py') for pkg_name in sandesh_req_uve_pkg_list: self._create_sandesh_request_and_uve_lists(pkg_name) if http_port != -1: self._http_server = SandeshHttp( self, module, http_port, sandesh_req_uve_pkg_list) gevent.spawn(self._http_server.start_http_server) primary_collector = None secondary_collector = None if self._collectors is not None: if len(self._collectors) > 0: primary_collector = self._collectors[0] if len(self._collectors) > 1: secondary_collector = self._collectors[1] self._client = SandeshClient( self, primary_collector, secondary_collector, discovery_client) self._client.initiate() # end init_generator def logger(self): return self._logger # end logger def sandesh_logger(self): return self._sandesh_logger # end sandesh_logger def set_logging_params(self, enable_local_log=False, category='', level=SandeshLevel.SYS_INFO, file=SandeshLogger._DEFAULT_LOG_FILE, enable_syslog=False, syslog_facility=_DEFAULT_SYSLOG_FACILITY): self._sandesh_logger.set_logging_params( enable_local_log, category, level, file, enable_syslog, syslog_facility) # end set_logging_params def set_local_logging(self, enable_local_log): self._sandesh_logger.set_local_logging(enable_local_log) # end set_local_logging def set_logging_level(self, level): self._sandesh_logger.set_logging_level(level) # end set_logging_level def set_logging_category(self, category): self._sandesh_logger.set_logging_category(category) # end set_logging_category def set_logging_file(self, file): self._sandesh_logger.set_logging_file(file) # end set_logging_file def is_send_queue_enabled(self): return self._send_queue_enabled # end is_send_queue_enabled def set_send_queue(self, enable): if self._send_queue_enabled != enable: self._logger.info("SANDESH: CLIENT: SEND QUEUE: %s -> %s", self._send_queue_enabled, enable) self._send_queue_enabled = enable if enable: connection = self._client.connection() if connection and connection.session(): connection.session().send_queue().may_be_start_runner() # end set_send_queue def init_collector(self): pass # end init_collector def stats(self): return self._stats # end stats @classmethod def next_seqnum(cls): if not hasattr(cls, '_lseqnum'): cls._lseqnum = 1 else: cls._lseqnum += 1 return cls._lseqnum # end next_seqnum @classmethod def lseqnum(cls): if not hasattr(cls, '_lseqnum'): cls._lseqnum = 0 return cls._lseqnum # end lseqnum def module(self): return self._module # end module def source_id(self): return self._source # end source_id def node_type(self): return self._node_type #end node_type def instance_id(self): return self._instance_id #end instance_id def scope(self): return self._scope # end scope def context(self): return self._context # end context def seqnum(self): return self._seqnum # end seqnum def timestamp(self): return self._timestamp # end timestamp def versionsig(self): return self._versionsig # end versionsig def type(self): return self._type # end type def hints(self): return self._hints # end hints def client(self): return self._client # end client def level(self): return self._level # end level def category(self): return self._category # end category def validate(self): return # end validate def is_local_logging_enabled(self): return self._sandesh_logger.is_local_logging_enabled() # end is_local_logging_enabled def logging_level(self): return self._sandesh_logger.logging_level() # end logging_level def logging_category(self): return self._sandesh_logger.logging_category() # end logging_category def is_syslog_logging_enabled(self): return self._sandesh_logger.is_syslog_logging_enabled() #end is_syslog_logging_enabled def logging_syslog_facility(self): return self._sandesh_logger.logging_syslog_facility() #end logging_syslog_facility def is_unit_test(self): return self._role == self.SandeshRole.INVALID # end is_unit_test def handle_test(self, sandesh_init): if sandesh_init.is_unit_test() or self._is_level_ut(): if self._is_logging_allowed(sandesh_init): sandesh_init._logger.debug(self.log()) return True return False def is_logging_allowed(self, sandesh_init): if not sandesh_init.is_local_logging_enabled(): return False logging_level = sandesh_init.logging_level() level_allowed = logging_level >= self._level logging_category = sandesh_init.logging_category() if logging_category is None or len(logging_category) == 0: category_allowed = True else: category_allowed = logging_category == self._category return level_allowed and category_allowed # end is_logging_allowed def enqueue_sandesh_request(self, sandesh): self._rcv_queue.enqueue(sandesh) # end enqueue_sandesh_request def send_sandesh(self, tx_sandesh): if self._client: ret = self._client.send_sandesh(tx_sandesh) else: self._logger.debug(tx_sandesh.log()) # end send_sandesh def send_generator_info(self): from gen_py.sandesh_uve.ttypes import SandeshClientInfo, \ ModuleClientState, SandeshModuleClientTrace client_info = SandeshClientInfo() try: client_start_time = self._start_time except: self._start_time = UTCTimestampUsec() finally: client_info.start_time = self._start_time client_info.pid = os.getpid() if self._http_server is not None: client_info.http_port = self._http_server.get_port() client_info.collector_name = self._client.connection().collector() client_info.status = self._client.connection().state() client_info.successful_connections = \ self._client.connection().statemachine().connect_count() client_info.primary = self._client.connection().primary_collector() if client_info.primary is None: client_info.primary = '' client_info.secondary = \ self._client.connection().secondary_collector() if client_info.secondary is None: client_info.secondary = '' module_state = ModuleClientState(name=self._source + ':' + self._node_type + ':' + self._module + ':' + self._instance_id, client_info=client_info) generator_info = SandeshModuleClientTrace( data=module_state, sandesh=self) generator_info.send(sandesh=self) # end send_generator_info def get_sandesh_request_object(self, request): try: req_module = self._sandesh_request_dict[request] except KeyError: self._logger.error('Invalid Sandesh Request "%s"' % (request)) return None else: if req_module: try: imp_module = importlib.import_module(req_module) except ImportError: self._logger.error( 'Failed to import Module "%s"' % (req_module)) else: try: sandesh_request = getattr(imp_module, request)() return sandesh_request except AttributeError: self._logger.error( 'Failed to create Sandesh Request "%s"' % (request)) return None else: self._logger.error( 'Sandesh Request "%s" not implemented' % (request)) return None # end get_sandesh_request_object def trace_enable(self): self._trace.TraceOn() # end trace_enable def trace_disable(self): self._trace.TraceOff() # end trace_disable def is_trace_enabled(self): return self._trace.IsTraceOn() # end is_trace_enabled def trace_buffer_create(self, name, size, enable=True): self._trace.TraceBufAdd(name, size, enable) # end trace_buffer_create def trace_buffer_delete(self, name): self._trace.TraceBufDelete(name) # end trace_buffer_delete def trace_buffer_enable(self, name): self._trace.TraceBufOn(name) # end trace_buffer_enable def trace_buffer_disable(self, name): self._trace.TraceBufOff(name) # end trace_buffer_disable def is_trace_buffer_enabled(self, name): return self._trace.IsTraceBufOn(name) # end is_trace_buffer_enabled def trace_buffer_list_get(self): return self._trace.TraceBufListGet() # end trace_buffer_list_get def trace_buffer_size_get(self, name): return self._trace.TraceBufSizeGet(name) # end trace_buffer_size_get def trace_buffer_read(self, name, read_context, count, read_cb): self._trace.TraceRead(name, read_context, count, read_cb) # end trace_buffer_read def trace_buffer_read_done(self, name, context): self._trace.TraceReadDone(name, context) # end trace_buffer_read_done # API to send the trace buffer to the Collector. # If trace count is not specified/or zero, then the entire trace buffer # is sent to the Collector. # [Note] No duplicate trace message sent to the Collector. i.e., If there # is no trace message added between two consequent calls to this API, then # no trace message is sent to the Collector. def send_sandesh_trace_buffer(self, trace_buf, count=0): trace_req_runner = SandeshTraceRequestRunner(sandesh=self, request_buffer_name= trace_buf, request_context='', read_context='Collector', request_count=count) trace_req_runner.Run() # end send_sandesh_trace_buffer # Private functions def _is_level_ut(self): return self._level >= SandeshLevel.UT_START and \ self._level <= SandeshLevel.UT_END # end _is_level_ut def _create_task(self): return gevent.spawn(self._runner.run_for_ever) # end _create_task def _process_rx_sandesh(self, rx_sandesh): handle_request_fn = getattr(rx_sandesh, "handle_request", None) if callable(handle_request_fn): handle_request_fn(rx_sandesh) else: self._logger.error('Sandesh Request "%s" not implemented' % (rx_sandesh.__class__.__name__)) # end _process_rx_sandesh def _create_sandesh_request_and_uve_lists(self, package): try: imp_pkg = __import__(package) except ImportError: self._logger.error('Failed to import package "%s"' % (package)) else: try: pkg_path = imp_pkg.__path__ except AttributeError: self._logger.error( 'Failed to get package [%s] path' % (package)) return for importer, mod, ispkg in \ pkgutil.walk_packages(path=pkg_path, prefix=imp_pkg.__name__ + '.'): if not ispkg: module = mod.rsplit('.', 1)[-1] if 'ttypes' == module: self._logger.debug( 'Add Sandesh requests in module "%s"' % (mod)) self._add_sandesh_request(mod) self._logger.debug( 'Add Sandesh UVEs in module "%s"' % (mod)) self._add_sandesh_uve(mod) # end _create_sandesh_request_and_uve_lists def _add_sandesh_request(self, mod): try: imp_module = importlib.import_module(mod) except ImportError: self._logger.error('Failed to import Module "%s"' % (mod)) else: try: sandesh_req_list = getattr(imp_module, '_SANDESH_REQUEST_LIST') except AttributeError: self._logger.error( '"%s" module does not have sandesh request list' % (mod)) else: # Add sandesh requests to the dictionary. for req in sandesh_req_list: self._sandesh_request_dict[req] = mod # end _add_sandesh_request def _get_sandesh_uve_list(self, imp_module): try: sandesh_uve_list = getattr(imp_module, '_SANDESH_UVE_LIST') except AttributeError: self._logger.error( '"%s" module does not have sandesh UVE list' % (imp_module.__name__)) return None else: return sandesh_uve_list # end _get_sandesh_uve_list def _get_sandesh_uve_data_list(self, imp_module): try: sandesh_uve_data_list = getattr(imp_module, '_SANDESH_UVE_DATA_LIST') except AttributeError: self._logger.error( '"%s" module does not have sandesh UVE data list' % (imp_module.__name__)) return None else: return sandesh_uve_data_list # end _get_sandesh_uve_data_list def _add_sandesh_uve(self, mod): try: imp_module = importlib.import_module(mod) except ImportError: self._logger.error('Failed to import Module "%s"' % (mod)) else: sandesh_uve_list = self._get_sandesh_uve_list(imp_module) sandesh_uve_data_list = self._get_sandesh_uve_data_list(imp_module) if sandesh_uve_list is None or sandesh_uve_data_list is None: return if len(sandesh_uve_list) != len(sandesh_uve_data_list): self._logger.error( '"%s" module sandesh UVE and UVE data list do not match' % (mod)) return sandesh_uve_info_list = zip(sandesh_uve_list, sandesh_uve_data_list) # Register sandesh UVEs for uve_type_name, uve_data_type_name in sandesh_uve_info_list: SandeshUVEPerTypeMap(self, uve_type_name, uve_data_type_name, mod) # end _add_sandesh_uve def _init_logger(self, generator): if not generator: generator = 'sandesh' self._sandesh_logger = SandeshLogger(generator) self._logger = self._sandesh_logger.logger() # end _init_logger # end class Sandesh sandesh_global = Sandesh() class SandeshAsync(Sandesh): def __init__(self): Sandesh.__init__(self) # end __init__ def send(self, sandesh=sandesh_global): try: self.validate() except e: sandesh._logger.error('sandesh "%s" validation failed [%s]' % (self.__class__.__name__, e)) return -1 self._seqnum = self.next_seqnum() if self.handle_test(sandesh): return 0 sandesh.send_sandesh(self) return 0 # end send # end class SandeshAsync class SandeshSystem(SandeshAsync): def __init__(self): SandeshAsync.__init__(self) self._type = SandeshType.SYSTEM # end __init__ # end class SandeshSystem class SandeshObject(SandeshAsync): def __init__(self): SandeshAsync.__init__(self) self._type = SandeshType.OBJECT # end __init__ # end class SandeshObject class SandeshFlow(SandeshAsync): def __init__(self): SandeshAsync.__init__(self) self._type = SandeshType.FLOW # end __init__ # end class SandeshFlow class SandeshRequest(Sandesh): def __init__(self): Sandesh.__init__(self) self._type = SandeshType.REQUEST # end __init__ def request(self, context='', sandesh=sandesh_global): try: self.validate() except e: sandesh._logger.error('sandesh "%s" validation failed [%s]' % (self.__class__.__name__, e)) return -1 if context == 'ctrl': self._hints |= SANDESH_CONTROL_HINT self._context = context self._seqnum = self.next_seqnum() if self.handle_test(sandesh): return 0 sandesh.send_sandesh(self) return 0 # end request # end class SandeshRequest class SandeshResponse(Sandesh): def __init__(self): Sandesh.__init__(self) self._type = SandeshType.RESPONSE self._more = False # end __init__ def response(self, context='', more=False, sandesh=sandesh_global): try: self.validate() except e: sandesh._logger.error('sandesh "%s" validation failed [%s]' % (self.__class__.__name__, e)) return -1 self._context = context self._more = more self._seqnum = self.next_seqnum() if self._context.find('http://') == 0: SandeshHttp.create_http_response(self, sandesh) else: if self.handle_test(sandesh): return 0 sandesh.send_sandesh(self) return 0 # end response # end class SandeshResponse class SandeshUVE(Sandesh): def __init__(self): Sandesh.__init__(self) self._type = SandeshType.UVE self._more = False # end __init__ def send(self, isseq=False, seqno=0, context='', more=False, sandesh=sandesh_global): try: self.validate() except e: sandesh._logger.error('sandesh "%s" validation failed [%s]' % (self.__class__.__name__, e)) return -1 if isseq is True: self._seqnum = seqno else: uve_type_map = sandesh._uve_type_maps.get_uve_type_map( self.__class__.__name__) if uve_type_map is None: return -1 self._seqnum = self.next_seqnum() uve_type_map.update_uve(self) self._context = context self._more = more if self._context.find('http://') == 0: SandeshHttp.create_http_response(self, sandesh) else: if self.handle_test(sandesh): return 0 if sandesh._client: sandesh._client.send_uve_sandesh(self) else: sandesh._logger.debug(self.log()) return 0 # end send # end class SandeshUVE class SandeshTrace(Sandesh): def __init__(self, type): Sandesh.__init__(self) self._type = type self._more = False # end __init__ def send_trace(self, context='', more=False, sandesh=sandesh_global): try: self.validate() except e: sandesh._logger.error('sandesh "%s" validation failed [%s]' % (self.__class__.__name__, e)) return -1 self._context = context self._more = more if self._context.find('http://') == 0: SandeshHttp.create_http_response(self, sandesh) else: if self.handle_test(sandesh): return 0 sandesh.send_sandesh(self) return 0 # end send_trace def trace_msg(self, name, sandesh=sandesh_global): if sandesh._trace.IsTraceOn() and sandesh._trace.IsTraceBufOn(name): # store the trace buffer name in category self._category = name self._seqnum = sandesh._trace.TraceWrite(name, self) # end trace_msg # end class SandeshTrace
simonwydooghe/ansible
refs/heads/devel
lib/ansible/modules/network/f5/bigip_firewall_rule.py
21
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright: (c) 2018, 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 ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'certified'} DOCUMENTATION = r''' --- module: bigip_firewall_rule short_description: Manage AFM Firewall rules description: - Manages firewall rules in an AFM firewall policy. New rules will always be added to the end of the policy. Rules can be re-ordered using the C(bigip_security_policy) module. Rules can also be pre-ordered using the C(bigip_security_policy) module and then later updated using the C(bigip_firewall_rule) module. version_added: 2.7 options: name: description: - Specifies the name of the rule. type: str required: True parent_policy: description: - The policy which contains the rule to be managed. - One of either C(parent_policy) or C(parent_rule_list) is required. type: str parent_rule_list: description: - The rule list which contains the rule to be managed. - One of either C(parent_policy) or C(parent_rule_list) is required. type: str action: description: - Specifies the action for the firewall rule. - When C(accept), allows packets with the specified source, destination, and protocol to pass through the firewall. Packets that match the rule, and are accepted, traverse the system as if the firewall is not present. - When C(drop), drops packets with the specified source, destination, and protocol. Dropping a packet is a silent action with no notification to the source or destination systems. Dropping the packet causes the connection to be retried until the retry threshold is reached. - When C(reject), rejects packets with the specified source, destination, and protocol. When a packet is rejected the firewall sends a destination unreachable message to the sender. - When C(accept-decisively), allows packets with the specified source, destination, and protocol to pass through the firewall, and does not require any further processing by any of the further firewalls. Packets that match the rule, and are accepted, traverse the system as if the firewall is not present. If the Rule List is applied to a virtual server, management IP, or self IP firewall rule, then Accept Decisively is equivalent to Accept. - When creating a new rule, if this parameter is not provided, the default is C(reject). type: str choices: - accept - drop - reject - accept-decisively status: description: - Indicates the activity state of the rule or rule list. - When C(disabled), specifies that the rule or rule list does not apply at all. - When C(enabled), specifies that the system applies the firewall rule or rule list to the given context and addresses. - When C(scheduled), specifies that the system applies the rule or rule list according to the specified schedule. - When creating a new rule, if this parameter is not provided, the default is C(enabled). type: str choices: - enabled - disabled - scheduled schedule: description: - Specifies a schedule for the firewall rule. - You configure schedules to define days and times when the firewall rule is made active. type: str description: description: - The rule description. type: str irule: description: - Specifies an iRule that is applied to the firewall rule. - An iRule can be started when the firewall rule matches traffic. type: str protocol: description: - Specifies the protocol to which the rule applies. - Protocols may be specified by either their name or numeric value. - A special protocol value C(any) can be specified to match any protocol. The numeric equivalent of this protocol is C(255). type: str source: description: - Specifies packet sources to which the rule applies. - Leaving this field blank applies the rule to all addresses and all ports. - You can specify the following source items. An IPv4 or IPv6 address, an IPv4 or IPv6 address range, geographic location, VLAN, address list, port, port range, port list or address list. - You can specify a mix of different types of items for the source address. suboptions: address: description: - Specifies a specific IP address. type: str address_list: description: - Specifies an existing address list. type: str address_range: description: - Specifies an address range. type: str country: description: - Specifies a country code. type: str port: description: - Specifies a single numeric port. - This option is only valid when C(protocol) is C(tcp)(6) or C(udp)(17). type: int port_list: description: - Specifes an existing port list. - This option is only valid when C(protocol) is C(tcp)(6) or C(udp)(17). type: str port_range: description: - Specifies a range of ports, which is two port values separated by a hyphen. The port to the left of the hyphen should be less than the port to the right. - This option is only valid when C(protocol) is C(tcp)(6) or C(udp)(17). type: str vlan: description: - Specifies VLANs to which the rule applies. - The VLAN source refers to the packet's source. type: str type: list destination: description: - Specifies packet destinations to which the rule applies. - Leaving this field blank applies the rule to all addresses and all ports. - You can specify the following destination items. An IPv4 or IPv6 address, an IPv4 or IPv6 address range, geographic location, VLAN, address list, port, port range, port list or address list. - You can specify a mix of different types of items for the source address. suboptions: address: description: - Specifies a specific IP address. type: str address_list: description: - Specifies an existing address list. type: str address_range: description: - Specifies an address range. type: str country: description: - Specifies a country code. type: str port: description: - Specifies a single numeric port. - This option is only valid when C(protocol) is C(tcp)(6) or C(udp)(17). type: int port_list: description: - Specifes an existing port list. - This option is only valid when C(protocol) is C(tcp)(6) or C(udp)(17). type: str port_range: description: - Specifies a range of ports, which is two port values separated by a hyphen. The port to the left of the hyphen should be less than the port to the right. - This option is only valid when C(protocol) is C(tcp)(6) or C(udp)(17). type: str type: list logging: description: - Specifies whether logging is enabled or disabled for the firewall rule. - When creating a new rule, if this parameter is not specified, the default if C(no). type: bool rule_list: description: - Specifies an existing rule list to use in the rule. - This parameter is mutually exclusive with many of the other individual-rule specific settings. This includes C(logging), C(action), C(source), C(destination), C(irule'), C(protocol) and C(logging). - This parameter is only used when C(parent_policy) is specified, otherwise it is ignored. type: str icmp_message: description: - Specifies the Internet Control Message Protocol (ICMP) or ICMPv6 message C(type) and C(code) that the rule uses. - This parameter is only relevant when C(protocol) is either C(icmp)(1) or C(icmpv6)(58). suboptions: type: description: - Specifies the type of ICMP message. - You can specify control messages, such as Echo Reply (0) and Destination Unreachable (3), or you can specify C(any) to indicate that the system applies the rule for all ICMP messages. - You can also specify an arbitrary ICMP message. - The ICMP protocol contains definitions for the existing message type and number pairs. type: str code: description: - Specifies the code returned in response to the specified ICMP message type. - You can specify codes, each set appropriate to the associated type, such as No Code (0) (associated with Echo Reply (0)) and Host Unreachable (1) (associated with Destination Unreachable (3)), or you can specify C(any) to indicate that the system applies the rule for all codes in response to that specific ICMP message. - You can also specify an arbitrary code. - The ICMP protocol contains definitions for the existing message code and number pairs. type: str type: list partition: description: - Device partition to manage resources on. type: str default: Common state: description: - When C(state) is C(present), ensures that the rule exists. - When C(state) is C(absent), ensures that the rule is removed. type: str choices: - present - absent default: present extends_documentation_fragment: f5 author: - Tim Rupp (@caphrim007) - Wojciech Wypior (@wojtek0806) ''' EXAMPLES = r''' - name: Create a new rule in the foo firewall policy bigip_firewall_rule: name: foo parent_policy: policy1 protocol: tcp source: - address: 1.2.3.4 - address: "::1" - address_list: foo-list1 - address_range: 1.1.1.1-2.2.2.2 - vlan: vlan1 - country: US - port: 22 - port_list: port-list1 - port_range: 80-443 destination: - address: 1.2.3.4 - address: "::1" - address_list: foo-list1 - address_range: 1.1.1.1-2.2.2.2 - country: US - port: 22 - port_list: port-list1 - port_range: 80-443 irule: irule1 action: accept logging: yes provider: password: secret server: lb.mydomain.com user: admin delegate_to: localhost - name: Create an ICMP specific rule bigip_firewall_rule: name: foo protocol: icmp icmp_message: type: 0 source: - country: US action: drop logging: yes provider: password: secret server: lb.mydomain.com user: admin delegate_to: localhost - name: Add a new policy rule that uses an existing rule list bigip_firewall_rule: name: foo parent_policy: foo_policy rule_list: rule-list1 provider: password: secret server: lb.mydomain.com user: admin delegate_to: localhost ''' RETURN = r''' name: description: Name of the rule. returned: changed type: str sample: FooRule parent_policy: description: The policy which contains the rule to be managed. returned: changed type: str sample: FooPolicy parent_rule_list: description: The rule list which contains the rule to be managed. returned: changed type: str sample: FooRuleList action: description: The action for the firewall rule. returned: changed type: str sample: drop status: description: The activity state of the rule or rule list. returned: changed type: str sample: scheduled schedule: description: The schedule for the firewall rule. returned: changed type: str sample: Foo_schedule description: description: The rule description. returned: changed type: str sample: MyRule irule: description: The iRule that is applied to the firewall rule. returned: changed type: str sample: _sys_auth_radius protocol: description: The protocol to which the rule applies. returned: changed type: str sample: any source: description: The packet sources to which the rule applies returned: changed type: complex contains: address: description: A specific IP address. returned: changed type: str sample: 192.168.1.1 address_list: description: An existing address list. returned: changed type: str sample: foo-list1 address_range: description: The address range. returned: changed type: str sample: 1.1.1.1-2.2.2.2 country: description: A country code. returned: changed type: str sample: US port: description: Single numeric port. returned: changed type: int sample: 8080 port_list: description: An existing port list. returned: changed type: str sample: port-list1 port_range: description: The port range. returned: changed type: str sample: 80-443 vlan: description: Source VLANs for the packets. returned: changed type: str sample: vlan1 sample: hash/dictionary of values destination: description: The packet destinations to which the rule applies. returned: changed type: complex contains: address: description: A specific IP address. returned: changed type: str sample: 192.168.1.1 address_list: description: An existing address list. returned: changed type: str sample: foo-list1 address_range: description: The address range. returned: changed type: str sample: 1.1.1.1-2.2.2.2 country: description: A country code. returned: changed type: str sample: US port: description: Single numeric port. returned: changed type: int sample: 8080 port_list: description: An existing port list. returned: changed type: str sample: port-list1 port_range: description: The port range. returned: changed type: str sample: 80-443 sample: hash/dictionary of values logging: description: Enable or Disable logging for the firewall rule. returned: changed type: bool sample: yes rule_list: description: An existing rule list to use in the parent policy. returned: changed type: str sample: rule-list-1 icmp_message: description: The (ICMP) or ICMPv6 message C(type) and C(code) that the rule uses. returned: changed type: complex contains: type: description: The type of ICMP message. returned: changed type: str sample: 0 code: description: The code returned in response to the specified ICMP message type. returned: changed type: str sample: 1 sample: hash/dictionary of values ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import env_fallback try: from library.module_utils.network.f5.bigip import F5RestClient from library.module_utils.network.f5.common import F5ModuleError from library.module_utils.network.f5.common import AnsibleF5Parameters from library.module_utils.network.f5.common import fq_name from library.module_utils.network.f5.common import f5_argument_spec from library.module_utils.network.f5.common import transform_name except ImportError: from ansible.module_utils.network.f5.bigip import F5RestClient from ansible.module_utils.network.f5.common import F5ModuleError from ansible.module_utils.network.f5.common import AnsibleF5Parameters from ansible.module_utils.network.f5.common import fq_name from ansible.module_utils.network.f5.common import f5_argument_spec from ansible.module_utils.network.f5.common import transform_name class Parameters(AnsibleF5Parameters): api_map = { 'ipProtocol': 'protocol', 'log': 'logging', 'icmp': 'icmp_message', 'ruleList': 'rule_list' } api_attributes = [ 'irule', 'ipProtocol', 'log', 'schedule', 'status', 'destination', 'source', 'icmp', 'action', 'description', 'ruleList', ] returnables = [ 'logging', 'protocol', 'irule', 'source', 'destination', 'action', 'status', 'schedule', 'description', 'icmp_message', 'rule_list', ] updatables = [ 'logging', 'protocol', 'irule', 'source', 'destination', 'action', 'status', 'schedule', 'description', 'icmp_message', 'rule_list', ] protocol_map = { '1': 'icmp', '6': 'tcp', '17': 'udp', '58': 'icmpv6', '255': 'any', } class ApiParameters(Parameters): @property def logging(self): if self._values['logging'] is None: return None if self._values['logging'] == 'yes': return True return False @property def protocol(self): if self._values['protocol'] is None: return None if self._values['protocol'] in self.protocol_map: return self.protocol_map[self._values['protocol']] return self._values['protocol'] @property def source(self): result = [] if self._values['source'] is None: return None v = self._values['source'] if 'addressLists' in v: result += [('address_list', x) for x in v['addressLists']] if 'vlans' in v: result += [('vlan', x) for x in v['vlans']] if 'geo' in v: result += [('geo', x['name']) for x in v['geo']] if 'addresses' in v: result += [('address', x['name']) for x in v['addresses']] if 'ports' in v: result += [('port', str(x['name'])) for x in v['ports']] if 'portLists' in v: result += [('port_list', x) for x in v['portLists']] if result: return result return None @property def destination(self): result = [] if self._values['destination'] is None: return None v = self._values['destination'] if 'addressLists' in v: result += [('address_list', x) for x in v['addressLists']] if 'geo' in v: result += [('geo', x['name']) for x in v['geo']] if 'addresses' in v: result += [('address', x['name']) for x in v['addresses']] if 'ports' in v: result += [('port', x['name']) for x in v['ports']] if 'portLists' in v: result += [('port_list', x) for x in v['portLists']] if result: return result return None @property def icmp_message(self): if self._values['icmp_message'] is None: return None result = [x['name'] for x in self._values['icmp_message']] return result class ModuleParameters(Parameters): @property def irule(self): if self._values['irule'] is None: return None if self._values['irule'] == '': return '' return fq_name(self.partition, self._values['irule']) @property def description(self): if self._values['description'] is None: return None if self._values['description'] == '': return '' return self._values['description'] @property def schedule(self): if self._values['schedule'] is None: return None if self._values['schedule'] == '': return '' return fq_name(self.partition, self._values['schedule']) @property def source(self): result = [] if self._values['source'] is None: return None for x in self._values['source']: if 'address' in x and x['address'] is not None: result += [('address', x['address'])] elif 'address_range' in x and x['address_range'] is not None: result += [('address', x['address_range'])] elif 'address_list' in x and x['address_list'] is not None: result += [('address_list', x['address_list'])] elif 'country' in x and x['country'] is not None: result += [('geo', x['country'])] elif 'vlan' in x and x['vlan'] is not None: result += [('vlan', fq_name(self.partition, x['vlan']))] elif 'port' in x and x['port'] is not None: result += [('port', str(x['port']))] elif 'port_range' in x and x['port_range'] is not None: result += [('port', x['port_range'])] elif 'port_list' in x and x['port_list'] is not None: result += [('port_list', fq_name(self.partition, x['port_list']))] if result: return result return None @property def destination(self): result = [] if self._values['destination'] is None: return None for x in self._values['destination']: if 'address' in x and x['address'] is not None: result += [('address', x['address'])] elif 'address_range' in x and x['address_range'] is not None: result += [('address', x['address_range'])] elif 'address_list' in x and x['address_list'] is not None: result += [('address_list', x['address_list'])] elif 'country' in x and x['country'] is not None: result += [('geo', x['country'])] elif 'port' in x and x['port'] is not None: result += [('port', str(x['port']))] elif 'port_range' in x and x['port_range'] is not None: result += [('port', x['port_range'])] elif 'port_list' in x and x['port_list'] is not None: result += [('port_list', fq_name(self.partition, x['port_list']))] if result: return result return None @property def icmp_message(self): if self._values['icmp_message'] is None: return None result = [] for x in self._values['icmp_message']: type = x.get('type', '255') code = x.get('code', '255') if type is None or type == 'any': type = '255' if code is None or code == 'any': code = '255' if type == '255' and code == '255': result.append("255") elif type == '255' and code != '255': raise F5ModuleError( "A type of 'any' (255) requires a code of 'any'." ) elif code == '255': result.append(type) else: result.append('{0}:{1}'.format(type, code)) result = list(set(result)) return result @property def rule_list(self): if self._values['rule_list'] is None: return None if self._values['parent_policy'] is not None: return fq_name(self.partition, self._values['rule_list']) return None class Changes(Parameters): def to_return(self): result = {} try: for returnable in self.returnables: result[returnable] = getattr(self, returnable) result = self._filter_params(result) except Exception: pass return result class UsableChanges(Changes): @property def logging(self): if self._values['logging'] is None: return None if self._values['logging'] is True: return "yes" return "no" @property def source(self): if self._values['source'] is None: return None result = dict( addresses=[], addressLists=[], vlans=[], geo=[], ports=[], portLists=[] ) for x in self._values['source']: if x[0] == 'address': result['addresses'].append({'name': x[1]}) elif x[0] == 'address_list': result['addressLists'].append(x[1]) elif x[0] == 'vlan': result['vlans'].append(x[1]) elif x[0] == 'geo': result['geo'].append({'name': x[1]}) elif x[0] == 'port': result['ports'].append({'name': str(x[1])}) elif x[0] == 'port_list': result['portLists'].append(x[1]) return result @property def destination(self): if self._values['destination'] is None: return None result = dict( addresses=[], addressLists=[], vlans=[], geo=[], ports=[], portLists=[] ) for x in self._values['destination']: if x[0] == 'address': result['addresses'].append({'name': x[1]}) elif x[0] == 'address_list': result['addressLists'].append(x[1]) elif x[0] == 'geo': result['geo'].append({'name': x[1]}) elif x[0] == 'port': result['ports'].append({'name': str(x[1])}) elif x[0] == 'port_list': result['portLists'].append(x[1]) return result @property def icmp_message(self): if self._values['icmp_message'] is None: return None result = [] for x in self._values['icmp_message']: result.append({'name': x}) return result class ReportableChanges(Changes): @property def source(self): if self._values['source'] is None: return None result = [] v = self._values['source'] if v['addressLists']: result += [('address_list', x) for x in v['addressLists']] if v['vlans']: result += [('vlan', x) for x in v['vlans']] if v['geo']: result += [('geo', x['name']) for x in v['geo']] if v['addresses']: result += [('address', x['name']) for x in v['addresses']] if v['ports']: result += [('port', str(x)) for x in v['ports']] if v['portLists']: result += [('port_list', x['name']) for x in v['portLists']] if result: return dict(result) return None @property def destination(self): if self._values['destination'] is None: return None result = [] v = self._values['destination'] if v['addressLists']: result += [('address_list', x) for x in v['addressLists']] if v['geo']: result += [('geo', x['name']) for x in v['geo']] if v['addresses']: result += [('address', x['name']) for x in v['addresses']] if v['ports']: result += [('port', str(x)) for x in v['ports']] if v['portLists']: result += [('port_list', x['name']) for x in v['portLists']] if result: return dict(result) return None class Difference(object): def __init__(self, want, have=None): self.want = want self.have = have def compare(self, param): try: result = getattr(self, param) return result except AttributeError: return self.__default(param) def __default(self, param): attr1 = getattr(self.want, param) try: attr2 = getattr(self.have, param) if attr1 != attr2: return attr1 except AttributeError: return attr1 @property def irule(self): if self.want.irule is None: return None if self.have.irule is None and self.want.irule == '': return None if self.have.irule is None: return self.want.irule if self.want.irule != self.have.irule: return self.want.irule @property def description(self): if self.want.description is None: return None if self.have.description is None and self.want.description == '': return None if self.have.description is None: return self.want.description if self.want.description != self.have.description: return self.want.description @property def source(self): if self.want.source is None: return None if self.want.source is None and self.have.source is None: return None if self.have.source is None: return self.want.source if set(self.want.source) != set(self.have.source): return self.want.source @property def destination(self): if self.want.destination is None: return None if self.want.destination is None and self.have.destination is None: return None if self.have.destination is None: return self.want.destination if set(self.want.destination) != set(self.have.destination): return self.want.destination @property def icmp_message(self): if self.want.icmp_message is None: return None if self.want.icmp_message is None and self.have.icmp_message is None: return None if self.have.icmp_message is None: return self.want.icmp_message if set(self.want.icmp_message) != set(self.have.icmp_message): return self.want.icmp_message class ModuleManager(object): def __init__(self, *args, **kwargs): self.module = kwargs.get('module', None) self.client = F5RestClient(**self.module.params) self.want = ModuleParameters(params=self.module.params) self.have = ApiParameters() self.changes = UsableChanges() def _set_changed_options(self): changed = {} for key in Parameters.returnables: if getattr(self.want, key) is not None: changed[key] = getattr(self.want, key) if changed: self.changes = UsableChanges(params=changed) def _update_changed_options(self): diff = Difference(self.want, self.have) updatables = Parameters.updatables changed = dict() for k in updatables: change = diff.compare(k) if change is None: continue else: if isinstance(change, dict): changed.update(change) else: changed[k] = change if changed: self.changes = UsableChanges(params=changed) return True return False def should_update(self): result = self._update_changed_options() if result: return True return False def exec_module(self): changed = False result = dict() state = self.want.state if state == "present": changed = self.present() elif state == "absent": changed = self.absent() reportable = ReportableChanges(params=self.changes.to_return()) changes = reportable.to_return() result.update(**changes) result.update(dict(changed=changed)) self._announce_deprecations(result) return result def _announce_deprecations(self, result): warnings = result.pop('__warnings', []) for warning in warnings: self.client.module.deprecate( msg=warning['msg'], version=warning['version'] ) def present(self): if self.exists(): return self.update() else: return self.create() def exists(self): name = self.want.name if self.want.parent_policy: uri = "https://{0}:{1}/mgmt/tm/security/firewall/policy/{2}/rules/{3}".format( self.client.provider['server'], self.client.provider['server_port'], transform_name(self.want.partition, self.want.parent_policy), name.replace('/', '_') ) else: uri = "https://{0}:{1}/mgmt/tm/security/firewall/rule-list/{2}/rules/{3}".format( self.client.provider['server'], self.client.provider['server_port'], transform_name(self.want.partition, self.want.parent_rule_list), name.replace('/', '_') ) resp = self.client.api.get(uri) if resp.ok: return True return False def update(self): self.have = self.read_current_from_device() if not self.should_update(): return False if self.module.check_mode: return True self.update_on_device() return True def remove(self): if self.module.check_mode: return True self.remove_from_device() if self.exists(): raise F5ModuleError("Failed to delete the resource.") return True def create(self): self._set_changed_options() self.set_reasonable_creation_defaults() if self.want.status == 'scheduled' and self.want.schedule is None: raise F5ModuleError( "A 'schedule' must be specified when 'status' is 'scheduled'." ) if self.module.check_mode: return True self.create_on_device() return True def set_reasonable_creation_defaults(self): if self.want.action is None: self.changes.update({'action': 'reject'}) if self.want.logging is None: self.changes.update({'logging': False}) if self.want.status is None: self.changes.update({'status': 'enabled'}) def create_on_device(self): params = self.changes.api_params() name = self.want.name params['name'] = name.replace('/', '_') params['partition'] = self.want.partition params['placeAfter'] = 'last' if self.want.parent_policy: uri = "https://{0}:{1}/mgmt/tm/security/firewall/policy/{2}/rules/".format( self.client.provider['server'], self.client.provider['server_port'], transform_name(self.want.partition, self.want.parent_policy), ) else: uri = "https://{0}:{1}/mgmt/tm/security/firewall/rule-list/{2}/rules/".format( self.client.provider['server'], self.client.provider['server_port'], transform_name(self.want.partition, self.want.parent_rule_list), ) if self.changes.protocol not in ['icmp', 'icmpv6']: if self.changes.icmp_message is not None: raise F5ModuleError( "The 'icmp_message' can only be specified when 'protocol' is 'icmp' or 'icmpv6'." ) resp = self.client.api.post(uri, json=params) try: response = resp.json() except ValueError as ex: raise F5ModuleError(str(ex)) if 'code' in response and response['code'] in [400, 403, 404]: if 'message' in response: raise F5ModuleError(response['message']) else: raise F5ModuleError(resp.content) def update_on_device(self): name = self.want.name if self.want.parent_policy and self.want.rule_list: uri = "https://{0}:{1}/mgmt/tm/security/firewall/policy/{2}/rules/{3}".format( self.client.provider['server'], self.client.provider['server_port'], transform_name(self.want.partition, self.want.parent_policy), name.replace('/', '_') ) elif self.want.parent_policy: uri = "https://{0}:{1}/mgmt/tm/security/firewall/policy/{2}/rules/{3}".format( self.client.provider['server'], self.client.provider['server_port'], transform_name(self.want.partition, self.want.parent_policy), name.replace('/', '_') ) else: uri = "https://{0}:{1}/mgmt/tm/security/firewall/rule-list/{2}/rules/{3}".format( self.client.provider['server'], self.client.provider['server_port'], transform_name(self.want.partition, self.want.parent_rule_list), name.replace('/', '_') ) if self.have.protocol not in ['icmp', 'icmpv6'] and self.changes.protocol not in ['icmp', 'icmpv6']: if self.changes.icmp_message is not None: raise F5ModuleError( "The 'icmp_message' can only be specified when 'protocol' is 'icmp' or 'icmpv6'." ) if self.changes.protocol in ['icmp', 'icmpv6']: self.changes.update({'source': {}}) self.changes.update({'destination': {}}) params = self.changes.api_params() resp = self.client.api.patch(uri, json=params) try: response = resp.json() except ValueError as ex: raise F5ModuleError(str(ex)) if 'code' in response and response['code'] in [400, 403, 404]: if 'message' in response: raise F5ModuleError(response['message']) else: raise F5ModuleError(resp.content) def absent(self): if self.exists(): return self.remove() return False def remove_from_device(self): name = self.want.name if self.want.parent_policy: uri = "https://{0}:{1}/mgmt/tm/security/firewall/policy/{2}/rules/{3}".format( self.client.provider['server'], self.client.provider['server_port'], transform_name(self.want.partition, self.want.parent_policy), name.replace('/', '_') ) else: uri = "https://{0}:{1}/mgmt/tm/security/firewall/rule-list/{2}/rules/{3}".format( self.client.provider['server'], self.client.provider['server_port'], transform_name(self.want.partition, self.want.parent_rule_list), name.replace('/', '_') ) resp = self.client.api.delete(uri) if resp.status == 200: return True def read_current_from_device(self): if self.want.parent_policy: uri = "https://{0}:{1}/mgmt/tm/security/firewall/policy/{2}/rules/{3}".format( self.client.provider['server'], self.client.provider['server_port'], transform_name(self.want.partition, self.want.parent_policy), self.want.name ) else: uri = "https://{0}:{1}/mgmt/tm/security/firewall/rule-list/{2}/rules/{3}".format( self.client.provider['server'], self.client.provider['server_port'], transform_name(self.want.partition, self.want.parent_rule_list), self.want.name ) resp = self.client.api.get(uri) try: response = resp.json() except ValueError as ex: raise F5ModuleError(str(ex)) if 'code' in response and response['code'] == 400: if 'message' in response: raise F5ModuleError(response['message']) else: raise F5ModuleError(resp.content) return ApiParameters(params=response) class ArgumentSpec(object): def __init__(self): self.supports_check_mode = True argument_spec = dict( name=dict(required=True), parent_policy=dict(), parent_rule_list=dict(), logging=dict(type='bool'), protocol=dict(), irule=dict(), description=dict(), source=dict( type='list', elements='dict', options=dict( address=dict(), address_list=dict(), address_range=dict(), country=dict(), port=dict(type='int'), port_list=dict(), port_range=dict(), vlan=dict(), ), mutually_exclusive=[[ 'address', 'address_list', 'address_range', 'country', 'vlan', 'port', 'port_range', 'port_list' ]] ), destination=dict( type='list', elements='dict', options=dict( address=dict(), address_list=dict(), address_range=dict(), country=dict(), port=dict(type='int'), port_list=dict(), port_range=dict(), ), mutually_exclusive=[[ 'address', 'address_list', 'address_range', 'country', 'port', 'port_range', 'port_list' ]] ), action=dict( choices=['accept', 'drop', 'reject', 'accept-decisively'] ), status=dict( choices=['enabled', 'disabled', 'scheduled'] ), schedule=dict(), rule_list=dict(), icmp_message=dict( type='list', elements='dict', options=dict( type=dict(), code=dict(), ) ), partition=dict( default='Common', fallback=(env_fallback, ['F5_PARTITION']) ), state=dict( default='present', choices=['present', 'absent'] ) ) self.argument_spec = {} self.argument_spec.update(f5_argument_spec) self.argument_spec.update(argument_spec) self.mutually_exclusive = [ ['rule_list', 'action'], ['rule_list', 'source'], ['rule_list', 'destination'], ['rule_list', 'irule'], ['rule_list', 'protocol'], ['rule_list', 'logging'], ['parent_policy', 'parent_rule_list'] ] self.required_one_of = [ ['parent_policy', 'parent_rule_list'] ] def main(): spec = ArgumentSpec() module = AnsibleModule( argument_spec=spec.argument_spec, supports_check_mode=spec.supports_check_mode, mutually_exclusive=spec.mutually_exclusive, required_one_of=spec.required_one_of ) try: mm = ModuleManager(module=module) results = mm.exec_module() module.exit_json(**results) except F5ModuleError as ex: module.fail_json(msg=str(ex)) if __name__ == '__main__': main()
vdeluca/tfi
refs/heads/tfi
geonode/documents/autocomplete_light_registry.py
35
import autocomplete_light from models import Document autocomplete_light.register( Document, search_fields=['^title'], autocomplete_js_attributes={ 'placeholder': 'Document name..', }, )
PersonalGenomesOrg/open-humans
refs/heads/master
public_data/forms.py
2
from django.forms import BooleanField, CharField, Form class ConsentForm(Form): """ A subclass of django-user-account's SignupForm with a `terms` field to add validation for the Terms of Use checkbox. """ check_uncertainty = BooleanField( label=( "I understand the uncertainty and risk as stated " "in this feature activation process." ) ) check_any_purpose = BooleanField( label=( "I understand that data I choose to publicly share may be " "for any purpose, including research purposes." ) ) check_privacy = BooleanField( label=( "I understand that once I authorize public data sharing, " "data privacy laws might not apply or no longer protect my " "information." ) ) check_withdraw = BooleanField( label=( "I understand that I can turn off public data sharing at " "any time, but copies of that data that have already been " "made by other people may remain." ) ) check_rights = BooleanField( label=("By signing this form, I have not given up any of my " "legal rights.") ) check_eligible = BooleanField(label=("I am at least 18 years of age.")) check_name = BooleanField(label="I am signing this form with my full legal name.") class Meta: # noqa: D101 fields = "__all__"
yvaucher/stock-logistics-tracking
refs/heads/8.0
__unported__/stock_move_packaging/wizard/move_pack.py
4
# -*- coding: utf-8 -*- ################################################################################# # # OpenERP, Open Source Management Solution # Copyright (C) 2011 Julius Network Solutions SARL <contact@julius.fr> # # 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 openerp.osv import fields, osv, orm from openerp.tools.translate import _ from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT, DEFAULT_SERVER_DATE_FORMAT import time class stock_move_packaging(orm.TransientModel): _name = "stock.move.packaging" _columns = { 'pack_id': fields.many2one('stock.tracking', 'Pack to move', required=True), 'location_dest_id': fields.many2one('stock.location', 'Destination location', required=True), } _defaults = { 'pack_id': lambda s,cr,uid,c: c.get('active_id') or False, } def move_pack(self, cr, uid, ids, context=None): barcode_obj = self.pool.get('tr.barcode') tracking_obj = self.pool.get('stock.tracking') move_obj = self.pool.get('stock.move') history_obj = self.pool.get('stock.tracking.history') picking_obj = self.pool.get('stock.picking') if context == None: context = {} context.update({'from_pack':True}) for obj in self.browse(cr, uid, ids, context=context): pack = obj.pack_id if not pack or not obj.location_dest_id: continue """ This is related to the module stock_tracking_child TODO: remove this from this method to be able to install it without stock_tracking_child """ if pack.parent_id: raise osv.except_osv(_('Warning!'),_('You cannot move this pack because it\'s inside of an other pack: %s.') % (pack.parent_id.name)) for child in pack.child_ids: """ This is related to the module stock_tracking_state TODO: remove this from this method to be able to install it without stock_tracking_state """ if child.state != 'close': raise osv.except_osv(_('Warning!'),_('You cannot move this pack because there is a none closed pack inside of it: %s.') % (child.name)) current_type = pack.location_id.usage dest_type = obj.location_dest_id.usage pick_type = 'out' if type == 'internal': pick_type = 'internal' elif type == 'supplier': pick_type = 'in' elif type == 'customer': pick_type = 'out' date = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT), pick_id = picking_obj.create(cr, uid, { 'type': pick_type, 'auto_picking': 'draft', 'company_id': self.pool.get('res.company')._company_default_get(cr, uid, 'stock.company', context=context), 'address_id': obj.location_dest_id.address_id and obj.location_dest_id.address_id.id or False, 'invoice_state': 'none', 'date': date, 'state': 'done', }, context=context) child_packs = tracking_obj.hierarchy_ids(pack) for child_pack in child_packs: hist_id = history_obj.create(cr, uid, { 'tracking_id': child_pack.id, 'type': 'move', 'location_id': child_pack.location_id.id, 'location_dest_id': obj.location_dest_id.id, }, context=context) for move in child_pack.current_move_ids: defaults = { 'location_id': move.location_dest_id.id, 'location_dest_id': obj.location_dest_id.id, 'picking_id': pick_id, 'state': 'done', 'date': date, 'date_expected': date, } new_id = move_obj.copy(cr, uid, move.id, default=defaults, context=context) move_obj.write(cr, uid, [move.id], {'pack_history_id': hist_id, 'move_dest_id': new_id}, context=context) tracking_obj.write(cr, uid, [child_pack.id], {'location_id': obj.location_dest_id.id}, context=context) return {'type': 'ir.actions.act_window_close'} # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
yuifan/pexus4_external_regex-re2
refs/heads/pexus_kt
re2/make_unicode_groups.py
219
#!/usr/bin/python # Copyright 2008 The RE2 Authors. All Rights Reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. """Generate C++ tables for Unicode Script and Category groups.""" import sys import unicode _header = """ // GENERATED BY make_unicode_groups.py; DO NOT EDIT. // make_unicode_groups.py >unicode_groups.cc #include "re2/unicode_groups.h" namespace re2 { """ _trailer = """ } // namespace re2 """ n16 = 0 n32 = 0 def MakeRanges(codes): """Turn a list like [1,2,3,7,8,9] into a range list [[1,3], [7,9]]""" ranges = [] last = -100 for c in codes: if c == last+1: ranges[-1][1] = c else: ranges.append([c, c]) last = c return ranges def PrintRanges(type, name, ranges): """Print the ranges as an array of type named name.""" print "static %s %s[] = {" % (type, name,) for lo, hi in ranges: print "\t{ %d, %d }," % (lo, hi) print "};" # def PrintCodes(type, name, codes): # """Print the codes as an array of type named name.""" # print "static %s %s[] = {" % (type, name,) # for c in codes: # print "\t%d," % (c,) # print "};" def PrintGroup(name, codes): """Print the data structures for the group of codes. Return a UGroup literal for the group.""" # See unicode_groups.h for a description of the data structure. # Split codes into 16-bit ranges and 32-bit ranges. range16 = MakeRanges([c for c in codes if c < 65536]) range32 = MakeRanges([c for c in codes if c >= 65536]) # Pull singleton ranges out of range16. # code16 = [lo for lo, hi in range16 if lo == hi] # range16 = [[lo, hi] for lo, hi in range16 if lo != hi] global n16 global n32 n16 += len(range16) n32 += len(range32) ugroup = "{ \"%s\", +1" % (name,) # if len(code16) > 0: # PrintCodes("uint16", name+"_code16", code16) # ugroup += ", %s_code16, %d" % (name, len(code16)) # else: # ugroup += ", 0, 0" if len(range16) > 0: PrintRanges("URange16", name+"_range16", range16) ugroup += ", %s_range16, %d" % (name, len(range16)) else: ugroup += ", 0, 0" if len(range32) > 0: PrintRanges("URange32", name+"_range32", range32) ugroup += ", %s_range32, %d" % (name, len(range32)) else: ugroup += ", 0, 0" ugroup += " }" return ugroup def main(): print _header ugroups = [] for name, codes in unicode.Categories().iteritems(): ugroups.append(PrintGroup(name, codes)) for name, codes in unicode.Scripts().iteritems(): ugroups.append(PrintGroup(name, codes)) print "// %d 16-bit ranges, %d 32-bit ranges" % (n16, n32) print "UGroup unicode_groups[] = {"; ugroups.sort() for ug in ugroups: print "\t%s," % (ug,) print "};" print "int num_unicode_groups = %d;" % (len(ugroups),) print _trailer if __name__ == '__main__': main()
robovm/robovm-studio
refs/heads/master
python/lib/Lib/site-packages/django/utils/xmlutils.py
734
""" Utilities for XML generation/parsing. """ from xml.sax.saxutils import XMLGenerator class SimplerXMLGenerator(XMLGenerator): def addQuickElement(self, name, contents=None, attrs=None): "Convenience method for adding an element with no children" if attrs is None: attrs = {} self.startElement(name, attrs) if contents is not None: self.characters(contents) self.endElement(name)
gsnbng/erpnext
refs/heads/develop
erpnext/accounts/doctype/purchase_invoice_item/purchase_invoice_item.py
120
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document from erpnext.controllers.print_settings import print_settings_for_item_table class PurchaseInvoiceItem(Document): def __setup__(self): print_settings_for_item_table(self)
kstaniek/condoor
refs/heads/master
condoor/drivers/XE.py
1
"""This is IOS XE driver implementation.""" from functools import partial import re from condoor.drivers.IOS import Driver as IOSDriver from condoor import pattern_manager, TIMEOUT, EOF from condoor.actions import a_send_line, a_send, a_disconnect, a_message_callback, a_return_and_reconnect from condoor.fsm import FSM from condoor.exceptions import ConnectionError # based on IOS driver class Driver(IOSDriver): """This is a Driver class implementation for IOS XR.""" platform = 'XE' families = { "ASR-9": "ASR900", "ASR1": "ASR1K", "WS-C4500": "C4500-X" } def __init__(self, device): """Initialize the IOS XE driver object.""" super(Driver, self).__init__(device) def update_driver(self, prompt): """Return driver name based on prompt analysis.""" if "-stby" in prompt: raise ConnectionError("Standby console detected") return pattern_manager.platform(prompt, ['XE']) def reload(self, reload_timeout=300, save_config=True): """Reload the device. CSM_DUT#reload System configuration has been modified. Save? [yes/no]: yes Building configuration... [OK] Proceed with reload? [confirm] """ SAVE_CONFIG = re.compile(re.escape("System configuration has been modified. Save? [yes/no]: ")) PROCEED = re.compile(re.escape("Proceed with reload? [confirm]")) IMAGE = re.compile("Passing control to the main image") BOOTSTRAP = re.compile("System Bootstrap") LOCATED = re.compile("Located .*") RETURN = re.compile(re.escape("Press RETURN to get started!")) response = "yes" if save_config else "no" # 0 1 2 3 4 events = [SAVE_CONFIG, PROCEED, LOCATED, RETURN, self.username_re, self.password_re, BOOTSTRAP, IMAGE, TIMEOUT, EOF] # 5 6 7 8 9 transitions = [ (SAVE_CONFIG, [0], 1, partial(a_send_line, response), 60), (PROCEED, [0, 1], 2, partial(a_send, "\r"), reload_timeout), (LOCATED, [2], 2, a_message_callback, reload_timeout), # if timeout try to send the reload command again (TIMEOUT, [0], 0, partial(a_send_line, self.reload_cmd), 10), (BOOTSTRAP, [2], -1, a_disconnect, reload_timeout), (IMAGE, [2], 3, a_message_callback, reload_timeout), (self.username_re, [3], -1, a_return_and_reconnect, 0), (self.password_re, [3], -1, a_return_and_reconnect, 0), (RETURN, [3], -1, a_return_and_reconnect, 0), (TIMEOUT, [2], -1, a_disconnect, 0), (EOF, [0, 1, 2, 3], -1, a_disconnect, 0) ] fsm = FSM("IOS-RELOAD", self.device, events, transitions, timeout=10) return fsm.run()
chovanecm/sacredboard
refs/heads/develop
sacredboard/app/data/__init__.py
1
"""Sacred(board) Data Access Layer.""" from sacredboard.app.data.errors import NotFoundError, DataSourceError from .datastorage import Cursor, DataStorage from .metricsdao import MetricsDAO __all__ = ["Cursor", "DataStorage", "MetricsDAO", "NotFoundError", "DataSourceError"]
numenta/nupic
refs/heads/master
external/linux32/lib/python2.6/site-packages/matplotlib/numerix/npyma/__init__.py
70
from matplotlib.numerix import use_maskedarray if use_maskedarray: from maskedarray import * print "using maskedarray" else: try: from numpy.ma import * # numpy 1.05 and later except ImportError: from numpy.core.ma import * # earlier #print "using ma"
CoderBotOrg/coderbotsrv
refs/heads/master
server/lib/pyasn1_modules/rfc2315.py
127
# # PKCS#7 message syntax # # ASN.1 source from: # http://www.trl.ibm.com/projects/xml/xss4j/data/asn1/grammars/pkcs7.asn # # Sample captures from: # openssl crl2pkcs7 -nocrl -certfile cert1.cer -out outfile.p7b # from pyasn1.type import tag,namedtype,namedval,univ,constraint,char,useful from pyasn1_modules.rfc2459 import * class Attribute(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('type', AttributeType()), namedtype.NamedType('values', univ.SetOf(componentType=AttributeValue())) ) class AttributeValueAssertion(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('attributeType', AttributeType()), namedtype.NamedType('attributeValue', AttributeValue()) ) pkcs_7 = univ.ObjectIdentifier('1.2.840.113549.1.7') data = univ.ObjectIdentifier('1.2.840.113549.1.7.1') signedData = univ.ObjectIdentifier('1.2.840.113549.1.7.2') envelopedData = univ.ObjectIdentifier('1.2.840.113549.1.7.3') signedAndEnvelopedData = univ.ObjectIdentifier('1.2.840.113549.1.7.4') digestedData = univ.ObjectIdentifier('1.2.840.113549.1.7.5') encryptedData = univ.ObjectIdentifier('1.2.840.113549.1.7.6') class ContentType(univ.ObjectIdentifier): pass class ContentEncryptionAlgorithmIdentifier(AlgorithmIdentifier): pass class EncryptedContent(univ.OctetString): pass class EncryptedContentInfo(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('contentType', ContentType()), namedtype.NamedType('contentEncryptionAlgorithm', ContentEncryptionAlgorithmIdentifier()), namedtype.OptionalNamedType('encryptedContent', EncryptedContent().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0))) ) class Version(univ.Integer): pass # overrides x509.Version class EncryptedData(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('version', Version()), namedtype.NamedType('encryptedContentInfo', EncryptedContentInfo()) ) class DigestAlgorithmIdentifier(AlgorithmIdentifier): pass class DigestAlgorithmIdentifiers(univ.SetOf): componentType = DigestAlgorithmIdentifier() class Digest(univ.OctetString): pass class ContentInfo(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('contentType', ContentType()), namedtype.OptionalNamedType('content', univ.Any().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0))) ) class DigestedData(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('version', Version()), namedtype.NamedType('digestAlgorithm', DigestAlgorithmIdentifier()), namedtype.NamedType('contentInfo', ContentInfo()), namedtype.NamedType('digest', Digest) ) class IssuerAndSerialNumber(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('issuer', Name()), namedtype.NamedType('serialNumber', CertificateSerialNumber()) ) class KeyEncryptionAlgorithmIdentifier(AlgorithmIdentifier): pass class EncryptedKey(univ.OctetString): pass class RecipientInfo(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('version', Version()), namedtype.NamedType('issuerAndSerialNumber', IssuerAndSerialNumber()), namedtype.NamedType('keyEncryptionAlgorithm', KeyEncryptionAlgorithmIdentifier()), namedtype.NamedType('encryptedKey', EncryptedKey()) ) class RecipientInfos(univ.SetOf): componentType = RecipientInfo() class Attributes(univ.SetOf): componentType = Attribute() class ExtendedCertificateInfo(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('version', Version()), namedtype.NamedType('certificate', Certificate()), namedtype.NamedType('attributes', Attributes()) ) class SignatureAlgorithmIdentifier(AlgorithmIdentifier): pass class Signature(univ.BitString): pass class ExtendedCertificate(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('extendedCertificateInfo', ExtendedCertificateInfo()), namedtype.NamedType('signatureAlgorithm', SignatureAlgorithmIdentifier()), namedtype.NamedType('signature', Signature()) ) class ExtendedCertificateOrCertificate(univ.Choice): componentType = namedtype.NamedTypes( namedtype.NamedType('certificate', Certificate()), namedtype.NamedType('extendedCertificate', ExtendedCertificate().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0))) ) class ExtendedCertificatesAndCertificates(univ.SetOf): componentType = ExtendedCertificateOrCertificate() class SerialNumber(univ.Integer): pass class CRLEntry(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('userCertificate', SerialNumber()), namedtype.NamedType('revocationDate', useful.UTCTime()) ) class TBSCertificateRevocationList(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('signature', AlgorithmIdentifier()), namedtype.NamedType('issuer', Name()), namedtype.NamedType('lastUpdate', useful.UTCTime()), namedtype.NamedType('nextUpdate', useful.UTCTime()), namedtype.OptionalNamedType('revokedCertificates', univ.SequenceOf(componentType=CRLEntry())) ) class CertificateRevocationList(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('tbsCertificateRevocationList', TBSCertificateRevocationList()), namedtype.NamedType('signatureAlgorithm', AlgorithmIdentifier()), namedtype.NamedType('signature', univ.BitString()) ) class CertificateRevocationLists(univ.SetOf): componentType = CertificateRevocationList() class DigestEncryptionAlgorithmIdentifier(AlgorithmIdentifier): pass class EncryptedDigest(univ.OctetString): pass class SignerInfo(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('version', Version()), namedtype.NamedType('issuerAndSerialNumber', IssuerAndSerialNumber()), namedtype.NamedType('digestAlgorithm', DigestAlgorithmIdentifier()), namedtype.OptionalNamedType('authenticatedAttributes', Attributes().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0))), namedtype.NamedType('digestEncryptionAlgorithm', DigestEncryptionAlgorithmIdentifier()), namedtype.NamedType('encryptedDigest', EncryptedDigest()), namedtype.OptionalNamedType('unauthenticatedAttributes', Attributes().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 1))) ) class SignerInfos(univ.SetOf): componentType = SignerInfo() class SignedAndEnvelopedData(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('version', Version()), namedtype.NamedType('recipientInfos', RecipientInfos()), namedtype.NamedType('digestAlgorithms', DigestAlgorithmIdentifiers()), namedtype.NamedType('encryptedContentInfo', EncryptedContentInfo()), namedtype.OptionalNamedType('certificates', ExtendedCertificatesAndCertificates().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0))), namedtype.OptionalNamedType('crls', CertificateRevocationLists().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 1))), namedtype.NamedType('signerInfos', SignerInfos()) ) class EnvelopedData(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('version', Version()), namedtype.NamedType('recipientInfos', RecipientInfos()), namedtype.NamedType('encryptedContentInfo', EncryptedContentInfo()) ) class DigestInfo(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('digestAlgorithm', DigestAlgorithmIdentifier()), namedtype.NamedType('digest', Digest()) ) class SignedData(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('version', Version()), namedtype.NamedType('digestAlgorithms', DigestAlgorithmIdentifiers()), namedtype.NamedType('contentInfo', ContentInfo()), namedtype.OptionalNamedType('certificates', ExtendedCertificatesAndCertificates().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0))), namedtype.OptionalNamedType('crls', CertificateRevocationLists().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 1))), namedtype.NamedType('signerInfos', SignerInfos()) ) class Data(univ.OctetString): pass
yahoo/pulsar
refs/heads/master
pulsar-functions/python-examples/native_exclamation_function.py
9
#!/usr/bin/env python # # 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. # def process(input): return input + '!'
qualitio/qualitio
refs/heads/master
qualitio/core/custommodel/management/commands/remove_customizations.py
1
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import inspect from operator import itemgetter, attrgetter from subprocess import call from optparse import make_option from django.db import connection, transaction from qualitio import customizations from qualitio.core.custommodel.models import ModelCustomization from qualitio.core.custommodel.management.commands.refresh_customizations import BaseCustomizationCommand from south.models import MigrationHistory CONFIRMATION = """ Are you really sure you want to delete all information about customizations? Here is a list of changes: * all customization migrations will be removed (customizations/migrations/ directory), * migration history of customizations module from database will be removed, * tables of all customizations models will be droped. Are you sure you want to run? (y/n): """ class Command(BaseCustomizationCommand): option_list = list(BaseCustomizationCommand.option_list) + [ # verbose option is already there make_option('--no-interactive', action="store_false", dest="interactive", default=True, help="No interactive mode. Use it only if you know what you are doing."), ] help = "Remove all customizations." def remove_customizations_migrations_directory(self, verbose=True): if verbose: self.print_verbose_msg("Deleting qualitio/customizations/migration directory.") try: return call(['rm', '-rf', self.customizations_migrations_dir_path()]) == 0 except OSError as e: return False def remove_history_of_customizations_migrations_from_database(self, verbose=True): if verbose: self.print_verbose_msg("Deleting history of customizations migrations from database.") MigrationHistory.objects.filter(app_name='customizations').delete() def _filter_customization_models(self): def predicate(tuple_info): # inspect.getmembers returns list of (name, classinfo) tuples name, cls = tuple_info return inspect.isclass(cls) and issubclass(cls, ModelCustomization) and cls is not ModelCustomization # here we want only classinfo objects return map(itemgetter(1), filter(predicate, inspect.getmembers(customizations.models))) def _get_customization_models_table_names(self): return map(attrgetter('_meta.db_table'), self._filter_customization_models()) def drop_customizations_tables(self, verbose=True): if verbose: self.print_verbose_msg("Droping tables") cursor = connection.cursor() for table in self._get_customization_models_table_names(): cursor.execute('DROP TABLE %s;' % table) transaction.commit_unless_managed() def handle_noargs(self, **options): verbose = options.get('verbose') if options.get('interactive'): answer = raw_input(CONFIRMATION) while answer not in ['y', 'n']: answer = raw_input(" choose 'y'(yes) or 'n'(no): ") if answer is not 'y': return self.remove_customizations_migrations_directory(verbose=verbose) self.remove_history_of_customizations_migrations_from_database(verbose=verbose) self.drop_customizations_tables(verbose=verbose)
Mariatta/pythondotorg
refs/heads/master
minutes/migrations/0002_auto_20150416_1853.py
12
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('minutes', '0001_initial'), ] operations = [ migrations.AlterField( model_name='minutes', name='content_markup_type', field=models.CharField(max_length=30, default='restructuredtext', choices=[('', '--'), ('html', 'HTML'), ('plain', 'Plain'), ('markdown', 'Markdown'), ('restructuredtext', 'Restructured Text')]), preserve_default=True, ), ]
DavidGuben/rcbplayspokemon
refs/heads/master
app/pywin32-220/com/win32com/demos/excelAddin.py
35
# A demo plugin for Microsoft Excel # # This addin simply adds a new button to the main Excel toolbar, # and displays a message box when clicked. Thus, it demonstrates # how to plug in to Excel itself, and hook Excel events. # # # To register the addin, simply execute: # excelAddin.py # This will install the COM server, and write the necessary # AddIn key to Excel # # To unregister completely: # excelAddin.py --unregister # # To debug, execute: # excelAddin.py --debug # # Then open Pythonwin, and select "Tools->Trace Collector Debugging Tool" # Restart excel, and you should see some output generated. # # NOTE: If the AddIn fails with an error, Excel will re-register # the addin to not automatically load next time Excel starts. To # correct this, simply re-register the addin (see above) # # Author <ekoome@yahoo.com> Eric Koome # Copyright (c) 2003 Wavecom Inc. All rights reserved # # Redistribution and use in source and binary forms, with or without #modification, are permitted provided that the following conditions #are met: # #1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 ERIC KOOME OR # ITS 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. from win32com import universal from win32com.server.exception import COMException from win32com.client import gencache, DispatchWithEvents import winerror import pythoncom from win32com.client import constants, Dispatch import sys # Support for COM objects we use. gencache.EnsureModule('{00020813-0000-0000-C000-000000000046}', 0, 1, 3, bForDemand=True) # Excel 9 gencache.EnsureModule('{2DF8D04C-5BFA-101B-BDE5-00AA0044DE52}', 0, 2, 1, bForDemand=True) # Office 9 # The TLB defiining the interfaces we implement universal.RegisterInterfaces('{AC0714F2-3D04-11D1-AE7D-00A0C90F26F4}', 0, 1, 0, ["_IDTExtensibility2"]) class ButtonEvent: def OnClick(self, button, cancel): import win32ui # Possible, but not necessary, to use a Pythonwin GUI import win32con win32ui.MessageBox("Hello from Python", "Python Test",win32con.MB_OKCANCEL) return cancel class ExcelAddin: _com_interfaces_ = ['_IDTExtensibility2'] _public_methods_ = [] _reg_clsctx_ = pythoncom.CLSCTX_INPROC_SERVER _reg_clsid_ = "{C5482ECA-F559-45A0-B078-B2036E6F011A}" _reg_progid_ = "Python.Test.ExcelAddin" _reg_policy_spec_ = "win32com.server.policy.EventHandlerPolicy" def __init__(self): self.appHostApp = None def OnConnection(self, application, connectMode, addin, custom): print "OnConnection", application, connectMode, addin, custom try: self.appHostApp = application cbcMyBar = self.appHostApp.CommandBars.Add(Name="PythonBar", Position=constants.msoBarTop, MenuBar=constants.msoBarTypeNormal, Temporary=True) btnMyButton = cbcMyBar.Controls.Add(Type=constants.msoControlButton, Parameter="Greetings") btnMyButton=self.toolbarButton = DispatchWithEvents(btnMyButton, ButtonEvent) btnMyButton.Style = constants.msoButtonCaption btnMyButton.BeginGroup = True btnMyButton.Caption = "&Python" btnMyButton.TooltipText = "Python rules the World" btnMyButton.Width = "34" cbcMyBar.Visible = True except pythoncom.com_error, (hr, msg, exc, arg): print "The Excel call failed with code %d: %s" % (hr, msg) if exc is None: print "There is no extended error information" else: wcode, source, text, helpFile, helpId, scode = exc print "The source of the error is", source print "The error message is", text print "More info can be found in %s (id=%d)" % (helpFile, helpId) def OnDisconnection(self, mode, custom): print "OnDisconnection" self.appHostApp.CommandBars("PythonBar").Delete self.appHostApp=None def OnAddInsUpdate(self, custom): print "OnAddInsUpdate", custom def OnStartupComplete(self, custom): print "OnStartupComplete", custom def OnBeginShutdown(self, custom): print "OnBeginShutdown", custom def RegisterAddin(klass): import _winreg key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Office\\Excel\\Addins") subkey = _winreg.CreateKey(key, klass._reg_progid_) _winreg.SetValueEx(subkey, "CommandLineSafe", 0, _winreg.REG_DWORD, 0) _winreg.SetValueEx(subkey, "LoadBehavior", 0, _winreg.REG_DWORD, 3) _winreg.SetValueEx(subkey, "Description", 0, _winreg.REG_SZ, "Excel Addin") _winreg.SetValueEx(subkey, "FriendlyName", 0, _winreg.REG_SZ, "A Simple Excel Addin") def UnregisterAddin(klass): import _winreg try: _winreg.DeleteKey(_winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Office\\Excel\\Addins\\" + klass._reg_progid_) except WindowsError: pass if __name__ == '__main__': import win32com.server.register win32com.server.register.UseCommandLine(ExcelAddin) if "--unregister" in sys.argv: UnregisterAddin(ExcelAddin) else: RegisterAddin(ExcelAddin)
nikephoroscoin/nikephoroscoin
refs/heads/master
share/qt/make_spinner.py
4415
#!/usr/bin/env python # W.J. van der Laan, 2011 # Make spinning .mng animation from a .png # Requires imagemagick 6.7+ from __future__ import division from os import path from PIL import Image from subprocess import Popen SRC='img/reload_scaled.png' DST='../../src/qt/res/movies/update_spinner.mng' TMPDIR='/tmp' TMPNAME='tmp-%03i.png' NUMFRAMES=35 FRAMERATE=10.0 CONVERT='convert' CLOCKWISE=True DSIZE=(16,16) im_src = Image.open(SRC) if CLOCKWISE: im_src = im_src.transpose(Image.FLIP_LEFT_RIGHT) def frame_to_filename(frame): return path.join(TMPDIR, TMPNAME % frame) frame_files = [] for frame in xrange(NUMFRAMES): rotation = (frame + 0.5) / NUMFRAMES * 360.0 if CLOCKWISE: rotation = -rotation im_new = im_src.rotate(rotation, Image.BICUBIC) im_new.thumbnail(DSIZE, Image.ANTIALIAS) outfile = frame_to_filename(frame) im_new.save(outfile, 'png') frame_files.append(outfile) p = Popen([CONVERT, "-delay", str(FRAMERATE), "-dispose", "2"] + frame_files + [DST]) p.communicate()