code
stringlengths
2
1.05M
repo_name
stringlengths
5
104
path
stringlengths
4
251
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
#!/usr/bin/env python # Copyright 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import generate_unexpire_flags import os import unittest class TestUnexpireGenerator(unittest.TestCase): TEST_MSTONE = 123 def read_golden_file(self, extension): return file( os.path.join( os.path.dirname(__file__), 'unexpire_test.' + extension + '.expected')).read() def testCcFile(self): cc = generate_unexpire_flags.gen_features_impl('foobar', 123) golden_cc = self.read_golden_file('cc') self.assertEquals(golden_cc, cc) def testHFile(self): h = generate_unexpire_flags.gen_features_header('foobar', 123) golden_h = self.read_golden_file('h') self.assertEquals(golden_h, h) def testIncFile(self): inc = generate_unexpire_flags.gen_flags_fragment('foobar', 123) golden_inc = self.read_golden_file('inc') self.assertEquals(golden_inc, inc) if __name__ == '__main__': unittest.main()
nwjs/chromium.src
tools/flags/generate_unexpire_flags_unittests.py
Python
bsd-3-clause
1,062
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from benchmarks import press from telemetry import benchmark from page_sets import dromaeo_pages @benchmark.Info(component='Blink>Bindings', emails=['jbroman@chromium.org', 'yukishiino@chromium.org', 'haraken@chromium.org']) # pylint: disable=protected-access class DromaeoBenchmark(press._PressBenchmark): @classmethod def Name(cls): return 'dromaeo' def CreateStorySet(self, options): return dromaeo_pages.DromaeoStorySet()
scheib/chromium
tools/perf/benchmarks/dromaeo.py
Python
bsd-3-clause
675
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. from __future__ import absolute_import, division, print_function import abc import os import six from cryptography import utils from cryptography.exceptions import AlreadyFinalized from cryptography.hazmat.bindings.utils import LazyLibrary, build_ffi with open(os.path.join(os.path.dirname(__file__), "src/padding.h")) as f: TYPES = f.read() with open(os.path.join(os.path.dirname(__file__), "src/padding.c")) as f: FUNCTIONS = f.read() _ffi = build_ffi(cdef_source=TYPES, verify_source=FUNCTIONS) _lib = LazyLibrary(_ffi) @six.add_metaclass(abc.ABCMeta) class PaddingContext(object): @abc.abstractmethod def update(self, data): """ Pads the provided bytes and returns any available data as bytes. """ @abc.abstractmethod def finalize(self): """ Finalize the padding, returns bytes. """ class PKCS7(object): def __init__(self, block_size): if not (0 <= block_size < 256): raise ValueError("block_size must be in range(0, 256).") if block_size % 8 != 0: raise ValueError("block_size must be a multiple of 8.") self.block_size = block_size def padder(self): return _PKCS7PaddingContext(self.block_size) def unpadder(self): return _PKCS7UnpaddingContext(self.block_size) @utils.register_interface(PaddingContext) class _PKCS7PaddingContext(object): def __init__(self, block_size): self.block_size = block_size # TODO: more copies than necessary, we should use zero-buffer (#193) self._buffer = b"" def update(self, data): if self._buffer is None: raise AlreadyFinalized("Context was already finalized.") if not isinstance(data, bytes): raise TypeError("data must be bytes.") self._buffer += data finished_blocks = len(self._buffer) // (self.block_size // 8) result = self._buffer[:finished_blocks * (self.block_size // 8)] self._buffer = self._buffer[finished_blocks * (self.block_size // 8):] return result def finalize(self): if self._buffer is None: raise AlreadyFinalized("Context was already finalized.") pad_size = self.block_size // 8 - len(self._buffer) result = self._buffer + six.int2byte(pad_size) * pad_size self._buffer = None return result @utils.register_interface(PaddingContext) class _PKCS7UnpaddingContext(object): def __init__(self, block_size): self.block_size = block_size # TODO: more copies than necessary, we should use zero-buffer (#193) self._buffer = b"" def update(self, data): if self._buffer is None: raise AlreadyFinalized("Context was already finalized.") if not isinstance(data, bytes): raise TypeError("data must be bytes.") self._buffer += data finished_blocks = max( len(self._buffer) // (self.block_size // 8) - 1, 0 ) result = self._buffer[:finished_blocks * (self.block_size // 8)] self._buffer = self._buffer[finished_blocks * (self.block_size // 8):] return result def finalize(self): if self._buffer is None: raise AlreadyFinalized("Context was already finalized.") if len(self._buffer) != self.block_size // 8: raise ValueError("Invalid padding bytes.") valid = _lib.Cryptography_check_pkcs7_padding( self._buffer, self.block_size // 8 ) if not valid: raise ValueError("Invalid padding bytes.") pad_size = six.indexbytes(self._buffer, -1) res = self._buffer[:-pad_size] self._buffer = None return res
deandunbar/html2bwml
venv/lib/python2.7/site-packages/cryptography/hazmat/primitives/padding.py
Python
mit
3,948
# -*- coding: utf-8 -*- """ *************************************************************************** r_li_renyi_ascii.py ------------------- Date : February 2016 Copyright : (C) 2016 by Médéric Ribreux Email : medspx at medspx dot 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 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ __author__ = 'Médéric Ribreux' __date__ = 'February 2016' __copyright__ = '(C) 2016, Médéric Ribreux' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' from .r_li import checkMovingWindow, configFile, moveOutputTxtFile def checkParameterValuesBeforeExecuting(alg, parameters, context): return checkMovingWindow(alg, parameters, context, True) def processCommand(alg, parameters, context, feedback): configFile(alg, parameters, context, feedback, True) def processOutputs(alg, parameters, context, feedback): moveOutputTxtFile(alg, parameters, context)
geopython/QGIS
python/plugins/processing/algs/grass7/ext/r_li_renyi_ascii.py
Python
gpl-2.0
1,538
#!/usr/bin/python # -*- coding: utf-8 -*- """ *** Description *** Converts a progression to chords, orchestrates them and plays them using fluidsynth. Make sure to set SF2 to a valid soundfont file. Based on play_progression.py """ from mingus.core import progressions, intervals from mingus.core import chords as ch from mingus.containers import NoteContainer, Note from mingus.midi import fluidsynth import time import sys from random import random, choice, randrange SF2 = 'soundfont.sf2' progression = ['I', 'bVdim7'] # progression = ["I", "vi", "ii", "iii7", "I7", "viidom7", "iii7", # "V7"] key = 'C' # If True every second iteration will be played in double time, starting on the # first double_time = True orchestrate_second = True swing = True play_solo = True play_drums = True play_bass = True play_chords = True bar_length = 1.75 song_end = 28 # Control beginning of solos and chords solo_start = 8 solo_end = 20 chord_start = 16 chord_end = 24 # Channels chord_channel = 1 chord_channel2 = 7 chord_channel3 = 3 bass_channel = 4 solo_channel = 13 random_solo_channel = False if not fluidsynth.init(SF2): print "Couldn't load soundfont", SF2 sys.exit(1) chords = progressions.to_chords(progression, key) loop = 1 while loop < song_end: i = 0 if random_solo_channel: solo_channel = choice(range(5, 8) + [11]) for chord in chords: c = NoteContainer(chords[i]) l = Note(c[0].name) n = Note('C') l.octave_down() l.octave_down() print ch.determine(chords[i])[0] if not swing and play_chords and loop > chord_start and loop\ < chord_end: fluidsynth.play_NoteContainer(c, chord_channel, randrange(50, 75)) if play_chords and loop > chord_start and loop < chord_end: if orchestrate_second: if loop % 2 == 0: fluidsynth.play_NoteContainer(c, chord_channel2, randrange(50, 75)) else: fluidsynth.play_NoteContainer(c, chord_channel2, randrange(50, 75)) if double_time: beats = [random() > 0.5 for x in range((loop % 2 + 1) * 8)] else: beats = [random() > 0.5 for x in range(8)] t = 0 for beat in beats: # Play random note if beat and play_solo and loop > solo_start and loop < solo_end: fluidsynth.stop_Note(n) if t % 2 == 0: n = Note(choice(c).name) elif random() > 0.5: if random() < 0.46: n = Note(intervals.second(choice(c).name, key)) elif random() < 0.46: n = Note(intervals.seventh(choice(c).name, key)) else: n = Note(choice(c).name) if t > 0 and t < len(beats) - 1: if beats[t - 1] and not beats[t + 1]: n = Note(choice(c).name) fluidsynth.play_Note(n, solo_channel, randrange(80, 110)) print n # Repeat chord on half of the bar if play_chords and t != 0 and loop > chord_start and loop\ < chord_end: if swing and random() > 0.95: fluidsynth.play_NoteContainer(c, chord_channel3, randrange(20, 75)) elif t % (len(beats) / 2) == 0 and t != 0: fluidsynth.play_NoteContainer(c, chord_channel3, randrange(20, 75)) # Play bass note if play_bass and t % 4 == 0 and t != 0: l = Note(choice(c).name) l.octave_down() l.octave_down() fluidsynth.play_Note(l, bass_channel, randrange(50, 75)) elif play_bass and t == 0: fluidsynth.play_Note(l, bass_channel, randrange(50, 75)) # Drums if play_drums and loop > 0: if t % (len(beats) / 2) == 0 and t != 0: fluidsynth.play_Note(Note('E', 2), 9, randrange(50, 100)) # snare else: if random() > 0.8 or t == 0: fluidsynth.play_Note(Note('C', 2), 9, randrange(20, 100)) # bass if t == 0 and random() > 0.75: fluidsynth.play_Note(Note('C#', 3), 9, randrange(60, 100)) # crash if swing: if random() > 0.9: fluidsynth.play_Note(Note('A#', 2), 9, randrange(50, 100)) # hihat open elif random() > 0.6: fluidsynth.play_Note(Note('G#', 2), 9, randrange(100, 120)) # hihat closed if random() > 0.95: fluidsynth.play_Note(Note('E', 2), 9, 100) # snare elif t % 2 == 0: fluidsynth.play_Note(Note('A#', 2), 9, 100) # hihat open else: if random() > 0.9: fluidsynth.play_Note(Note('E', 2), 9, 100) # snare if swing: if t % 2 == 0: time.sleep((bar_length / (len(beats) * 3)) * 4) else: time.sleep((bar_length / (len(beats) * 3)) * 2) else: time.sleep(bar_length / len(beats)) t += 1 fluidsynth.stop_NoteContainer(c, chord_channel) fluidsynth.stop_NoteContainer(c, chord_channel2) fluidsynth.stop_NoteContainer(c, chord_channel3) fluidsynth.stop_Note(l, bass_channel) fluidsynth.stop_Note(n, solo_channel) i += 1 print '-' * 20 loop += 1
yardex/python-mingus
mingus_examples/improviser/improviser.py
Python
gpl-3.0
5,915
# # -*- coding: utf-8 -*- # Copyright 2019 Red Hat # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ############################################# # WARNING # ############################################# # # This file is auto generated by the resource # module builder playbook. # # Do not edit this file manually. # # Changes to this file will be over written # by the resource module builder. # # Changes should be made in the model used to # generate this file or in the resource module # builder template. # ############################################# """ The arg spec for the nxos_interfaces module """ from __future__ import absolute_import, division, print_function __metaclass__ = type class InterfacesArgs(object): # pylint: disable=R0903 """The arg spec for the nxos_interfaces module """ def __init__(self, **kwargs): pass argument_spec = { 'config': { 'elements': 'dict', 'options': { 'description': { 'type': 'str' }, 'duplex': { 'choices': ['full', 'half', 'auto'], 'type': 'str' }, 'enabled': { 'default': True, 'type': 'bool' }, 'fabric_forwarding_anycast_gateway': { 'type': 'bool' }, 'ip_forward': { 'type': 'bool' }, 'mode': { 'choices': ['layer2', 'layer3'], 'type': 'str' }, 'mtu': { 'type': 'str' }, 'name': { 'required': True, 'type': 'str' }, 'speed': { 'type': 'str' } }, 'type': 'list' }, 'state': { 'choices': ['merged', 'replaced', 'overridden', 'deleted'], 'default': 'merged', 'type': 'str' } } # pylint: disable=C0301
sestrella/ansible
lib/ansible/module_utils/network/nxos/argspec/interfaces/interfaces.py
Python
gpl-3.0
2,238
#!/usr/bin/python # # Copyright (c) 2016 Matt Davis, <mdavis@ansible.com> # Chris Houseknecht, <house@redhat.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'curated'} DOCUMENTATION = ''' --- module: azure_rm_virtualmachine version_added: "2.1" short_description: Manage Azure virtual machines. description: - Create, update, stop and start a virtual machine. Provide an existing storage account and network interface or allow the module to create these for you. If you choose not to provide a network interface, the resource group must contain a virtual network with at least one subnet. - Currently requires an image found in the Azure Marketplace. Use azure_rm_virtualmachineimage_facts module to discover the publisher, offer, sku and version of a particular image. options: resource_group: description: - Name of the resource group containing the virtual machine. required: true name: description: - Name of the virtual machine. required: true state: description: - Assert the state of the virtual machine. - State 'present' will check that the machine exists with the requested configuration. If the configuration of the existing machine does not match, the machine will be updated. Use options started, allocated and restarted to change the machine's power state. - State 'absent' will remove the virtual machine. default: present required: false choices: - absent - present started: description: - Use with state 'present' to start the machine. Set to false to have the machine be 'stopped'. default: true required: false allocated: description: - Toggle that controls if the machine is allocated/deallocated, only useful with state='present'. default: True required: false restarted: description: - Use with state 'present' to restart a running VM. default: false required: false location: description: - Valid Azure location. Defaults to location of the resource group. default: null required: false short_hostname: description: - Name assigned internally to the host. On a linux VM this is the name returned by the `hostname` command. When creating a virtual machine, short_hostname defaults to name. default: null required: false vm_size: description: - A valid Azure VM size value. For example, 'Standard_D4'. The list of choices varies depending on the subscription and location. Check your subscription for available choices. default: Standard_D1 required: false admin_username: description: - Admin username used to access the host after it is created. Required when creating a VM. default: null required: false admin_password: description: - Password for the admin username. Not required if the os_type is Linux and SSH password authentication is disabled by setting ssh_password_enabled to false. default: null required: false ssh_password_enabled: description: - When the os_type is Linux, setting ssh_password_enabled to false will disable SSH password authentication and require use of SSH keys. default: true required: false ssh_public_keys: description: - "For os_type Linux provide a list of SSH keys. Each item in the list should be a dictionary where the dictionary contains two keys: path and key_data. Set the path to the default location of the authorized_keys files. On an Enterprise Linux host, for example, the path will be /home/<admin username>/.ssh/authorized_keys. Set key_data to the actual value of the public key." default: null required: false image: description: - "A dictionary describing the Marketplace image used to build the VM. Will contain keys: publisher, offer, sku and version. NOTE: set image.version to 'latest' to get the most recent version of a given image." required: true storage_account_name: description: - Name of an existing storage account that supports creation of VHD blobs. If not specified for a new VM, a new storage account named <vm name>01 will be created using storage type 'Standard_LRS'. default: null required: false storage_container_name: description: - Name of the container to use within the storage account to store VHD blobs. If no name is specified a default container will created. default: vhds required: false storage_blob_name: description: - Name fo the storage blob used to hold the VM's OS disk image. If no name is provided, defaults to the VM name + '.vhd'. If you provide a name, it must end with '.vhd' aliases: - storage_blob default: null required: false os_disk_caching: description: - Type of OS disk caching. choices: - ReadOnly - ReadWrite default: ReadOnly aliases: - disk_caching required: false os_type: description: - Base type of operating system. choices: - Windows - Linux default: - Linux required: false public_ip_allocation_method: description: - If a public IP address is created when creating the VM (because a Network Interface was not provided), determines if the public IP address remains permanently associated with the Network Interface. If set to 'Dynamic' the public IP address may change any time the VM is rebooted or power cycled. choices: - Dynamic - Static default: - Static aliases: - public_ip_allocation required: false open_ports: description: - If a network interface is created when creating the VM, a security group will be created as well. For Linux hosts a rule will be added to the security group allowing inbound TCP connections to the default SSH port 22, and for Windows hosts ports 3389 and 5986 will be opened. Override the default open ports by providing a list of ports. default: null required: false network_interface_names: description: - List of existing network interface names to add to the VM. If a network interface name is not provided when the VM is created, a default network interface will be created. In order for the module to create a network interface, at least one Virtual Network with one Subnet must exist. default: null required: false virtual_network_name: description: - When creating a virtual machine, if a network interface name is not provided, one will be created. The new network interface will be assigned to the first virtual network found in the resource group. Use this parameter to provide a specific virtual network instead. aliases: - virtual_network default: null required: false subnet_name: description: - When creating a virtual machine, if a network interface name is not provided, one will be created. The new network interface will be assigned to the first subnet found in the virtual network. Use this parameter to provide a specific subnet instead. aliases: - virtual_network default: null required: false remove_on_absent: description: - When removing a VM using state 'absent', also remove associated resources - "It can be 'all' or a list with any of the following: ['network_interfaces', 'virtual_storage', 'public_ips']" - Any other input will be ignored default: ['all'] required: false extends_documentation_fragment: - azure - azure_tags author: - "Chris Houseknecht (@chouseknecht)" - "Matt Davis (@nitzmahone)" ''' EXAMPLES = ''' - name: Create VM with defaults azure_rm_virtualmachine: resource_group: Testing name: testvm10 admin_username: chouseknecht admin_password: <your password here> image: offer: CentOS publisher: OpenLogic sku: '7.1' version: latest - name: Create a VM with exiting storage account and NIC azure_rm_virtualmachine: resource_group: Testing name: testvm002 vm_size: Standard_D4 storage_account: testaccount001 admin_username: adminUser ssh_public_keys: - path: /home/adminUser/.ssh/authorized_keys key_data: < insert yor ssh public key here... > network_interfaces: testvm001 image: offer: CentOS publisher: OpenLogic sku: '7.1' version: latest - name: Power Off azure_rm_virtualmachine: resource_group: Testing name: testvm002 started: no - name: Deallocate azure_rm_virtualmachine: resource_group: Testing name: testvm002 allocated: no - name: Power On azure_rm_virtualmachine: resource_group: name: testvm002 - name: Restart azure_rm_virtualmachine: resource_group: name: testvm002 restarted: yes - name: remove vm and all resources except public ips azure_rm_virtualmachine: resource_group: Testing name: testvm002 state: absent remove_on_absent: - network_interfaces - virtual_storage ''' RETURN = ''' powerstate: description: Indicates if the state is running, stopped, deallocated returned: always type: string example: running deleted_vhd_uris: description: List of deleted Virtual Hard Disk URIs. returned: 'on delete' type: list example: ["https://testvm104519.blob.core.windows.net/vhds/testvm10.vhd"] deleted_network_interfaces: description: List of deleted NICs. returned: 'on delete' type: list example: ["testvm1001"] deleted_public_ips: description: List of deleted public IP address names. returned: 'on delete' type: list example: ["testvm1001"] azure_vm: description: Facts about the current state of the object. Note that facts are not part of the registered output but available directly. returned: always type: complex example: { "properties": { "hardwareProfile": { "vmSize": "Standard_D1" }, "instanceView": { "disks": [ { "name": "testvm10.vhd", "statuses": [ { "code": "ProvisioningState/succeeded", "displayStatus": "Provisioning succeeded", "level": "Info", "time": "2016-03-30T07:11:16.187272Z" } ] } ], "statuses": [ { "code": "ProvisioningState/succeeded", "displayStatus": "Provisioning succeeded", "level": "Info", "time": "2016-03-30T20:33:38.946916Z" }, { "code": "PowerState/running", "displayStatus": "VM running", "level": "Info" } ], "vmAgent": { "extensionHandlers": [], "statuses": [ { "code": "ProvisioningState/succeeded", "displayStatus": "Ready", "level": "Info", "message": "GuestAgent is running and accepting new configurations.", "time": "2016-03-30T20:31:16.000Z" } ], "vmAgentVersion": "WALinuxAgent-2.0.16" } }, "networkProfile": { "networkInterfaces": [ { "id": "/subscriptions/XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX/resourceGroups/Testing/providers/Microsoft.Network/networkInterfaces/testvm10_NIC01", "name": "testvm10_NIC01", "properties": { "dnsSettings": { "appliedDnsServers": [], "dnsServers": [] }, "enableIPForwarding": false, "ipConfigurations": [ { "etag": 'W/"041c8c2a-d5dd-4cd7-8465-9125cfbe2cf8"', "id": "/subscriptions/XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX/resourceGroups/Testing/providers/Microsoft.Network/networkInterfaces/testvm10_NIC01/ipConfigurations/default", "name": "default", "properties": { "privateIPAddress": "10.10.0.5", "privateIPAllocationMethod": "Dynamic", "provisioningState": "Succeeded", "publicIPAddress": { "id": "/subscriptions/XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX/resourceGroups/Testing/providers/Microsoft.Network/publicIPAddresses/testvm10_PIP01", "name": "testvm10_PIP01", "properties": { "idleTimeoutInMinutes": 4, "ipAddress": "13.92.246.197", "ipConfiguration": { "id": "/subscriptions/XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX/resourceGroups/Testing/providers/Microsoft.Network/networkInterfaces/testvm10_NIC01/ipConfigurations/default" }, "provisioningState": "Succeeded", "publicIPAllocationMethod": "Static", "resourceGuid": "3447d987-ca0d-4eca-818b-5dddc0625b42" } } } } ], "macAddress": "00-0D-3A-12-AA-14", "primary": true, "provisioningState": "Succeeded", "resourceGuid": "10979e12-ccf9-42ee-9f6d-ff2cc63b3844", "virtualMachine": { "id": "/subscriptions/XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX/resourceGroups/Testing/providers/Microsoft.Compute/virtualMachines/testvm10" } } } ] }, "osProfile": { "adminUsername": "chouseknecht", "computerName": "test10", "linuxConfiguration": { "disablePasswordAuthentication": false }, "secrets": [] }, "provisioningState": "Succeeded", "storageProfile": { "dataDisks": [], "imageReference": { "offer": "CentOS", "publisher": "OpenLogic", "sku": "7.1", "version": "7.1.20160308" }, "osDisk": { "caching": "ReadOnly", "createOption": "fromImage", "name": "testvm10.vhd", "osType": "Linux", "vhd": { "uri": "https://testvm10sa1.blob.core.windows.net/vhds/testvm10.vhd" } } } }, "type": "Microsoft.Compute/virtualMachines" } ''' # NOQA import random from ansible.module_utils.basic import * from ansible.module_utils.azure_rm_common import * try: from msrestazure.azure_exceptions import CloudError from azure.mgmt.compute.models import NetworkInterfaceReference, \ VirtualMachine, HardwareProfile, \ StorageProfile, OSProfile, OSDisk, \ VirtualHardDisk, ImageReference,\ NetworkProfile, LinuxConfiguration, \ SshConfiguration, SshPublicKey from azure.mgmt.network.models import PublicIPAddress, NetworkSecurityGroup, NetworkInterface, \ NetworkInterfaceIPConfiguration, Subnet from azure.mgmt.storage.models import StorageAccountCreateParameters, Sku from azure.mgmt.storage.models.storage_management_client_enums import Kind, SkuTier, SkuName from azure.mgmt.compute.models.compute_management_client_enums import VirtualMachineSizeTypes, DiskCreateOptionTypes except ImportError: # This is handled in azure_rm_common pass AZURE_OBJECT_CLASS = 'VirtualMachine' AZURE_ENUM_MODULES = ['azure.mgmt.compute.models.compute_management_client_enums'] def extract_names_from_blob_uri(blob_uri): # HACK: ditch this once python SDK supports get by URI m = re.match('^https://(?P<accountname>[^\.]+)\.blob\.core\.windows\.net/' '(?P<containername>[^/]+)/(?P<blobname>.+)$', blob_uri) if not m: raise Exception("unable to parse blob uri '%s'" % blob_uri) extracted_names = m.groupdict() return extracted_names class AzureRMVirtualMachine(AzureRMModuleBase): def __init__(self): self.module_arg_spec = dict( resource_group=dict(type='str', required=True), name=dict(type='str', required=True), state=dict(choices=['present', 'absent'], default='present', type='str'), location=dict(type='str'), short_hostname=dict(type='str'), vm_size=dict(type='str', choices=[], default='Standard_D1'), admin_username=dict(type='str'), admin_password=dict(type='str', no_log=True), ssh_password_enabled=dict(type='bool', default=True), ssh_public_keys=dict(type='list'), image=dict(type='dict'), storage_account_name=dict(type='str', aliases=['storage_account']), storage_container_name=dict(type='str', aliases=['storage_container'], default='vhds'), storage_blob_name=dict(type='str', aliases=['storage_blob']), os_disk_caching=dict(type='str', aliases=['disk_caching'], choices=['ReadOnly', 'ReadWrite'], default='ReadOnly'), os_type=dict(type='str', choices=['Linux', 'Windows'], default='Linux'), public_ip_allocation_method=dict(type='str', choices=['Dynamic', 'Static'], default='Static', aliases=['public_ip_allocation']), open_ports=dict(type='list'), network_interface_names=dict(type='list', aliases=['network_interfaces']), remove_on_absent=dict(type='list', default=['all']), virtual_network_name=dict(type='str', aliases=['virtual_network']), subnet_name=dict(type='str', aliases=['subnet']), allocated=dict(type='bool', default=True), restarted=dict(type='bool', default=False), started=dict(type='bool', default=True), ) for key in VirtualMachineSizeTypes: self.module_arg_spec['vm_size']['choices'].append(getattr(key, 'value')) self.resource_group = None self.name = None self.state = None self.location = None self.short_hostname = None self.vm_size = None self.admin_username = None self.admin_password = None self.ssh_password_enabled = None self.ssh_public_keys = None self.image = None self.storage_account_name = None self.storage_container_name = None self.storage_blob_name = None self.os_type = None self.os_disk_caching = None self.network_interface_names = None self.remove_on_absent = set() self.tags = None self.force = None self.public_ip_allocation_method = None self.open_ports = None self.virtual_network_name = None self.subnet_name = None self.allocated = None self.restarted = None self.started = None self.differences = None self.results = dict( changed=False, actions=[], powerstate_change=None, ansible_facts=dict(azure_vm=None) ) super(AzureRMVirtualMachine, self).__init__(derived_arg_spec=self.module_arg_spec, supports_check_mode=True) def exec_module(self, **kwargs): for key in self.module_arg_spec.keys() + ['tags']: setattr(self, key, kwargs[key]) # make sure options are lower case self.remove_on_absent = set([resource.lower() for resource in self.remove_on_absent]) changed = False powerstate_change = None results = dict() vm = None network_interfaces = [] requested_vhd_uri = None disable_ssh_password = None vm_dict = None resource_group = self.get_resource_group(self.resource_group) if not self.location: # Set default location self.location = resource_group.location if self.state == 'present': # Verify parameters and resolve any defaults if self.vm_size and not self.vm_size_is_valid(): self.fail("Parameter error: vm_size {0} is not valid for your subscription and location.".format( self.vm_size )) if self.network_interface_names: for name in self.network_interface_names: nic = self.get_network_interface(name) network_interfaces.append(nic.id) if self.ssh_public_keys: msg = "Parameter error: expecting ssh_public_keys to be a list of type dict where " \ "each dict contains keys: path, key_data." for key in self.ssh_public_keys: if not isinstance(key, dict): self.fail(msg) if not key.get('path') or not key.get('key_data'): self.fail(msg) if self.image: if not self.image.get('publisher') or not self.image.get('offer') or not self.image.get('sku') \ or not self.image.get('version'): self.error("parameter error: expecting image to contain publisher, offer, sku and version keys.") image_version = self.get_image_version() if self.image['version'] == 'latest': self.image['version'] = image_version.name self.log("Using image version {0}".format(self.image['version'])) if not self.storage_blob_name: self.storage_blob_name = self.name + '.vhd' if self.storage_account_name: self.get_storage_account(self.storage_account_name) requested_vhd_uri = 'https://{0}.blob.core.windows.net/{1}/{2}'.format(self.storage_account_name, self.storage_container_name, self.storage_blob_name) disable_ssh_password = not self.ssh_password_enabled try: self.log("Fetching virtual machine {0}".format(self.name)) vm = self.compute_client.virtual_machines.get(self.resource_group, self.name, expand='instanceview') self.check_provisioning_state(vm, self.state) vm_dict = self.serialize_vm(vm) if self.state == 'present': differences = [] current_nics = [] results = vm_dict # Try to determine if the VM needs to be updated if self.network_interface_names: for nic in vm_dict['properties']['networkProfile']['networkInterfaces']: current_nics.append(nic['id']) if set(current_nics) != set(network_interfaces): self.log('CHANGED: virtual machine {0} - network interfaces are different.'.format(self.name)) differences.append('Network Interfaces') updated_nics = [dict(id=id) for id in network_interfaces] vm_dict['properties']['networkProfile']['networkInterfaces'] = updated_nics changed = True if self.os_disk_caching and \ self.os_disk_caching != vm_dict['properties']['storageProfile']['osDisk']['caching']: self.log('CHANGED: virtual machine {0} - OS disk caching'.format(self.name)) differences.append('OS Disk caching') changed = True vm_dict['properties']['storageProfile']['osDisk']['caching'] = self.os_disk_caching update_tags, vm_dict['tags'] = self.update_tags(vm_dict.get('tags', dict())) if update_tags: differences.append('Tags') changed = True if self.short_hostname and self.short_hostname != vm_dict['properties']['osProfile']['computerName']: self.log('CHANGED: virtual machine {0} - short hostname'.format(self.name)) differences.append('Short Hostname') changed = True vm_dict['properties']['osProfile']['computerName'] = self.short_hostname if self.started and vm_dict['powerstate'] != 'running': self.log("CHANGED: virtual machine {0} not running and requested state 'running'".format(self.name)) changed = True powerstate_change = 'poweron' elif self.state == 'present' and vm_dict['powerstate'] == 'running' and self.restarted: self.log("CHANGED: virtual machine {0} {1} and requested state 'restarted'" .format(self.name, vm_dict['powerstate'])) changed = True powerstate_change = 'restarted' elif self.state == 'present' and not self.allocated and vm_dict['powerstate'] != 'deallocated': self.log("CHANGED: virtual machine {0} {1} and requested state 'deallocated'" .format(self.name, vm_dict['powerstate'])) changed = True powerstate_change = 'deallocated' elif not self.started and vm_dict['powerstate'] == 'running': self.log("CHANGED: virtual machine {0} running and requested state 'stopped'".format(self.name)) changed = True powerstate_change = 'poweroff' self.differences = differences elif self.state == 'absent': self.log("CHANGED: virtual machine {0} exists and requested state is 'absent'".format(self.name)) results = dict() changed = True except CloudError: self.log('Virtual machine {0} does not exist'.format(self.name)) if self.state == 'present': self.log("CHANGED: virtual machine does not exist but state is present." \ .format(self.name)) changed = True self.results['changed'] = changed self.results['ansible_facts']['azure_vm'] = results self.results['powerstate_change'] = powerstate_change if self.check_mode: return self.results if changed: if self.state == 'present': if not vm: # Create the VM self.log("Create virtual machine {0}".format(self.name)) self.results['actions'].append('Created VM {0}'.format(self.name)) # Validate parameters if not self.admin_username: self.fail("Parameter error: admin_username required when creating a virtual machine.") if self.os_type == 'Linux': if disable_ssh_password and not self.ssh_public_keys: self.fail("Parameter error: ssh_public_keys required when disabling SSH password.") if not self.image: self.fail("Parameter error: an image is required when creating a virtual machine.") # Get defaults if not self.network_interface_names: default_nic = self.create_default_nic() self.log("network interface:") self.log(self.serialize_obj(default_nic, 'NetworkInterface'), pretty_print=True) network_interfaces = [default_nic.id] if not self.storage_account_name: storage_account = self.create_default_storage_account() self.log("storage account:") self.log(self.serialize_obj(storage_account, 'StorageAccount'), pretty_print=True) requested_vhd_uri = 'https://{0}.blob.core.windows.net/{1}/{2}'.format( storage_account.name, self.storage_container_name, self.storage_blob_name) if not self.short_hostname: self.short_hostname = self.name nics = [NetworkInterfaceReference(id=id) for id in network_interfaces] vhd = VirtualHardDisk(uri=requested_vhd_uri) vm_resource = VirtualMachine( self.location, tags=self.tags, os_profile=OSProfile( admin_username=self.admin_username, computer_name=self.short_hostname, ), hardware_profile=HardwareProfile( vm_size=self.vm_size ), storage_profile=StorageProfile( os_disk=OSDisk( self.storage_blob_name, vhd, DiskCreateOptionTypes.from_image, caching=self.os_disk_caching, ), image_reference=ImageReference( publisher=self.image['publisher'], offer=self.image['offer'], sku=self.image['sku'], version=self.image['version'], ), ), network_profile=NetworkProfile( network_interfaces=nics ), ) if self.admin_password: vm_resource.os_profile.admin_password = self.admin_password if self.os_type == 'Linux': vm_resource.os_profile.linux_configuration = LinuxConfiguration( disable_password_authentication=disable_ssh_password ) if self.ssh_public_keys: ssh_config = SshConfiguration() ssh_config.public_keys = \ [SshPublicKey(path=key['path'], key_data=key['key_data']) for key in self.ssh_public_keys] vm_resource.os_profile.linux_configuration.ssh = ssh_config self.log("Create virtual machine with parameters:") self.create_or_update_vm(vm_resource) elif self.differences and len(self.differences) > 0: # Update the VM based on detected config differences self.log("Update virtual machine {0}".format(self.name)) self.results['actions'].append('Updated VM {0}'.format(self.name)) nics = [NetworkInterfaceReference(id=interface['id']) for interface in vm_dict['properties']['networkProfile']['networkInterfaces']] vhd = VirtualHardDisk(uri=vm_dict['properties']['storageProfile']['osDisk']['vhd']['uri']) vm_resource = VirtualMachine( vm_dict['location'], vm_id=vm_dict['properties']['vmId'], os_profile=OSProfile( admin_username=vm_dict['properties']['osProfile']['adminUsername'], computer_name=vm_dict['properties']['osProfile']['computerName'] ), hardware_profile=HardwareProfile( vm_size=vm_dict['properties']['hardwareProfile']['vmSize'] ), storage_profile=StorageProfile( os_disk=OSDisk( vm_dict['properties']['storageProfile']['osDisk']['name'], vhd, vm_dict['properties']['storageProfile']['osDisk']['createOption'], os_type=vm_dict['properties']['storageProfile']['osDisk']['osType'], caching=vm_dict['properties']['storageProfile']['osDisk']['caching'] ), image_reference=ImageReference( publisher=vm_dict['properties']['storageProfile']['imageReference']['publisher'], offer=vm_dict['properties']['storageProfile']['imageReference']['offer'], sku=vm_dict['properties']['storageProfile']['imageReference']['sku'], version=vm_dict['properties']['storageProfile']['imageReference']['version'] ), ), network_profile=NetworkProfile( network_interfaces=nics ), ) if vm_dict.get('tags'): vm_resource.tags = vm_dict['tags'] # Add admin password, if one provided if vm_dict['properties']['osProfile'].get('adminPassword'): vm_resource.os_profile.admin_password = vm_dict['properties']['osProfile']['adminPassword'] # Add linux configuration, if applicable linux_config = vm_dict['properties']['osProfile'].get('linuxConfiguration') if linux_config: ssh_config = linux_config.get('ssh', None) vm_resource.os_profile.linux_configuration = LinuxConfiguration( disable_password_authentication=linux_config.get('disablePasswordAuthentication', False) ) if ssh_config: public_keys = ssh_config.get('publicKeys') if public_keys: vm_resource.os_profile.linux_configuration.ssh = SshConfiguration(public_keys=[]) for key in public_keys: vm_resource.os_profile.linux_configuration.ssh.public_keys.append( SshPublicKey(path=key['path'], key_data=key['keyData']) ) self.log("Update virtual machine with parameters:") self.create_or_update_vm(vm_resource) # Make sure we leave the machine in requested power state if (powerstate_change == 'poweron' and self.results['ansible_facts']['azure_vm']['powerstate'] != 'running'): # Attempt to power on the machine self.power_on_vm() elif (powerstate_change == 'poweroff' and self.results['ansible_facts']['azure_vm']['powerstate'] == 'running'): # Attempt to power off the machine self.power_off_vm() elif powerstate_change == 'restarted': self.restart_vm() elif powerstate_change == 'deallocated': self.deallocate_vm() self.results['ansible_facts']['azure_vm'] = self.serialize_vm(self.get_vm()) elif self.state == 'absent': # delete the VM self.log("Delete virtual machine {0}".format(self.name)) self.results['ansible_facts']['azure_vm'] = None self.delete_vm(vm) # until we sort out how we want to do this globally del self.results['actions'] return self.results def get_vm(self): ''' Get the VM with expanded instanceView :return: VirtualMachine object ''' try: vm = self.compute_client.virtual_machines.get(self.resource_group, self.name, expand='instanceview') return vm except Exception as exc: self.fail("Error getting virtual machine (0) - {1}".format(self.name, str(exc))) def serialize_vm(self, vm): ''' Convert a VirtualMachine object to dict. :param vm: VirtualMachine object :return: dict ''' result = self.serialize_obj(vm, AZURE_OBJECT_CLASS, enum_modules=AZURE_ENUM_MODULES) result['id'] = vm.id result['name'] = vm.name result['type'] = vm.type result['location'] = vm.location result['tags'] = vm.tags result['powerstate'] = dict() if vm.instance_view: result['powerstate'] = next((s.code.replace('PowerState/', '') for s in vm.instance_view.statuses if s.code.startswith('PowerState')), None) # Expand network interfaces to include config properties for interface in vm.network_profile.network_interfaces: int_dict = azure_id_to_dict(interface.id) nic = self.get_network_interface(int_dict['networkInterfaces']) for interface_dict in result['properties']['networkProfile']['networkInterfaces']: if interface_dict['id'] == interface.id: nic_dict = self.serialize_obj(nic, 'NetworkInterface') interface_dict['name'] = int_dict['networkInterfaces'] interface_dict['properties'] = nic_dict['properties'] # Expand public IPs to include config properties for interface in result['properties']['networkProfile']['networkInterfaces']: for config in interface['properties']['ipConfigurations']: if config['properties'].get('publicIPAddress'): pipid_dict = azure_id_to_dict(config['properties']['publicIPAddress']['id']) try: pip = self.network_client.public_ip_addresses.get(self.resource_group, pipid_dict['publicIPAddresses']) except Exception as exc: self.fail("Error fetching public ip {0} - {1}".format(pipid_dict['publicIPAddresses'], str(exc))) pip_dict = self.serialize_obj(pip, 'PublicIPAddress') config['properties']['publicIPAddress']['name'] = pipid_dict['publicIPAddresses'] config['properties']['publicIPAddress']['properties'] = pip_dict['properties'] self.log(result, pretty_print=True) if self.state != 'absent' and not result['powerstate']: self.fail("Failed to determine PowerState of virtual machine {0}".format(self.name)) return result def power_off_vm(self): self.log("Powered off virtual machine {0}".format(self.name)) self.results['actions'].append("Powered off virtual machine {0}".format(self.name)) try: poller = self.compute_client.virtual_machines.power_off(self.resource_group, self.name) self.get_poller_result(poller) except Exception as exc: self.fail("Error powering off virtual machine {0} - {1}".format(self.name, str(exc))) return True def power_on_vm(self): self.results['actions'].append("Powered on virtual machine {0}".format(self.name)) self.log("Power on virtual machine {0}".format(self.name)) try: poller = self.compute_client.virtual_machines.start(self.resource_group, self.name) self.get_poller_result(poller) except Exception as exc: self.fail("Error powering on virtual machine {0} - {1}".format(self.name, str(exc))) return True def restart_vm(self): self.results['actions'].append("Restarted virtual machine {0}".format(self.name)) self.log("Restart virtual machine {0}".format(self.name)) try: poller = self.compute_client.virtual_machines.restart(self.resource_group, self.name) self.get_poller_result(poller) except Exception as exc: self.fail("Error restarting virtual machine {0} - {1}".format(self.name, str(exc))) return True def deallocate_vm(self): self.results['actions'].append("Deallocated virtual machine {0}".format(self.name)) self.log("Deallocate virtual machine {0}".format(self.name)) try: poller = self.compute_client.virtual_machines.deallocate(self.resource_group, self.name) self.get_poller_result(poller) except Exception as exc: self.fail("Error deallocating virtual machine {0} - {1}".format(self.name, str(exc))) return True def delete_vm(self, vm): vhd_uris = [] nic_names = [] pip_names = [] if self.remove_on_absent.intersection(set(['all','virtual_storage'])): # store the attached vhd info so we can nuke it after the VM is gone self.log('Storing VHD URI for deletion') vhd_uris.append(vm.storage_profile.os_disk.vhd.uri) self.log("VHD URIs to delete: {0}".format(', '.join(vhd_uris))) self.results['deleted_vhd_uris'] = vhd_uris if self.remove_on_absent.intersection(set(['all','network_interfaces'])): # store the attached nic info so we can nuke them after the VM is gone self.log('Storing NIC names for deletion.') for interface in vm.network_profile.network_interfaces: id_dict = azure_id_to_dict(interface.id) nic_names.append(id_dict['networkInterfaces']) self.log('NIC names to delete {0}'.format(', '.join(nic_names))) self.results['deleted_network_interfaces'] = nic_names if self.remove_on_absent.intersection(set(['all','public_ips'])): # also store each nic's attached public IPs and delete after the NIC is gone for name in nic_names: nic = self.get_network_interface(name) for ipc in nic.ip_configurations: if ipc.public_ip_address: pip_dict = azure_id_to_dict(ipc.public_ip_address.id) pip_names.append(pip_dict['publicIPAddresses']) self.log('Public IPs to delete are {0}'.format(', '.join(pip_names))) self.results['deleted_public_ips'] = pip_names self.log("Deleting virtual machine {0}".format(self.name)) self.results['actions'].append("Deleted virtual machine {0}".format(self.name)) try: poller = self.compute_client.virtual_machines.delete(self.resource_group, self.name) # wait for the poller to finish self.get_poller_result(poller) except Exception as exc: self.fail("Error deleting virtual machine {0} - {1}".format(self.name, str(exc))) # TODO: parallelize nic, vhd, and public ip deletions with begin_deleting # TODO: best-effort to keep deleting other linked resources if we encounter an error if self.remove_on_absent.intersection(set(['all','virtual_storage'])): self.log('Deleting virtual storage') self.delete_vm_storage(vhd_uris) if self.remove_on_absent.intersection(set(['all','network_interfaces'])): self.log('Deleting network interfaces') for name in nic_names: self.delete_nic(name) if self.remove_on_absent.intersection(set(['all','public_ips'])): self.log('Deleting public IPs') for name in pip_names: self.delete_pip(name) return True def get_network_interface(self, name): try: nic = self.network_client.network_interfaces.get(self.resource_group, name) return nic except Exception as exc: self.fail("Error fetching network interface {0} - {1}".format(name, str(exc))) def delete_nic(self, name): self.log("Deleting network interface {0}".format(name)) self.results['actions'].append("Deleted network interface {0}".format(name)) try: poller = self.network_client.network_interfaces.delete(self.resource_group, name) except Exception as exc: self.fail("Error deleting network interface {0} - {1}".format(name, str(exc))) self.get_poller_result(poller) # Delete doesn't return anything. If we get this far, assume success return True def delete_pip(self, name): self.results['actions'].append("Deleted public IP {0}".format(name)) try: poller = self.network_client.public_ip_addresses.delete(self.resource_group, name) self.get_poller_result(poller) except Exception as exc: self.fail("Error deleting {0} - {1}".format(name, str(exc))) # Delete returns nada. If we get here, assume that all is well. return True def delete_vm_storage(self, vhd_uris): for uri in vhd_uris: self.log("Extracting info from blob uri '{0}'".format(uri)) try: blob_parts = extract_names_from_blob_uri(uri) except Exception as exc: self.fail("Error parsing blob URI {0}".format(str(exc))) storage_account_name = blob_parts['accountname'] container_name = blob_parts['containername'] blob_name = blob_parts['blobname'] blob_client = self.get_blob_client(self.resource_group, storage_account_name) self.log("Delete blob {0}:{1}".format(container_name, blob_name)) self.results['actions'].append("Deleted blob {0}:{1}".format(container_name, blob_name)) try: blob_client.delete_blob(container_name, blob_name) except Exception as exc: self.fail("Error deleting blob {0}:{1} - {2}".format(container_name, blob_name, str(exc))) def get_image_version(self): try: versions = self.compute_client.virtual_machine_images.list(self.location, self.image['publisher'], self.image['offer'], self.image['sku']) except Exception as exc: self.fail("Error fetching image {0} {1} {2} - {4}".format(self.image['publisher'], self.image['offer'], self.image['sku'], str(exc))) if versions and len(versions) > 0: if self.image['version'] == 'latest': return versions[len(versions) - 1] for version in versions: if version.name == self.image['version']: return version self.fail("Error could not find image {0} {1} {2} {3}".format(self.image['publisher'], self.image['offer'], self.image['sku'], self.image['version'])) def get_storage_account(self, name): try: account = self.storage_client.storage_accounts.get_properties(self.resource_group, name) return account except Exception as exc: self.fail("Error fetching storage account {0} - {1}".format(self.storage_account_name, str(exc))) def create_or_update_vm(self, params): try: poller = self.compute_client.virtual_machines.create_or_update(self.resource_group, self.name, params) self.get_poller_result(poller) except Exception as exc: self.fail("Error creating or updating virtual machine {0} - {1}".format(self.name, str(exc))) def vm_size_is_valid(self): ''' Validate self.vm_size against the list of virtual machine sizes available for the account and location. :return: boolean ''' try: sizes = self.compute_client.virtual_machine_sizes.list(self.location) except Exception as exc: self.fail("Error retrieving available machine sizes - {0}".format(str(exc))) for size in sizes: if size.name == self.vm_size: return True return False def create_default_storage_account(self): ''' Create a default storage account <vm name>XXXX, where XXXX is a random number. If <vm name>XXXX exists, use it. Otherwise, create one. :return: storage account object ''' account = None valid_name = False # Attempt to find a valid storage account name storage_account_name_base = self.name[:20].lower() for i in range(0, 5): rand = random.randrange(1000, 9999) storage_account_name = storage_account_name_base + str(rand) if self.check_storage_account_name(storage_account_name): valid_name = True break if not valid_name: self.fail("Failed to create a unique storage account name for {0}. Try using a different VM name." .format(self.name)) try: account = self.storage_client.storage_accounts.get_properties(self.resource_group, storage_account_name) except CloudError: pass if account: self.log("Storage account {0} found.".format(storage_account_name)) self.check_provisioning_state(account) return account sku = Sku(SkuName.standard_lrs) Sku.tier = SkuTier.standard kind = Kind.storage parameters = StorageAccountCreateParameters(sku, kind, self.location) self.log("Creating storage account {0} in location {1}".format(storage_account_name, self.location)) self.results['actions'].append("Created storage account {0}".format(storage_account_name)) try: poller = self.storage_client.storage_accounts.create(self.resource_group, storage_account_name, parameters) self.get_poller_result(poller) except Exception as exc: self.fail("Failed to create storage account: {0} - {1}".format(storage_account_name, str(exc))) return self.get_storage_account(storage_account_name) def check_storage_account_name(self, name): self.log("Checking storage account name availability for {0}".format(name)) try: response = self.storage_client.storage_accounts.check_name_availability(name) except Exception as exc: self.fail("Error checking storage account name availability for {0} - {1}".format(name, str(exc))) return response.name_available def create_default_nic(self): ''' Create a default Network Interface <vm name>01. Requires an existing virtual network with one subnet. If NIC <vm name>01 exists, use it. Otherwise, create one. :return: NIC object ''' network_interface_name = self.name + '01' nic = None self.log("Create default NIC {0}".format(network_interface_name)) self.log("Check to see if NIC {0} exists".format(network_interface_name)) try: nic = self.network_client.network_interfaces.get(self.resource_group, network_interface_name) except CloudError: pass if nic: self.log("NIC {0} found.".format(network_interface_name)) self.check_provisioning_state(nic) return nic self.log("NIC {0} does not exist.".format(network_interface_name)) if self.virtual_network_name: try: self.network_client.virtual_networks.list(self.resource_group, self.virtual_network_name) virtual_network_name = self.virtual_network_name except Exception as exc: self.fail("Error: fetching virtual network {0} - {1}".format(self.virtual_network_name, str(exc))) else: # Find a virtual network no_vnets_msg = "Error: unable to find virtual network in resource group {0}. A virtual network " \ "with at least one subnet must exist in order to create a NIC for the virtual " \ "machine.".format(self.resource_group) virtual_network_name = None try: vnets = self.network_client.virtual_networks.list(self.resource_group) except CloudError: self.log('cloud error!') self.fail(no_vnets_msg) for vnet in vnets: virtual_network_name = vnet.name self.log('vnet name: {0}'.format(vnet.name)) break if not virtual_network_name: self.fail(no_vnets_msg) if self.subnet_name: try: subnet = self.network_client.subnets.get(self.resource_group, virtual_network_name) subnet_id = subnet.id except Exception as exc: self.fail("Error: fetching subnet {0} - {1}".format(self.subnet_name, str(exc))) else: no_subnets_msg = "Error: unable to find a subnet in virtual network {0}. A virtual network " \ "with at least one subnet must exist in order to create a NIC for the virtual " \ "machine.".format(virtual_network_name) subnet_id = None try: subnets = self.network_client.subnets.list(self.resource_group, virtual_network_name) except CloudError: self.fail(no_subnets_msg) for subnet in subnets: subnet_id = subnet.id self.log('subnet id: {0}'.format(subnet_id)) break if not subnet_id: self.fail(no_subnets_msg) self.results['actions'].append('Created default public IP {0}'.format(self.name + '01')) pip = self.create_default_pip(self.resource_group, self.location, self.name, self.public_ip_allocation_method) self.results['actions'].append('Created default security group {0}'.format(self.name + '01')) group = self.create_default_securitygroup(self.resource_group, self.location, self.name, self.os_type, self.open_ports) parameters = NetworkInterface( location=self.location, ip_configurations=[ NetworkInterfaceIPConfiguration( private_ip_allocation_method='Dynamic', ) ] ) parameters.ip_configurations[0].subnet = Subnet(id=subnet_id) parameters.ip_configurations[0].name = 'default' parameters.network_security_group = NetworkSecurityGroup(id=group.id, location=group.location, resource_guid=group.resource_guid) parameters.ip_configurations[0].public_ip_address = PublicIPAddress(id=pip.id, location=pip.location, resource_guid=pip.resource_guid) self.log("Creating NIC {0}".format(network_interface_name)) self.log(self.serialize_obj(parameters, 'NetworkInterface'), pretty_print=True) self.results['actions'].append("Created NIC {0}".format(network_interface_name)) try: poller = self.network_client.network_interfaces.create_or_update(self.resource_group, network_interface_name, parameters) new_nic = self.get_poller_result(poller) except Exception as exc: self.fail("Error creating network interface {0} - {1}".format(network_interface_name, str(exc))) return new_nic def main(): AzureRMVirtualMachine() if __name__ == '__main__': main()
bjolivot/ansible
lib/ansible/modules/cloud/azure/azure_rm_virtualmachine.py
Python
gpl-3.0
60,368
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import cmd import functools import os import pprint import sys import threading import time from collections import deque from multiprocessing import Lock from jinja2.exceptions import UndefinedError from ansible import constants as C from ansible.errors import AnsibleError, AnsibleParserError, AnsibleUndefinedVariable from ansible.executor import action_write_locks from ansible.executor.process.worker import WorkerProcess from ansible.executor.task_result import TaskResult from ansible.inventory.host import Host from ansible.module_utils.six.moves import queue as Queue from ansible.module_utils.six import iteritems, itervalues, string_types from ansible.module_utils._text import to_text from ansible.module_utils.connection import Connection, ConnectionError from ansible.playbook.helpers import load_list_of_blocks from ansible.playbook.included_file import IncludedFile from ansible.playbook.task_include import TaskInclude from ansible.playbook.role_include import IncludeRole from ansible.plugins.loader import action_loader, connection_loader, filter_loader, lookup_loader, module_loader, test_loader from ansible.template import Templar from ansible.utils.vars import combine_vars from ansible.vars.clean import strip_internal_keys try: from __main__ import display except ImportError: from ansible.utils.display import Display display = Display() __all__ = ['StrategyBase'] class StrategySentinel: pass # TODO: this should probably be in the plugins/__init__.py, with # a smarter mechanism to set all of the attributes based on # the loaders created there class SharedPluginLoaderObj: ''' A simple object to make pass the various plugin loaders to the forked processes over the queue easier ''' def __init__(self): self.action_loader = action_loader self.connection_loader = connection_loader self.filter_loader = filter_loader self.test_loader = test_loader self.lookup_loader = lookup_loader self.module_loader = module_loader _sentinel = StrategySentinel() def results_thread_main(strategy): while True: try: result = strategy._final_q.get() if isinstance(result, StrategySentinel): break else: strategy._results_lock.acquire() strategy._results.append(result) strategy._results_lock.release() except (IOError, EOFError): break except Queue.Empty: pass def debug_closure(func): """Closure to wrap ``StrategyBase._process_pending_results`` and invoke the task debugger""" @functools.wraps(func) def inner(self, iterator, one_pass=False, max_passes=None): status_to_stats_map = ( ('is_failed', 'failures'), ('is_unreachable', 'dark'), ('is_changed', 'changed'), ('is_skipped', 'skipped'), ) # We don't know the host yet, copy the previous states, for lookup after we process new results prev_host_states = iterator._host_states.copy() results = func(self, iterator, one_pass=one_pass, max_passes=max_passes) _processed_results = [] for result in results: task = result._task host = result._host _queued_task_args = self._queued_task_cache.pop((host.name, task._uuid), None) task_vars = _queued_task_args['task_vars'] play_context = _queued_task_args['play_context'] # Try to grab the previous host state, if it doesn't exist use get_host_state to generate an empty state try: prev_host_state = prev_host_states[host.name] except KeyError: prev_host_state = iterator.get_host_state(host) while result.needs_debugger(globally_enabled=self.debugger_active): next_action = NextAction() dbg = Debugger(task, host, task_vars, play_context, result, next_action) dbg.cmdloop() if next_action.result == NextAction.REDO: # rollback host state self._tqm.clear_failed_hosts() iterator._host_states[host.name] = prev_host_state for method, what in status_to_stats_map: if getattr(result, method)(): self._tqm._stats.decrement(what, host.name) self._tqm._stats.decrement('ok', host.name) # redo self._queue_task(host, task, task_vars, play_context) _processed_results.extend(debug_closure(func)(self, iterator, one_pass)) break elif next_action.result == NextAction.CONTINUE: _processed_results.append(result) break elif next_action.result == NextAction.EXIT: # Matches KeyboardInterrupt from bin/ansible sys.exit(99) else: _processed_results.append(result) return _processed_results return inner class StrategyBase: ''' This is the base class for strategy plugins, which contains some common code useful to all strategies like running handlers, cleanup actions, etc. ''' def __init__(self, tqm): self._tqm = tqm self._inventory = tqm.get_inventory() self._workers = tqm.get_workers() self._notified_handlers = tqm._notified_handlers self._listening_handlers = tqm._listening_handlers self._variable_manager = tqm.get_variable_manager() self._loader = tqm.get_loader() self._final_q = tqm._final_q self._step = getattr(tqm._options, 'step', False) self._diff = getattr(tqm._options, 'diff', False) self.flush_cache = getattr(tqm._options, 'flush_cache', False) # the task cache is a dictionary of tuples of (host.name, task._uuid) # used to find the original task object of in-flight tasks and to store # the task args/vars and play context info used to queue the task. self._queued_task_cache = {} # Backwards compat: self._display isn't really needed, just import the global display and use that. self._display = display # internal counters self._pending_results = 0 self._cur_worker = 0 # this dictionary is used to keep track of hosts that have # outstanding tasks still in queue self._blocked_hosts = dict() self._results = deque() self._results_lock = threading.Condition(threading.Lock()) # create the result processing thread for reading results in the background self._results_thread = threading.Thread(target=results_thread_main, args=(self,)) self._results_thread.daemon = True self._results_thread.start() # holds the list of active (persistent) connections to be shutdown at # play completion self._active_connections = dict() self.debugger_active = C.ENABLE_TASK_DEBUGGER def cleanup(self): # close active persistent connections for sock in itervalues(self._active_connections): try: conn = Connection(sock) conn.reset() except ConnectionError as e: # most likely socket is already closed display.debug("got an error while closing persistent connection: %s" % e) self._final_q.put(_sentinel) self._results_thread.join() def run(self, iterator, play_context, result=0): # execute one more pass through the iterator without peeking, to # make sure that all of the hosts are advanced to their final task. # This should be safe, as everything should be ITERATING_COMPLETE by # this point, though the strategy may not advance the hosts itself. [iterator.get_next_task_for_host(host) for host in self._inventory.get_hosts(iterator._play.hosts) if host.name not in self._tqm._unreachable_hosts] # save the failed/unreachable hosts, as the run_handlers() # method will clear that information during its execution failed_hosts = iterator.get_failed_hosts() unreachable_hosts = self._tqm._unreachable_hosts.keys() display.debug("running handlers") handler_result = self.run_handlers(iterator, play_context) if isinstance(handler_result, bool) and not handler_result: result |= self._tqm.RUN_ERROR elif not handler_result: result |= handler_result # now update with the hosts (if any) that failed or were # unreachable during the handler execution phase failed_hosts = set(failed_hosts).union(iterator.get_failed_hosts()) unreachable_hosts = set(unreachable_hosts).union(self._tqm._unreachable_hosts.keys()) # return the appropriate code, depending on the status hosts after the run if not isinstance(result, bool) and result != self._tqm.RUN_OK: return result elif len(unreachable_hosts) > 0: return self._tqm.RUN_UNREACHABLE_HOSTS elif len(failed_hosts) > 0: return self._tqm.RUN_FAILED_HOSTS else: return self._tqm.RUN_OK def get_hosts_remaining(self, play): return [host for host in self._inventory.get_hosts(play.hosts) if host.name not in self._tqm._failed_hosts and host.name not in self._tqm._unreachable_hosts] def get_failed_hosts(self, play): return [host for host in self._inventory.get_hosts(play.hosts) if host.name in self._tqm._failed_hosts] def add_tqm_variables(self, vars, play): ''' Base class method to add extra variables/information to the list of task vars sent through the executor engine regarding the task queue manager state. ''' vars['ansible_current_hosts'] = [h.name for h in self.get_hosts_remaining(play)] vars['ansible_failed_hosts'] = [h.name for h in self.get_failed_hosts(play)] def _queue_task(self, host, task, task_vars, play_context): ''' handles queueing the task up to be sent to a worker ''' display.debug("entering _queue_task() for %s/%s" % (host.name, task.action)) # Add a write lock for tasks. # Maybe this should be added somewhere further up the call stack but # this is the earliest in the code where we have task (1) extracted # into its own variable and (2) there's only a single code path # leading to the module being run. This is called by three # functions: __init__.py::_do_handler_run(), linear.py::run(), and # free.py::run() so we'd have to add to all three to do it there. # The next common higher level is __init__.py::run() and that has # tasks inside of play_iterator so we'd have to extract them to do it # there. if task.action not in action_write_locks.action_write_locks: display.debug('Creating lock for %s' % task.action) action_write_locks.action_write_locks[task.action] = Lock() # and then queue the new task try: # create a dummy object with plugin loaders set as an easier # way to share them with the forked processes shared_loader_obj = SharedPluginLoaderObj() queued = False starting_worker = self._cur_worker while True: (worker_prc, rslt_q) = self._workers[self._cur_worker] if worker_prc is None or not worker_prc.is_alive(): self._queued_task_cache[(host.name, task._uuid)] = { 'host': host, 'task': task, 'task_vars': task_vars, 'play_context': play_context } worker_prc = WorkerProcess(self._final_q, task_vars, host, task, play_context, self._loader, self._variable_manager, shared_loader_obj) self._workers[self._cur_worker][0] = worker_prc worker_prc.start() display.debug("worker is %d (out of %d available)" % (self._cur_worker + 1, len(self._workers))) queued = True self._cur_worker += 1 if self._cur_worker >= len(self._workers): self._cur_worker = 0 if queued: break elif self._cur_worker == starting_worker: time.sleep(0.0001) self._pending_results += 1 except (EOFError, IOError, AssertionError) as e: # most likely an abort display.debug("got an error while queuing: %s" % e) return display.debug("exiting _queue_task() for %s/%s" % (host.name, task.action)) def get_task_hosts(self, iterator, task_host, task): if task.run_once: host_list = [host for host in self._inventory.get_hosts(iterator._play.hosts) if host.name not in self._tqm._unreachable_hosts] else: host_list = [task_host] return host_list def get_delegated_hosts(self, result, task): host_name = result.get('_ansible_delegated_vars', {}).get('ansible_delegated_host', None) if host_name is not None: actual_host = self._inventory.get_host(host_name) if actual_host is None: actual_host = Host(name=host_name) else: actual_host = Host(name=task.delegate_to) return [actual_host] @debug_closure def _process_pending_results(self, iterator, one_pass=False, max_passes=None): ''' Reads results off the final queue and takes appropriate action based on the result (executing callbacks, updating state, etc.). ''' ret_results = [] def get_original_host(host_name): # FIXME: this should not need x2 _inventory host_name = to_text(host_name) if host_name in self._inventory.hosts: return self._inventory.hosts[host_name] else: return self._inventory.get_host(host_name) def search_handler_blocks_by_name(handler_name, handler_blocks): for handler_block in handler_blocks: for handler_task in handler_block.block: if handler_task.name: handler_vars = self._variable_manager.get_vars(play=iterator._play, task=handler_task) templar = Templar(loader=self._loader, variables=handler_vars) try: # first we check with the full result of get_name(), which may # include the role name (if the handler is from a role). If that # is not found, we resort to the simple name field, which doesn't # have anything extra added to it. target_handler_name = templar.template(handler_task.name) if target_handler_name == handler_name: return handler_task else: target_handler_name = templar.template(handler_task.get_name()) if target_handler_name == handler_name: return handler_task except (UndefinedError, AnsibleUndefinedVariable): # We skip this handler due to the fact that it may be using # a variable in the name that was conditionally included via # set_fact or some other method, and we don't want to error # out unnecessarily continue return None def search_handler_blocks_by_uuid(handler_uuid, handler_blocks): for handler_block in handler_blocks: for handler_task in handler_block.block: if handler_uuid == handler_task._uuid: return handler_task return None def parent_handler_match(target_handler, handler_name): if target_handler: if isinstance(target_handler, (TaskInclude, IncludeRole)): try: handler_vars = self._variable_manager.get_vars(play=iterator._play, task=target_handler) templar = Templar(loader=self._loader, variables=handler_vars) target_handler_name = templar.template(target_handler.name) if target_handler_name == handler_name: return True else: target_handler_name = templar.template(target_handler.get_name()) if target_handler_name == handler_name: return True except (UndefinedError, AnsibleUndefinedVariable): pass return parent_handler_match(target_handler._parent, handler_name) else: return False cur_pass = 0 while True: try: self._results_lock.acquire() task_result = self._results.popleft() except IndexError: break finally: self._results_lock.release() # get the original host and task. We then assign them to the TaskResult for use in callbacks/etc. original_host = get_original_host(task_result._host) queue_cache_entry = (original_host.name, task_result._task) found_task = self._queued_task_cache.get(queue_cache_entry)['task'] original_task = found_task.copy(exclude_parent=True, exclude_tasks=True) original_task._parent = found_task._parent original_task.from_attrs(task_result._task_fields) task_result._host = original_host task_result._task = original_task # get the correct loop var for use later if original_task.loop_control: loop_var = original_task.loop_control.loop_var else: loop_var = 'item' # send callbacks for 'non final' results if '_ansible_retry' in task_result._result: self._tqm.send_callback('v2_runner_retry', task_result) continue elif '_ansible_item_result' in task_result._result: if task_result.is_failed() or task_result.is_unreachable(): self._tqm.send_callback('v2_runner_item_on_failed', task_result) elif task_result.is_skipped(): self._tqm.send_callback('v2_runner_item_on_skipped', task_result) else: if 'diff' in task_result._result: if self._diff: self._tqm.send_callback('v2_on_file_diff', task_result) self._tqm.send_callback('v2_runner_item_on_ok', task_result) continue if original_task.register: host_list = self.get_task_hosts(iterator, original_host, original_task) clean_copy = strip_internal_keys(task_result._result) if 'invocation' in clean_copy: del clean_copy['invocation'] for target_host in host_list: self._variable_manager.set_nonpersistent_facts(target_host, {original_task.register: clean_copy}) # all host status messages contain 2 entries: (msg, task_result) role_ran = False if task_result.is_failed(): role_ran = True ignore_errors = original_task.ignore_errors if not ignore_errors: display.debug("marking %s as failed" % original_host.name) if original_task.run_once: # if we're using run_once, we have to fail every host here for h in self._inventory.get_hosts(iterator._play.hosts): if h.name not in self._tqm._unreachable_hosts: state, _ = iterator.get_next_task_for_host(h, peek=True) iterator.mark_host_failed(h) state, new_task = iterator.get_next_task_for_host(h, peek=True) else: iterator.mark_host_failed(original_host) # increment the failed count for this host self._tqm._stats.increment('failures', original_host.name) # grab the current state and if we're iterating on the rescue portion # of a block then we save the failed task in a special var for use # within the rescue/always state, _ = iterator.get_next_task_for_host(original_host, peek=True) if iterator.is_failed(original_host) and state and state.run_state == iterator.ITERATING_COMPLETE: self._tqm._failed_hosts[original_host.name] = True if state and state.run_state == iterator.ITERATING_RESCUE: self._variable_manager.set_nonpersistent_facts( original_host, dict( ansible_failed_task=original_task.serialize(), ansible_failed_result=task_result._result, ), ) else: self._tqm._stats.increment('ok', original_host.name) if 'changed' in task_result._result and task_result._result['changed']: self._tqm._stats.increment('changed', original_host.name) self._tqm.send_callback('v2_runner_on_failed', task_result, ignore_errors=ignore_errors) elif task_result.is_unreachable(): self._tqm._unreachable_hosts[original_host.name] = True iterator._play._removed_hosts.append(original_host.name) self._tqm._stats.increment('dark', original_host.name) self._tqm.send_callback('v2_runner_on_unreachable', task_result) elif task_result.is_skipped(): self._tqm._stats.increment('skipped', original_host.name) self._tqm.send_callback('v2_runner_on_skipped', task_result) else: role_ran = True if original_task.loop: # this task had a loop, and has more than one result, so # loop over all of them instead of a single result result_items = task_result._result.get('results', []) else: result_items = [task_result._result] for result_item in result_items: if '_ansible_notify' in result_item: if task_result.is_changed(): # The shared dictionary for notified handlers is a proxy, which # does not detect when sub-objects within the proxy are modified. # So, per the docs, we reassign the list so the proxy picks up and # notifies all other threads for handler_name in result_item['_ansible_notify']: found = False # Find the handler using the above helper. First we look up the # dependency chain of the current task (if it's from a role), otherwise # we just look through the list of handlers in the current play/all # roles and use the first one that matches the notify name target_handler = search_handler_blocks_by_name(handler_name, iterator._play.handlers) if target_handler is not None: found = True if target_handler._uuid not in self._notified_handlers: self._notified_handlers[target_handler._uuid] = [] if original_host not in self._notified_handlers[target_handler._uuid]: self._notified_handlers[target_handler._uuid].append(original_host) self._tqm.send_callback('v2_playbook_on_notify', target_handler, original_host) else: # As there may be more than one handler with the notified name as the # parent, so we just keep track of whether or not we found one at all for target_handler_uuid in self._notified_handlers: target_handler = search_handler_blocks_by_uuid(target_handler_uuid, iterator._play.handlers) if target_handler and parent_handler_match(target_handler, handler_name): found = True if original_host not in self._notified_handlers[target_handler._uuid]: self._notified_handlers[target_handler._uuid].append(original_host) self._tqm.send_callback('v2_playbook_on_notify', target_handler, original_host) if handler_name in self._listening_handlers: for listening_handler_uuid in self._listening_handlers[handler_name]: listening_handler = search_handler_blocks_by_uuid(listening_handler_uuid, iterator._play.handlers) if listening_handler is not None: found = True else: continue if original_host not in self._notified_handlers[listening_handler._uuid]: self._notified_handlers[listening_handler._uuid].append(original_host) self._tqm.send_callback('v2_playbook_on_notify', listening_handler, original_host) # and if none were found, then we raise an error if not found: msg = ("The requested handler '%s' was not found in either the main handlers list nor in the listening " "handlers list" % handler_name) if C.ERROR_ON_MISSING_HANDLER: raise AnsibleError(msg) else: display.warning(msg) if 'add_host' in result_item: # this task added a new host (add_host module) new_host_info = result_item.get('add_host', dict()) self._add_host(new_host_info, iterator) elif 'add_group' in result_item: # this task added a new group (group_by module) self._add_group(original_host, result_item) if 'ansible_facts' in result_item: # if delegated fact and we are delegating facts, we need to change target host for them if original_task.delegate_to is not None and original_task.delegate_facts: host_list = self.get_delegated_hosts(result_item, original_task) else: host_list = self.get_task_hosts(iterator, original_host, original_task) if original_task.action == 'include_vars': for (var_name, var_value) in iteritems(result_item['ansible_facts']): # find the host we're actually referring too here, which may # be a host that is not really in inventory at all for target_host in host_list: self._variable_manager.set_host_variable(target_host, var_name, var_value) else: cacheable = result_item.pop('_ansible_facts_cacheable', False) for target_host in host_list: if not original_task.action == 'set_fact' or cacheable: self._variable_manager.set_host_facts(target_host, result_item['ansible_facts'].copy()) if original_task.action == 'set_fact': self._variable_manager.set_nonpersistent_facts(target_host, result_item['ansible_facts'].copy()) if 'ansible_stats' in result_item and 'data' in result_item['ansible_stats'] and result_item['ansible_stats']['data']: if 'per_host' not in result_item['ansible_stats'] or result_item['ansible_stats']['per_host']: host_list = self.get_task_hosts(iterator, original_host, original_task) else: host_list = [None] data = result_item['ansible_stats']['data'] aggregate = 'aggregate' in result_item['ansible_stats'] and result_item['ansible_stats']['aggregate'] for myhost in host_list: for k in data.keys(): if aggregate: self._tqm._stats.update_custom_stats(k, data[k], myhost) else: self._tqm._stats.set_custom_stats(k, data[k], myhost) if 'diff' in task_result._result: if self._diff: self._tqm.send_callback('v2_on_file_diff', task_result) if not isinstance(original_task, TaskInclude): self._tqm._stats.increment('ok', original_host.name) if 'changed' in task_result._result and task_result._result['changed']: self._tqm._stats.increment('changed', original_host.name) # finally, send the ok for this task self._tqm.send_callback('v2_runner_on_ok', task_result) self._pending_results -= 1 if original_host.name in self._blocked_hosts: del self._blocked_hosts[original_host.name] # If this is a role task, mark the parent role as being run (if # the task was ok or failed, but not skipped or unreachable) if original_task._role is not None and role_ran: # TODO: and original_task.action != 'include_role':? # lookup the role in the ROLE_CACHE to make sure we're dealing # with the correct object and mark it as executed for (entry, role_obj) in iteritems(iterator._play.ROLE_CACHE[original_task._role._role_name]): if role_obj._uuid == original_task._role._uuid: role_obj._had_task_run[original_host.name] = True ret_results.append(task_result) if one_pass or max_passes is not None and (cur_pass + 1) >= max_passes: break cur_pass += 1 return ret_results def _wait_on_pending_results(self, iterator): ''' Wait for the shared counter to drop to zero, using a short sleep between checks to ensure we don't spin lock ''' ret_results = [] display.debug("waiting for pending results...") while self._pending_results > 0 and not self._tqm._terminated: if self._tqm.has_dead_workers(): raise AnsibleError("A worker was found in a dead state") results = self._process_pending_results(iterator) ret_results.extend(results) if self._pending_results > 0: time.sleep(C.DEFAULT_INTERNAL_POLL_INTERVAL) display.debug("no more pending results, returning what we have") return ret_results def _add_host(self, host_info, iterator): ''' Helper function to add a new host to inventory based on a task result. ''' if host_info: host_name = host_info.get('host_name') # Check if host in inventory, add if not if host_name not in self._inventory.hosts: self._inventory.add_host(host_name, 'all') new_host = self._inventory.hosts.get(host_name) # Set/update the vars for this host new_host.vars = combine_vars(new_host.get_vars(), host_info.get('host_vars', dict())) new_groups = host_info.get('groups', []) for group_name in new_groups: if group_name not in self._inventory.groups: self._inventory.add_group(group_name) new_group = self._inventory.groups[group_name] new_group.add_host(self._inventory.hosts[host_name]) # reconcile inventory, ensures inventory rules are followed self._inventory.reconcile_inventory() def _add_group(self, host, result_item): ''' Helper function to add a group (if it does not exist), and to assign the specified host to that group. ''' changed = False # the host here is from the executor side, which means it was a # serialized/cloned copy and we'll need to look up the proper # host object from the master inventory real_host = self._inventory.hosts[host.name] group_name = result_item.get('add_group') parent_group_names = result_item.get('parent_groups', []) for name in [group_name] + parent_group_names: if name not in self._inventory.groups: # create the new group and add it to inventory self._inventory.add_group(name) changed = True group = self._inventory.groups[group_name] for parent_group_name in parent_group_names: parent_group = self._inventory.groups[parent_group_name] parent_group.add_child_group(group) if real_host.name not in group.get_hosts(): group.add_host(real_host) changed = True if group_name not in host.get_groups(): real_host.add_group(group) changed = True if changed: self._inventory.reconcile_inventory() return changed def _copy_included_file(self, included_file): ''' A proven safe and performant way to create a copy of an included file ''' ti_copy = included_file._task.copy(exclude_parent=True) ti_copy._parent = included_file._task._parent temp_vars = ti_copy.vars.copy() temp_vars.update(included_file._args) ti_copy.vars = temp_vars return ti_copy def _load_included_file(self, included_file, iterator, is_handler=False): ''' Loads an included YAML file of tasks, applying the optional set of variables. ''' display.debug("loading included file: %s" % included_file._filename) try: data = self._loader.load_from_file(included_file._filename) if data is None: return [] elif not isinstance(data, list): raise AnsibleError("included task files must contain a list of tasks") ti_copy = self._copy_included_file(included_file) # pop tags out of the include args, if they were specified there, and assign # them to the include. If the include already had tags specified, we raise an # error so that users know not to specify them both ways tags = included_file._task.vars.pop('tags', []) if isinstance(tags, string_types): tags = tags.split(',') if len(tags) > 0: if len(included_file._task.tags) > 0: raise AnsibleParserError("Include tasks should not specify tags in more than one way (both via args and directly on the task). " "Mixing tag specify styles is prohibited for whole import hierarchy, not only for single import statement", obj=included_file._task._ds) display.deprecated("You should not specify tags in the include parameters. All tags should be specified using the task-level option") included_file._task.tags = tags block_list = load_list_of_blocks( data, play=iterator._play, parent_block=None, task_include=ti_copy, role=included_file._task._role, use_handlers=is_handler, loader=self._loader, variable_manager=self._variable_manager, ) # since we skip incrementing the stats when the task result is # first processed, we do so now for each host in the list for host in included_file._hosts: self._tqm._stats.increment('ok', host.name) except AnsibleError as e: # mark all of the hosts including this file as failed, send callbacks, # and increment the stats for this host for host in included_file._hosts: tr = TaskResult(host=host, task=included_file._task, return_data=dict(failed=True, reason=to_text(e))) iterator.mark_host_failed(host) self._tqm._failed_hosts[host.name] = True self._tqm._stats.increment('failures', host.name) self._tqm.send_callback('v2_runner_on_failed', tr) return [] # finally, send the callback and return the list of blocks loaded self._tqm.send_callback('v2_playbook_on_include', included_file) display.debug("done processing included file") return block_list def run_handlers(self, iterator, play_context): ''' Runs handlers on those hosts which have been notified. ''' result = self._tqm.RUN_OK for handler_block in iterator._play.handlers: # FIXME: handlers need to support the rescue/always portions of blocks too, # but this may take some work in the iterator and gets tricky when # we consider the ability of meta tasks to flush handlers for handler in handler_block.block: if handler._uuid in self._notified_handlers and len(self._notified_handlers[handler._uuid]): result = self._do_handler_run(handler, handler.get_name(), iterator=iterator, play_context=play_context) if not result: break return result def _do_handler_run(self, handler, handler_name, iterator, play_context, notified_hosts=None): # FIXME: need to use iterator.get_failed_hosts() instead? # if not len(self.get_hosts_remaining(iterator._play)): # self._tqm.send_callback('v2_playbook_on_no_hosts_remaining') # result = False # break saved_name = handler.name handler.name = handler_name self._tqm.send_callback('v2_playbook_on_handler_task_start', handler) handler.name = saved_name if notified_hosts is None: notified_hosts = self._notified_handlers[handler._uuid] run_once = False try: action = action_loader.get(handler.action, class_only=True) if handler.run_once or getattr(action, 'BYPASS_HOST_LOOP', False): run_once = True except KeyError: # we don't care here, because the action may simply not have a # corresponding action plugin pass host_results = [] for host in notified_hosts: if not handler.has_triggered(host) and (not iterator.is_failed(host) or play_context.force_handlers): task_vars = self._variable_manager.get_vars(play=iterator._play, host=host, task=handler) self.add_tqm_variables(task_vars, play=iterator._play) self._queue_task(host, handler, task_vars, play_context) if run_once: break # collect the results from the handler run host_results = self._wait_on_pending_results(iterator) try: included_files = IncludedFile.process_include_results( host_results, iterator=iterator, loader=self._loader, variable_manager=self._variable_manager ) except AnsibleError as e: return False result = True if len(included_files) > 0: for included_file in included_files: try: new_blocks = self._load_included_file(included_file, iterator=iterator, is_handler=True) # for every task in each block brought in by the include, add the list # of hosts which included the file to the notified_handlers dict for block in new_blocks: iterator._play.handlers.append(block) iterator.cache_block_tasks(block) for task in block.block: result = self._do_handler_run( handler=task, handler_name=task.get_name(), iterator=iterator, play_context=play_context, notified_hosts=included_file._hosts[:], ) if not result: break except AnsibleError as e: for host in included_file._hosts: iterator.mark_host_failed(host) self._tqm._failed_hosts[host.name] = True display.warning(str(e)) continue # wipe the notification list self._notified_handlers[handler._uuid] = [] display.debug("done running handlers, result is: %s" % result) return result def _take_step(self, task, host=None): ret = False msg = u'Perform task: %s ' % task if host: msg += u'on %s ' % host msg += u'(N)o/(y)es/(c)ontinue: ' resp = display.prompt(msg) if resp.lower() in ['y', 'yes']: display.debug("User ran task") ret = True elif resp.lower() in ['c', 'continue']: display.debug("User ran task and canceled step mode") self._step = False ret = True else: display.debug("User skipped task") display.banner(msg) return ret def _execute_meta(self, task, play_context, iterator, target_host): # meta tasks store their args in the _raw_params field of args, # since they do not use k=v pairs, so get that meta_action = task.args.get('_raw_params') # FIXME(s): # * raise an error or show a warning when a conditional is used # on a meta task that doesn't support them def _evaluate_conditional(h): all_vars = self._variable_manager.get_vars(play=iterator._play, host=h, task=task) templar = Templar(loader=self._loader, variables=all_vars) return task.evaluate_conditional(templar, all_vars) skipped = False msg = '' if meta_action == 'noop': # FIXME: issue a callback for the noop here? msg = "noop" elif meta_action == 'flush_handlers': self.run_handlers(iterator, play_context) msg = "ran handlers" elif meta_action == 'refresh_inventory' or self.flush_cache: self._inventory.refresh_inventory() msg = "inventory successfully refreshed" elif meta_action == 'clear_facts': if _evaluate_conditional(target_host): for host in self._inventory.get_hosts(iterator._play.hosts): hostname = host.get_name() self._variable_manager.clear_facts(hostname) msg = "facts cleared" else: skipped = True elif meta_action == 'clear_host_errors': if _evaluate_conditional(target_host): for host in self._inventory.get_hosts(iterator._play.hosts): self._tqm._failed_hosts.pop(host.name, False) self._tqm._unreachable_hosts.pop(host.name, False) iterator._host_states[host.name].fail_state = iterator.FAILED_NONE msg = "cleared host errors" else: skipped = True elif meta_action == 'end_play': if _evaluate_conditional(target_host): for host in self._inventory.get_hosts(iterator._play.hosts): if host.name not in self._tqm._unreachable_hosts: iterator._host_states[host.name].run_state = iterator.ITERATING_COMPLETE msg = "ending play" elif meta_action == 'reset_connection': if target_host in self._active_connections: connection = Connection(self._active_connections[target_host]) del self._active_connections[target_host] else: connection = connection_loader.get(play_context.connection, play_context, os.devnull) play_context.set_options_from_plugin(connection) if connection: try: connection.reset() msg = 'reset connection' except ConnectionError as e: # most likely socket is already closed display.debug("got an error while closing persistent connection: %s" % e) else: msg = 'no connection, nothing to reset' else: raise AnsibleError("invalid meta action requested: %s" % meta_action, obj=task._ds) result = {'msg': msg} if skipped: result['skipped'] = True else: result['changed'] = False display.vv("META: %s" % msg) return [TaskResult(target_host, task, result)] def get_hosts_left(self, iterator): ''' returns list of available hosts for this iterator by filtering out unreachables ''' hosts_left = [] for host in self._inventory.get_hosts(iterator._play.hosts, order=iterator._play.order): if host.name not in self._tqm._unreachable_hosts: hosts_left.append(host) return hosts_left def update_active_connections(self, results): ''' updates the current active persistent connections ''' for r in results: if 'args' in r._task_fields: socket_path = r._task_fields['args'].get('_ansible_socket') if socket_path: if r._host not in self._active_connections: self._active_connections[r._host] = socket_path class NextAction(object): """ The next action after an interpreter's exit. """ REDO = 1 CONTINUE = 2 EXIT = 3 def __init__(self, result=EXIT): self.result = result class Debugger(cmd.Cmd): prompt_continuous = '> ' # multiple lines def __init__(self, task, host, task_vars, play_context, result, next_action): # cmd.Cmd is old-style class cmd.Cmd.__init__(self) self.prompt = '[%s] %s (debug)> ' % (host, task) self.intro = None self.scope = {} self.scope['task'] = task self.scope['task_vars'] = task_vars self.scope['host'] = host self.scope['play_context'] = play_context self.scope['result'] = result self.next_action = next_action def cmdloop(self): try: cmd.Cmd.cmdloop(self) except KeyboardInterrupt: pass do_h = cmd.Cmd.do_help def do_EOF(self, args): """Quit""" return self.do_quit(args) def do_quit(self, args): """Quit""" display.display('User interrupted execution') self.next_action.result = NextAction.EXIT return True do_q = do_quit def do_continue(self, args): """Continue to next result""" self.next_action.result = NextAction.CONTINUE return True do_c = do_continue def do_redo(self, args): """Schedule task for re-execution. The re-execution may not be the next result""" self.next_action.result = NextAction.REDO return True do_r = do_redo def evaluate(self, args): try: return eval(args, globals(), self.scope) except Exception: t, v = sys.exc_info()[:2] if isinstance(t, str): exc_type_name = t else: exc_type_name = t.__name__ display.display('***%s:%s' % (exc_type_name, repr(v))) raise def do_pprint(self, args): """Pretty Print""" try: result = self.evaluate(args) display.display(pprint.pformat(result)) except Exception: pass do_p = do_pprint def execute(self, args): try: code = compile(args + '\n', '<stdin>', 'single') exec(code, globals(), self.scope) except Exception: t, v = sys.exc_info()[:2] if isinstance(t, str): exc_type_name = t else: exc_type_name = t.__name__ display.display('***%s:%s' % (exc_type_name, repr(v))) raise def default(self, line): try: self.execute(line) except Exception: pass
ptisserand/ansible
lib/ansible/plugins/strategy/__init__.py
Python
gpl-3.0
51,787
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2014, Chris Schmidt <chris.schmidt () contrastsecurity.com> # # Built using https://github.com/hamnis/useful-scripts/blob/master/python/download-maven-artifact # as a reference and starting point. # # 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: maven_artifact short_description: Downloads an Artifact from a Maven Repository version_added: "2.0" description: - Downloads an artifact from a maven repository given the maven coordinates provided to the module. - Can retrieve snapshots or release versions of the artifact and will resolve the latest available version if one is not available. author: "Chris Schmidt (@chrisisbeef)" requirements: - "python >= 2.6" - lxml - boto if using a S3 repository (s3://...) options: group_id: description: - The Maven groupId coordinate required: true artifact_id: description: - The maven artifactId coordinate required: true version: description: - The maven version coordinate required: false default: latest classifier: description: - The maven classifier coordinate required: false default: null extension: description: - The maven type/extension coordinate required: false default: jar repository_url: description: - The URL of the Maven Repository to download from. - Use s3://... if the repository is hosted on Amazon S3, added in version 2.2. required: false default: http://repo1.maven.org/maven2 username: description: - The username to authenticate as to the Maven Repository. Use AWS secret key of the repository is hosted on S3 required: false default: null aliases: [ "aws_secret_key" ] password: description: - The password to authenticate with to the Maven Repository. Use AWS secret access key of the repository is hosted on S3 required: false default: null aliases: [ "aws_secret_access_key" ] dest: description: - The path where the artifact should be written to - If file mode or ownerships are specified and destination path already exists, they affect the downloaded file required: true default: false state: description: - The desired state of the artifact required: true default: present choices: [present,absent] timeout: description: - Specifies a timeout in seconds for the connection attempt required: false default: 10 version_added: "2.3" validate_certs: description: - If C(no), SSL certificates will not be validated. This should only be set to C(no) when no other option exists. required: false default: 'yes' choices: ['yes', 'no'] version_added: "1.9.3" keep_name: description: - If C(yes), the downloaded artifact's name is preserved, i.e the version number remains part of it. - This option only has effect when C(dest) is a directory and C(version) is set to C(latest). required: false default: 'no' choices: ['yes', 'no'] version_added: "2.4" extends_documentation_fragment: - files ''' EXAMPLES = ''' # Download the latest version of the JUnit framework artifact from Maven Central - maven_artifact: group_id: junit artifact_id: junit dest: /tmp/junit-latest.jar # Download JUnit 4.11 from Maven Central - maven_artifact: group_id: junit artifact_id: junit version: 4.11 dest: /tmp/junit-4.11.jar # Download an artifact from a private repository requiring authentication - maven_artifact: group_id: com.company artifact_id: library-name repository_url: 'https://repo.company.com/maven' username: user password: pass dest: /tmp/library-name-latest.jar # Download a WAR File to the Tomcat webapps directory to be deployed - maven_artifact: group_id: com.company artifact_id: web-app extension: war repository_url: 'https://repo.company.com/maven' dest: /var/lib/tomcat7/webapps/web-app.war # Keep a downloaded artifact's name, i.e. retain the version - maven_artifact: version: latest artifact_id: spring-core group_id: org.springframework dest: /tmp/ keep_name: yes ''' import hashlib import os import posixpath import sys from lxml import etree try: import boto3 HAS_BOTO = True except ImportError: HAS_BOTO = False from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.six.moves.urllib.parse import urlparse from ansible.module_utils.urls import fetch_url from ansible.module_utils._text import to_bytes def split_pre_existing_dir(dirname): ''' Return the first pre-existing directory and a list of the new directories that will be created. ''' head, tail = os.path.split(dirname) b_head = to_bytes(head, errors='surrogate_or_strict') if not os.path.exists(b_head): (pre_existing_dir, new_directory_list) = split_pre_existing_dir(head) else: return head, [tail] new_directory_list.append(tail) return pre_existing_dir, new_directory_list def adjust_recursive_directory_permissions(pre_existing_dir, new_directory_list, module, directory_args, changed): ''' Walk the new directories list and make sure that permissions are as we would expect ''' if new_directory_list: working_dir = os.path.join(pre_existing_dir, new_directory_list.pop(0)) directory_args['path'] = working_dir changed = module.set_fs_attributes_if_different(directory_args, changed) changed = adjust_recursive_directory_permissions(working_dir, new_directory_list, module, directory_args, changed) return changed class Artifact(object): def __init__(self, group_id, artifact_id, version, classifier='', extension='jar'): if not group_id: raise ValueError("group_id must be set") if not artifact_id: raise ValueError("artifact_id must be set") self.group_id = group_id self.artifact_id = artifact_id self.version = version self.classifier = classifier if not extension: self.extension = "jar" else: self.extension = extension def is_snapshot(self): return self.version and self.version.endswith("SNAPSHOT") def path(self, with_version=True): base = posixpath.join(self.group_id.replace(".", "/"), self.artifact_id) if with_version and self.version: base = posixpath.join(base, self.version) return base def _generate_filename(self): filename = self.artifact_id + "-" + self.classifier + "." + self.extension if not self.classifier: filename = self.artifact_id + "." + self.extension return filename def get_filename(self, filename=None): if not filename: filename = self._generate_filename() elif os.path.isdir(filename): filename = os.path.join(filename, self._generate_filename()) return filename def __str__(self): result = "%s:%s:%s" % (self.group_id, self.artifact_id, self.version) if self.classifier: result = "%s:%s:%s:%s:%s" % (self.group_id, self.artifact_id, self.extension, self.classifier, self.version) elif self.extension != "jar": result = "%s:%s:%s:%s" % (self.group_id, self.artifact_id, self.extension, self.version) return result @staticmethod def parse(input): parts = input.split(":") if len(parts) >= 3: g = parts[0] a = parts[1] v = parts[len(parts) - 1] t = None c = None if len(parts) == 4: t = parts[2] if len(parts) == 5: t = parts[2] c = parts[3] return Artifact(g, a, v, c, t) else: return None class MavenDownloader: def __init__(self, module, base="http://repo1.maven.org/maven2"): self.module = module if base.endswith("/"): base = base.rstrip("/") self.base = base self.user_agent = "Maven Artifact Downloader/1.0" self.latest_version_found = None def find_latest_version_available(self, artifact): if self.latest_version_found: return self.latest_version_found path = "/%s/maven-metadata.xml" % (artifact.path(False)) xml = self._request(self.base + path, "Failed to download maven-metadata.xml", etree.parse) v = xml.xpath("/metadata/versioning/versions/version[last()]/text()") if v: self.latest_version_found = v[0] return v[0] def find_uri_for_artifact(self, artifact): if artifact.version == "latest": artifact.version = self.find_latest_version_available(artifact) if artifact.is_snapshot(): path = "/%s/maven-metadata.xml" % (artifact.path()) xml = self._request(self.base + path, "Failed to download maven-metadata.xml", etree.parse) timestamp = xml.xpath("/metadata/versioning/snapshot/timestamp/text()")[0] buildNumber = xml.xpath("/metadata/versioning/snapshot/buildNumber/text()")[0] for snapshotArtifact in xml.xpath("/metadata/versioning/snapshotVersions/snapshotVersion"): classifier = snapshotArtifact.xpath("classifier/text()") artifact_classifier = classifier[0] if classifier else '' extension = snapshotArtifact.xpath("extension/text()") artifact_extension = extension[0] if extension else '' if artifact_classifier == artifact.classifier and artifact_extension == artifact.extension: return self._uri_for_artifact(artifact, snapshotArtifact.xpath("value/text()")[0]) return self._uri_for_artifact(artifact, artifact.version.replace("SNAPSHOT", timestamp + "-" + buildNumber)) return self._uri_for_artifact(artifact, artifact.version) def _uri_for_artifact(self, artifact, version=None): if artifact.is_snapshot() and not version: raise ValueError("Expected uniqueversion for snapshot artifact " + str(artifact)) elif not artifact.is_snapshot(): version = artifact.version if artifact.classifier: return posixpath.join(self.base, artifact.path(), artifact.artifact_id + "-" + version + "-" + artifact.classifier + "." + artifact.extension) return posixpath.join(self.base, artifact.path(), artifact.artifact_id + "-" + version + "." + artifact.extension) def _request(self, url, failmsg, f): url_to_use = url parsed_url = urlparse(url) if parsed_url.scheme=='s3': parsed_url = urlparse(url) bucket_name = parsed_url.netloc key_name = parsed_url.path[1:] client = boto3.client('s3',aws_access_key_id=self.module.params.get('username', ''), aws_secret_access_key=self.module.params.get('password', '')) url_to_use = client.generate_presigned_url('get_object',Params={'Bucket':bucket_name,'Key':key_name},ExpiresIn=10) req_timeout = self.module.params.get('timeout') # Hack to add parameters in the way that fetch_url expects self.module.params['url_username'] = self.module.params.get('username', '') self.module.params['url_password'] = self.module.params.get('password', '') self.module.params['http_agent'] = self.module.params.get('user_agent', None) response, info = fetch_url(self.module, url_to_use, timeout=req_timeout) if info['status'] != 200: raise ValueError(failmsg + " because of " + info['msg'] + "for URL " + url_to_use) else: return f(response) def download(self, artifact, filename=None): filename = artifact.get_filename(filename) if not artifact.version or artifact.version == "latest": artifact = Artifact(artifact.group_id, artifact.artifact_id, self.find_latest_version_available(artifact), artifact.classifier, artifact.extension) url = self.find_uri_for_artifact(artifact) result = True if not self.verify_md5(filename, url + ".md5"): response = self._request(url, "Failed to download artifact " + str(artifact), lambda r: r) if response: f = open(filename, 'w') # f.write(response.read()) self._write_chunks(response, f, report_hook=self.chunk_report) f.close() else: result = False return result def chunk_report(self, bytes_so_far, chunk_size, total_size): percent = float(bytes_so_far) / total_size percent = round(percent * 100, 2) sys.stdout.write("Downloaded %d of %d bytes (%0.2f%%)\r" % (bytes_so_far, total_size, percent)) if bytes_so_far >= total_size: sys.stdout.write('\n') def _write_chunks(self, response, file, chunk_size=8192, report_hook=None): total_size = response.info().getheader('Content-Length').strip() total_size = int(total_size) bytes_so_far = 0 while 1: chunk = response.read(chunk_size) bytes_so_far += len(chunk) if not chunk: break file.write(chunk) if report_hook: report_hook(bytes_so_far, chunk_size, total_size) return bytes_so_far def verify_md5(self, file, remote_md5): result = False if os.path.exists(file): local_md5 = self._local_md5(file) remote = self._request(remote_md5, "Failed to download MD5", lambda r: r.read()) result = local_md5 == remote return result def _local_md5(self, file): md5 = hashlib.md5() f = open(file, 'rb') for chunk in iter(lambda: f.read(8192), ''): md5.update(chunk) f.close() return md5.hexdigest() def main(): module = AnsibleModule( argument_spec = dict( group_id = dict(default=None), artifact_id = dict(default=None), version = dict(default="latest"), classifier = dict(default=''), extension = dict(default='jar'), repository_url = dict(default=None), username = dict(default=None,aliases=['aws_secret_key']), password = dict(default=None, no_log=True,aliases=['aws_secret_access_key']), state = dict(default="present", choices=["present","absent"]), # TODO - Implement a "latest" state timeout = dict(default=10, type='int'), dest = dict(type="path", default=None), validate_certs = dict(required=False, default=True, type='bool'), keep_name = dict(required=False, default=False, type='bool'), ), add_file_common_args=True ) repository_url = module.params["repository_url"] if not repository_url: repository_url = "http://repo1.maven.org/maven2" try: parsed_url = urlparse(repository_url) except AttributeError as e: module.fail_json(msg='url parsing went wrong %s' % e) if parsed_url.scheme=='s3' and not HAS_BOTO: module.fail_json(msg='boto3 required for this module, when using s3:// repository URLs') group_id = module.params["group_id"] artifact_id = module.params["artifact_id"] version = module.params["version"] classifier = module.params["classifier"] extension = module.params["extension"] state = module.params["state"] dest = module.params["dest"] b_dest = to_bytes(dest, errors='surrogate_or_strict') keep_name = module.params["keep_name"] #downloader = MavenDownloader(module, repository_url, repository_username, repository_password) downloader = MavenDownloader(module, repository_url) try: artifact = Artifact(group_id, artifact_id, version, classifier, extension) except ValueError as e: module.fail_json(msg=e.args[0]) changed = False prev_state = "absent" if dest.endswith(os.sep): b_dest = to_bytes(dest, errors='surrogate_or_strict') if not os.path.exists(b_dest): (pre_existing_dir, new_directory_list) = split_pre_existing_dir(dest) os.makedirs(b_dest) directory_args = module.load_file_common_arguments(module.params) directory_mode = module.params["directory_mode"] if directory_mode is not None: directory_args['mode'] = directory_mode else: directory_args['mode'] = None changed = adjust_recursive_directory_permissions(pre_existing_dir, new_directory_list, module, directory_args, changed) if os.path.isdir(b_dest): version_part = version if keep_name and version == 'latest': version_part = downloader.find_latest_version_available(artifact) if classifier: dest = posixpath.join(dest, "%s-%s-%s.%s" % (artifact_id, version_part, classifier, extension)) else: dest = posixpath.join(dest, "%s-%s.%s" % (artifact_id, version_part, extension)) b_dest = to_bytes(dest, errors='surrogate_or_strict') if os.path.lexists(b_dest) and downloader.verify_md5(dest, downloader.find_uri_for_artifact(artifact) + '.md5'): prev_state = "present" if prev_state == "absent": try: if downloader.download(artifact, b_dest): changed = True else: module.fail_json(msg="Unable to download the artifact") except ValueError as e: module.fail_json(msg=e.args[0]) module.params['dest'] = dest file_args = module.load_file_common_arguments(module.params) changed = module.set_fs_attributes_if_different(file_args, changed) if changed: module.exit_json(state=state, dest=dest, group_id=group_id, artifact_id=artifact_id, version=version, classifier=classifier, extension=extension, repository_url=repository_url, changed=changed) else: module.exit_json(state=state, dest=dest, changed=changed) if __name__ == '__main__': main()
marratj/ansible
lib/ansible/modules/packaging/language/maven_artifact.py
Python
gpl-3.0
18,975
# -*- encoding: utf-8 -*- ############################################################################## # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see http://www.gnu.org/licenses/. # ############################################################################## { "name": "MRP - Product variants", "version": "1.0", "depends": [ "product", "mrp", "product_variants_no_automatic_creation", "mrp_production_editable_scheduled_products", ], "author": "OdooMRP team," "AvanzOSC," "Serv. Tecnol. Avanzados - Pedro M. Baeza", "contributors": [ "Oihane Crucelaegui <oihanecrucelaegi@avanzosc.es>", "Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>", "Ana Juaristi <ajuaristio@gmail.com>", ], "category": "Manufacturing", "website": "http://www.odoomrp.com", "summary": "Customized product in manufacturing", "data": [ "security/ir.model.access.csv", "views/mrp_production_view.xml", "views/product_attribute_view.xml", ], "installable": True, "post_init_hook": "assign_product_template", }
odoocn/odoomrp-wip
mrp_product_variants/__openerp__.py
Python
agpl-3.0
1,735
#!/usr/bin/env python # Line too long - pylint: disable=C0301 # Invalid name - pylint: disable=C0103 """ Copyright (c) 2004-Present Pivotal Software, Inc. This program and the accompanying materials are made available under the terms of the 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. Capture information regarding the machine we run test on """ import os import platform import socket import re ##### class GpSystem: """ Capture information regarding the machine we run test on @class GpSystem @organization: DCD Partner Engineering @contact: Kenneth Wong @modified: Johnny Soedomo @note: platform.system returns Linux for both Redhat and SuSE, check the release file @change: Jacqui Taing - added attributes: os_version, os_major_version to provide OS release version """ ### def __init__(self): """ Constructor for GpSystem regards information we care about on the test system """ self.architecture = platform.machine() myos = platform.system() if myos == "Darwin": self.os = 'OSX' (version, major_version) = self.__getOsVersion() self.os_version = version self.os_major_version = major_version elif myos == "Linux": if os.path.exists("/etc/SuSE-release"): self.os = 'SUSE' (version, major_version) = self.__getOsVersion('/etc/SuSE-release') self.os_version = version self.os_major_version = major_version elif os.path.exists("/etc/redhat-release"): self.os = 'RHEL' (version, major_version) = self.__getOsVersion('/etc/redhat-release') self.os_version = version self.os_major_version = major_version elif myos == "SunOS": self.os = 'SOL' (version, major_version) = self.__getOsVersion('/etc/release') self.os_version = version self.os_major_version = major_version self.host = socket.gethostname() ### def __str__(self): """ @return: a string consists of host, architecture, os, os version, os major version """ return '\nGpSystem:\n host: %s\n architecture: %s\n os: %s\n os version: %s\n os major version: %s' % (self.host, self.architecture, self.os, self.os_version, self.os_major_version) def __getOsVersion(self, releasefile=None): """ @summary: Internal function to get the OS full release version (e.g. 5.5.) and major release version (e.g. 5) @return: list (full_version, major_version), e.g. (5.5, 5) """ if self.os == 'OSX': full_version = platform.mac_ver()[0] major_version = full_version.split('.')[0] return (full_version, major_version) else: if os.path.exists(releasefile): f = open(releasefile) releasetext = f.read() f.close() full_version = re.search('[\d\.*\d]+', releasetext).group(0) major_version = full_version.split('.')[0] return (full_version, major_version) else: return None ### def GetArchitecture(self): """ @return: architecture """ return self.architecture ### def GetOS(self): """ @return: os """ return self.os def GetOSMajorVersion(self): """ @return: major release version of OS, e.g. 5 for RHEL 5.5 """ return self.os_major_version def GetOSVersion(self): """ @return: full release version of OS, e.g. 5.5 for RHEL 5.5. """ return self.os_version ### def GetHost(self): """ @return: host """ return self.host ########################## if __name__ == '__main__': gpSystem = GpSystem() print(gpSystem)
Chibin/gpdb
src/test/tinc/tincrepo/mpp/lib/gpSystem.py
Python
apache-2.0
4,502
"""Unit tests for the io module.""" # Tests of io are scattered over the test suite: # * test_bufio - tests file buffering # * test_memoryio - tests BytesIO and StringIO # * test_fileio - tests FileIO # * test_file - tests the file interface # * test_io - tests everything else in the io module # * test_univnewlines - tests universal newline support # * test_largefile - tests operations on a file greater than 2**32 bytes # (only enabled with -ulargefile) ################################################################################ # ATTENTION TEST WRITERS!!! ################################################################################ # When writing tests for io, it's important to test both the C and Python # implementations. This is usually done by writing a base test that refers to # the type it is testing as a attribute. Then it provides custom subclasses to # test both implementations. This file has lots of examples. ################################################################################ from __future__ import print_function from __future__ import unicode_literals import os import sys import time import array import random import unittest import weakref import warnings import abc import signal import errno from itertools import cycle, count from collections import deque from UserList import UserList from test import test_support as support import contextlib import codecs import io # C implementation of io import _pyio as pyio # Python implementation of io try: import threading except ImportError: threading = None try: import fcntl except ImportError: fcntl = None __metaclass__ = type bytes = support.py3k_bytes def _default_chunk_size(): """Get the default TextIOWrapper chunk size""" with io.open(__file__, "r", encoding="latin1") as f: return f._CHUNK_SIZE class MockRawIOWithoutRead: """A RawIO implementation without read(), so as to exercise the default RawIO.read() which calls readinto().""" def __init__(self, read_stack=()): self._read_stack = list(read_stack) self._write_stack = [] self._reads = 0 self._extraneous_reads = 0 def write(self, b): self._write_stack.append(bytes(b)) return len(b) def writable(self): return True def fileno(self): return 42 def readable(self): return True def seekable(self): return True def seek(self, pos, whence): return 0 # wrong but we gotta return something def tell(self): return 0 # same comment as above def readinto(self, buf): self._reads += 1 max_len = len(buf) try: data = self._read_stack[0] except IndexError: self._extraneous_reads += 1 return 0 if data is None: del self._read_stack[0] return None n = len(data) if len(data) <= max_len: del self._read_stack[0] buf[:n] = data return n else: buf[:] = data[:max_len] self._read_stack[0] = data[max_len:] return max_len def truncate(self, pos=None): return pos class CMockRawIOWithoutRead(MockRawIOWithoutRead, io.RawIOBase): pass class PyMockRawIOWithoutRead(MockRawIOWithoutRead, pyio.RawIOBase): pass class MockRawIO(MockRawIOWithoutRead): def read(self, n=None): self._reads += 1 try: return self._read_stack.pop(0) except: self._extraneous_reads += 1 return b"" class CMockRawIO(MockRawIO, io.RawIOBase): pass class PyMockRawIO(MockRawIO, pyio.RawIOBase): pass class MisbehavedRawIO(MockRawIO): def write(self, b): return MockRawIO.write(self, b) * 2 def read(self, n=None): return MockRawIO.read(self, n) * 2 def seek(self, pos, whence): return -123 def tell(self): return -456 def readinto(self, buf): MockRawIO.readinto(self, buf) return len(buf) * 5 class CMisbehavedRawIO(MisbehavedRawIO, io.RawIOBase): pass class PyMisbehavedRawIO(MisbehavedRawIO, pyio.RawIOBase): pass class CloseFailureIO(MockRawIO): closed = 0 def close(self): if not self.closed: self.closed = 1 raise IOError class CCloseFailureIO(CloseFailureIO, io.RawIOBase): pass class PyCloseFailureIO(CloseFailureIO, pyio.RawIOBase): pass class MockFileIO: def __init__(self, data): self.read_history = [] super(MockFileIO, self).__init__(data) def read(self, n=None): res = super(MockFileIO, self).read(n) self.read_history.append(None if res is None else len(res)) return res def readinto(self, b): res = super(MockFileIO, self).readinto(b) self.read_history.append(res) return res class CMockFileIO(MockFileIO, io.BytesIO): pass class PyMockFileIO(MockFileIO, pyio.BytesIO): pass class MockNonBlockWriterIO: def __init__(self): self._write_stack = [] self._blocker_char = None def pop_written(self): s = b"".join(self._write_stack) self._write_stack[:] = [] return s def block_on(self, char): """Block when a given char is encountered.""" self._blocker_char = char def readable(self): return True def seekable(self): return True def writable(self): return True def write(self, b): b = bytes(b) n = -1 if self._blocker_char: try: n = b.index(self._blocker_char) except ValueError: pass else: if n > 0: # write data up to the first blocker self._write_stack.append(b[:n]) return n else: # cancel blocker and indicate would block self._blocker_char = None return None self._write_stack.append(b) return len(b) class CMockNonBlockWriterIO(MockNonBlockWriterIO, io.RawIOBase): BlockingIOError = io.BlockingIOError class PyMockNonBlockWriterIO(MockNonBlockWriterIO, pyio.RawIOBase): BlockingIOError = pyio.BlockingIOError class IOTest(unittest.TestCase): def setUp(self): support.unlink(support.TESTFN) def tearDown(self): support.unlink(support.TESTFN) def write_ops(self, f): self.assertEqual(f.write(b"blah."), 5) f.truncate(0) self.assertEqual(f.tell(), 5) f.seek(0) self.assertEqual(f.write(b"blah."), 5) self.assertEqual(f.seek(0), 0) self.assertEqual(f.write(b"Hello."), 6) self.assertEqual(f.tell(), 6) self.assertEqual(f.seek(-1, 1), 5) self.assertEqual(f.tell(), 5) self.assertEqual(f.write(bytearray(b" world\n\n\n")), 9) self.assertEqual(f.seek(0), 0) self.assertEqual(f.write(b"h"), 1) self.assertEqual(f.seek(-1, 2), 13) self.assertEqual(f.tell(), 13) self.assertEqual(f.truncate(12), 12) self.assertEqual(f.tell(), 13) self.assertRaises(TypeError, f.seek, 0.0) def read_ops(self, f, buffered=False): data = f.read(5) self.assertEqual(data, b"hello") data = bytearray(data) self.assertEqual(f.readinto(data), 5) self.assertEqual(data, b" worl") self.assertEqual(f.readinto(data), 2) self.assertEqual(len(data), 5) self.assertEqual(data[:2], b"d\n") self.assertEqual(f.seek(0), 0) self.assertEqual(f.read(20), b"hello world\n") self.assertEqual(f.read(1), b"") self.assertEqual(f.readinto(bytearray(b"x")), 0) self.assertEqual(f.seek(-6, 2), 6) self.assertEqual(f.read(5), b"world") self.assertEqual(f.read(0), b"") self.assertEqual(f.readinto(bytearray()), 0) self.assertEqual(f.seek(-6, 1), 5) self.assertEqual(f.read(5), b" worl") self.assertEqual(f.tell(), 10) self.assertRaises(TypeError, f.seek, 0.0) if buffered: f.seek(0) self.assertEqual(f.read(), b"hello world\n") f.seek(6) self.assertEqual(f.read(), b"world\n") self.assertEqual(f.read(), b"") LARGE = 2**31 def large_file_ops(self, f): assert f.readable() assert f.writable() self.assertEqual(f.seek(self.LARGE), self.LARGE) self.assertEqual(f.tell(), self.LARGE) self.assertEqual(f.write(b"xxx"), 3) self.assertEqual(f.tell(), self.LARGE + 3) self.assertEqual(f.seek(-1, 1), self.LARGE + 2) self.assertEqual(f.truncate(), self.LARGE + 2) self.assertEqual(f.tell(), self.LARGE + 2) self.assertEqual(f.seek(0, 2), self.LARGE + 2) self.assertEqual(f.truncate(self.LARGE + 1), self.LARGE + 1) self.assertEqual(f.tell(), self.LARGE + 2) self.assertEqual(f.seek(0, 2), self.LARGE + 1) self.assertEqual(f.seek(-1, 2), self.LARGE) self.assertEqual(f.read(2), b"x") def test_invalid_operations(self): # Try writing on a file opened in read mode and vice-versa. for mode in ("w", "wb"): with self.open(support.TESTFN, mode) as fp: self.assertRaises(IOError, fp.read) self.assertRaises(IOError, fp.readline) with self.open(support.TESTFN, "rb") as fp: self.assertRaises(IOError, fp.write, b"blah") self.assertRaises(IOError, fp.writelines, [b"blah\n"]) with self.open(support.TESTFN, "r") as fp: self.assertRaises(IOError, fp.write, "blah") self.assertRaises(IOError, fp.writelines, ["blah\n"]) def test_raw_file_io(self): with self.open(support.TESTFN, "wb", buffering=0) as f: self.assertEqual(f.readable(), False) self.assertEqual(f.writable(), True) self.assertEqual(f.seekable(), True) self.write_ops(f) with self.open(support.TESTFN, "rb", buffering=0) as f: self.assertEqual(f.readable(), True) self.assertEqual(f.writable(), False) self.assertEqual(f.seekable(), True) self.read_ops(f) def test_buffered_file_io(self): with self.open(support.TESTFN, "wb") as f: self.assertEqual(f.readable(), False) self.assertEqual(f.writable(), True) self.assertEqual(f.seekable(), True) self.write_ops(f) with self.open(support.TESTFN, "rb") as f: self.assertEqual(f.readable(), True) self.assertEqual(f.writable(), False) self.assertEqual(f.seekable(), True) self.read_ops(f, True) def test_readline(self): with self.open(support.TESTFN, "wb") as f: f.write(b"abc\ndef\nxyzzy\nfoo\x00bar\nanother line") with self.open(support.TESTFN, "rb") as f: self.assertEqual(f.readline(), b"abc\n") self.assertEqual(f.readline(10), b"def\n") self.assertEqual(f.readline(2), b"xy") self.assertEqual(f.readline(4), b"zzy\n") self.assertEqual(f.readline(), b"foo\x00bar\n") self.assertEqual(f.readline(None), b"another line") self.assertRaises(TypeError, f.readline, 5.3) with self.open(support.TESTFN, "r") as f: self.assertRaises(TypeError, f.readline, 5.3) def test_raw_bytes_io(self): f = self.BytesIO() self.write_ops(f) data = f.getvalue() self.assertEqual(data, b"hello world\n") f = self.BytesIO(data) self.read_ops(f, True) def test_large_file_ops(self): # On Windows and Mac OSX this test comsumes large resources; It takes # a long time to build the >2GB file and takes >2GB of disk space # therefore the resource must be enabled to run this test. if sys.platform[:3] == 'win' or sys.platform == 'darwin': support.requires( 'largefile', 'test requires %s bytes and a long time to run' % self.LARGE) with self.open(support.TESTFN, "w+b", 0) as f: self.large_file_ops(f) with self.open(support.TESTFN, "w+b") as f: self.large_file_ops(f) def test_with_open(self): for bufsize in (0, 1, 100): f = None with self.open(support.TESTFN, "wb", bufsize) as f: f.write(b"xxx") self.assertEqual(f.closed, True) f = None try: with self.open(support.TESTFN, "wb", bufsize) as f: 1 // 0 except ZeroDivisionError: self.assertEqual(f.closed, True) else: self.fail("1 // 0 didn't raise an exception") # issue 5008 def test_append_mode_tell(self): with self.open(support.TESTFN, "wb") as f: f.write(b"xxx") with self.open(support.TESTFN, "ab", buffering=0) as f: self.assertEqual(f.tell(), 3) with self.open(support.TESTFN, "ab") as f: self.assertEqual(f.tell(), 3) with self.open(support.TESTFN, "a") as f: self.assertTrue(f.tell() > 0) def test_destructor(self): record = [] class MyFileIO(self.FileIO): def __del__(self): record.append(1) try: f = super(MyFileIO, self).__del__ except AttributeError: pass else: f() def close(self): record.append(2) super(MyFileIO, self).close() def flush(self): record.append(3) super(MyFileIO, self).flush() f = MyFileIO(support.TESTFN, "wb") f.write(b"xxx") del f support.gc_collect() self.assertEqual(record, [1, 2, 3]) with self.open(support.TESTFN, "rb") as f: self.assertEqual(f.read(), b"xxx") def _check_base_destructor(self, base): record = [] class MyIO(base): def __init__(self): # This exercises the availability of attributes on object # destruction. # (in the C version, close() is called by the tp_dealloc # function, not by __del__) self.on_del = 1 self.on_close = 2 self.on_flush = 3 def __del__(self): record.append(self.on_del) try: f = super(MyIO, self).__del__ except AttributeError: pass else: f() def close(self): record.append(self.on_close) super(MyIO, self).close() def flush(self): record.append(self.on_flush) super(MyIO, self).flush() f = MyIO() del f support.gc_collect() self.assertEqual(record, [1, 2, 3]) def test_IOBase_destructor(self): self._check_base_destructor(self.IOBase) def test_RawIOBase_destructor(self): self._check_base_destructor(self.RawIOBase) def test_BufferedIOBase_destructor(self): self._check_base_destructor(self.BufferedIOBase) def test_TextIOBase_destructor(self): self._check_base_destructor(self.TextIOBase) def test_close_flushes(self): with self.open(support.TESTFN, "wb") as f: f.write(b"xxx") with self.open(support.TESTFN, "rb") as f: self.assertEqual(f.read(), b"xxx") def test_array_writes(self): a = array.array(b'i', range(10)) n = len(a.tostring()) with self.open(support.TESTFN, "wb", 0) as f: self.assertEqual(f.write(a), n) with self.open(support.TESTFN, "wb") as f: self.assertEqual(f.write(a), n) def test_closefd(self): self.assertRaises(ValueError, self.open, support.TESTFN, 'w', closefd=False) def test_read_closed(self): with self.open(support.TESTFN, "w") as f: f.write("egg\n") with self.open(support.TESTFN, "r") as f: file = self.open(f.fileno(), "r", closefd=False) self.assertEqual(file.read(), "egg\n") file.seek(0) file.close() self.assertRaises(ValueError, file.read) def test_no_closefd_with_filename(self): # can't use closefd in combination with a file name self.assertRaises(ValueError, self.open, support.TESTFN, "r", closefd=False) def test_closefd_attr(self): with self.open(support.TESTFN, "wb") as f: f.write(b"egg\n") with self.open(support.TESTFN, "r") as f: self.assertEqual(f.buffer.raw.closefd, True) file = self.open(f.fileno(), "r", closefd=False) self.assertEqual(file.buffer.raw.closefd, False) def test_garbage_collection(self): # FileIO objects are collected, and collecting them flushes # all data to disk. f = self.FileIO(support.TESTFN, "wb") f.write(b"abcxxx") f.f = f wr = weakref.ref(f) del f support.gc_collect() self.assertTrue(wr() is None, wr) with self.open(support.TESTFN, "rb") as f: self.assertEqual(f.read(), b"abcxxx") def test_unbounded_file(self): # Issue #1174606: reading from an unbounded stream such as /dev/zero. zero = "/dev/zero" if not os.path.exists(zero): self.skipTest("{0} does not exist".format(zero)) if sys.maxsize > 0x7FFFFFFF: self.skipTest("test can only run in a 32-bit address space") if support.real_max_memuse < support._2G: self.skipTest("test requires at least 2GB of memory") with self.open(zero, "rb", buffering=0) as f: self.assertRaises(OverflowError, f.read) with self.open(zero, "rb") as f: self.assertRaises(OverflowError, f.read) with self.open(zero, "r") as f: self.assertRaises(OverflowError, f.read) def check_flush_error_on_close(self, *args, **kwargs): # Test that the file is closed despite failed flush # and that flush() is called before file closed. f = self.open(*args, **kwargs) closed = [] def bad_flush(): closed[:] = [f.closed] raise IOError() f.flush = bad_flush self.assertRaises(IOError, f.close) # exception not swallowed self.assertTrue(f.closed) self.assertTrue(closed) # flush() called self.assertFalse(closed[0]) # flush() called before file closed f.flush = lambda: None # break reference loop def test_flush_error_on_close(self): # raw file # Issue #5700: io.FileIO calls flush() after file closed self.check_flush_error_on_close(support.TESTFN, 'wb', buffering=0) fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT) self.check_flush_error_on_close(fd, 'wb', buffering=0) fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT) self.check_flush_error_on_close(fd, 'wb', buffering=0, closefd=False) os.close(fd) # buffered io self.check_flush_error_on_close(support.TESTFN, 'wb') fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT) self.check_flush_error_on_close(fd, 'wb') fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT) self.check_flush_error_on_close(fd, 'wb', closefd=False) os.close(fd) # text io self.check_flush_error_on_close(support.TESTFN, 'w') fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT) self.check_flush_error_on_close(fd, 'w') fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT) self.check_flush_error_on_close(fd, 'w', closefd=False) os.close(fd) def test_multi_close(self): f = self.open(support.TESTFN, "wb", buffering=0) f.close() f.close() f.close() self.assertRaises(ValueError, f.flush) def test_RawIOBase_read(self): # Exercise the default RawIOBase.read() implementation (which calls # readinto() internally). rawio = self.MockRawIOWithoutRead((b"abc", b"d", None, b"efg", None)) self.assertEqual(rawio.read(2), b"ab") self.assertEqual(rawio.read(2), b"c") self.assertEqual(rawio.read(2), b"d") self.assertEqual(rawio.read(2), None) self.assertEqual(rawio.read(2), b"ef") self.assertEqual(rawio.read(2), b"g") self.assertEqual(rawio.read(2), None) self.assertEqual(rawio.read(2), b"") def test_fileio_closefd(self): # Issue #4841 with self.open(__file__, 'rb') as f1, \ self.open(__file__, 'rb') as f2: fileio = self.FileIO(f1.fileno(), closefd=False) # .__init__() must not close f1 fileio.__init__(f2.fileno(), closefd=False) f1.readline() # .close() must not close f2 fileio.close() f2.readline() def test_nonbuffered_textio(self): with warnings.catch_warnings(record=True) as recorded: with self.assertRaises(ValueError): self.open(support.TESTFN, 'w', buffering=0) support.gc_collect() self.assertEqual(recorded, []) def test_invalid_newline(self): with warnings.catch_warnings(record=True) as recorded: with self.assertRaises(ValueError): self.open(support.TESTFN, 'w', newline='invalid') support.gc_collect() self.assertEqual(recorded, []) class CIOTest(IOTest): def test_IOBase_finalize(self): # Issue #12149: segmentation fault on _PyIOBase_finalize when both a # class which inherits IOBase and an object of this class are caught # in a reference cycle and close() is already in the method cache. class MyIO(self.IOBase): def close(self): pass # create an instance to populate the method cache MyIO() obj = MyIO() obj.obj = obj wr = weakref.ref(obj) del MyIO del obj support.gc_collect() self.assertTrue(wr() is None, wr) class PyIOTest(IOTest): test_array_writes = unittest.skip( "len(array.array) returns number of elements rather than bytelength" )(IOTest.test_array_writes) class CommonBufferedTests: # Tests common to BufferedReader, BufferedWriter and BufferedRandom def test_detach(self): raw = self.MockRawIO() buf = self.tp(raw) self.assertIs(buf.detach(), raw) self.assertRaises(ValueError, buf.detach) repr(buf) # Should still work def test_fileno(self): rawio = self.MockRawIO() bufio = self.tp(rawio) self.assertEqual(42, bufio.fileno()) @unittest.skip('test having existential crisis') def test_no_fileno(self): # XXX will we always have fileno() function? If so, kill # this test. Else, write it. pass def test_invalid_args(self): rawio = self.MockRawIO() bufio = self.tp(rawio) # Invalid whence self.assertRaises(ValueError, bufio.seek, 0, -1) self.assertRaises(ValueError, bufio.seek, 0, 3) def test_override_destructor(self): tp = self.tp record = [] class MyBufferedIO(tp): def __del__(self): record.append(1) try: f = super(MyBufferedIO, self).__del__ except AttributeError: pass else: f() def close(self): record.append(2) super(MyBufferedIO, self).close() def flush(self): record.append(3) super(MyBufferedIO, self).flush() rawio = self.MockRawIO() bufio = MyBufferedIO(rawio) writable = bufio.writable() del bufio support.gc_collect() if writable: self.assertEqual(record, [1, 2, 3]) else: self.assertEqual(record, [1, 2]) def test_context_manager(self): # Test usability as a context manager rawio = self.MockRawIO() bufio = self.tp(rawio) def _with(): with bufio: pass _with() # bufio should now be closed, and using it a second time should raise # a ValueError. self.assertRaises(ValueError, _with) def test_error_through_destructor(self): # Test that the exception state is not modified by a destructor, # even if close() fails. rawio = self.CloseFailureIO() def f(): self.tp(rawio).xyzzy with support.captured_output("stderr") as s: self.assertRaises(AttributeError, f) s = s.getvalue().strip() if s: # The destructor *may* have printed an unraisable error, check it self.assertEqual(len(s.splitlines()), 1) self.assertTrue(s.startswith("Exception IOError: "), s) self.assertTrue(s.endswith(" ignored"), s) def test_repr(self): raw = self.MockRawIO() b = self.tp(raw) clsname = "%s.%s" % (self.tp.__module__, self.tp.__name__) self.assertEqual(repr(b), "<%s>" % clsname) raw.name = "dummy" self.assertEqual(repr(b), "<%s name=u'dummy'>" % clsname) raw.name = b"dummy" self.assertEqual(repr(b), "<%s name='dummy'>" % clsname) def test_flush_error_on_close(self): # Test that buffered file is closed despite failed flush # and that flush() is called before file closed. raw = self.MockRawIO() closed = [] def bad_flush(): closed[:] = [b.closed, raw.closed] raise IOError() raw.flush = bad_flush b = self.tp(raw) self.assertRaises(IOError, b.close) # exception not swallowed self.assertTrue(b.closed) self.assertTrue(raw.closed) self.assertTrue(closed) # flush() called self.assertFalse(closed[0]) # flush() called before file closed self.assertFalse(closed[1]) raw.flush = lambda: None # break reference loop def test_close_error_on_close(self): raw = self.MockRawIO() def bad_flush(): raise IOError('flush') def bad_close(): raise IOError('close') raw.close = bad_close b = self.tp(raw) b.flush = bad_flush with self.assertRaises(IOError) as err: # exception not swallowed b.close() self.assertEqual(err.exception.args, ('close',)) self.assertFalse(b.closed) def test_multi_close(self): raw = self.MockRawIO() b = self.tp(raw) b.close() b.close() b.close() self.assertRaises(ValueError, b.flush) def test_readonly_attributes(self): raw = self.MockRawIO() buf = self.tp(raw) x = self.MockRawIO() with self.assertRaises((AttributeError, TypeError)): buf.raw = x class SizeofTest: @support.cpython_only def test_sizeof(self): bufsize1 = 4096 bufsize2 = 8192 rawio = self.MockRawIO() bufio = self.tp(rawio, buffer_size=bufsize1) size = sys.getsizeof(bufio) - bufsize1 rawio = self.MockRawIO() bufio = self.tp(rawio, buffer_size=bufsize2) self.assertEqual(sys.getsizeof(bufio), size + bufsize2) class BufferedReaderTest(unittest.TestCase, CommonBufferedTests): read_mode = "rb" def test_constructor(self): rawio = self.MockRawIO([b"abc"]) bufio = self.tp(rawio) bufio.__init__(rawio) bufio.__init__(rawio, buffer_size=1024) bufio.__init__(rawio, buffer_size=16) self.assertEqual(b"abc", bufio.read()) self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0) self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16) self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1) rawio = self.MockRawIO([b"abc"]) bufio.__init__(rawio) self.assertEqual(b"abc", bufio.read()) def test_uninitialized(self): bufio = self.tp.__new__(self.tp) del bufio bufio = self.tp.__new__(self.tp) self.assertRaisesRegexp((ValueError, AttributeError), 'uninitialized|has no attribute', bufio.read, 0) bufio.__init__(self.MockRawIO()) self.assertEqual(bufio.read(0), b'') def test_read(self): for arg in (None, 7): rawio = self.MockRawIO((b"abc", b"d", b"efg")) bufio = self.tp(rawio) self.assertEqual(b"abcdefg", bufio.read(arg)) # Invalid args self.assertRaises(ValueError, bufio.read, -2) def test_read1(self): rawio = self.MockRawIO((b"abc", b"d", b"efg")) bufio = self.tp(rawio) self.assertEqual(b"a", bufio.read(1)) self.assertEqual(b"b", bufio.read1(1)) self.assertEqual(rawio._reads, 1) self.assertEqual(b"c", bufio.read1(100)) self.assertEqual(rawio._reads, 1) self.assertEqual(b"d", bufio.read1(100)) self.assertEqual(rawio._reads, 2) self.assertEqual(b"efg", bufio.read1(100)) self.assertEqual(rawio._reads, 3) self.assertEqual(b"", bufio.read1(100)) self.assertEqual(rawio._reads, 4) # Invalid args self.assertRaises(ValueError, bufio.read1, -1) def test_readinto(self): rawio = self.MockRawIO((b"abc", b"d", b"efg")) bufio = self.tp(rawio) b = bytearray(2) self.assertEqual(bufio.readinto(b), 2) self.assertEqual(b, b"ab") self.assertEqual(bufio.readinto(b), 2) self.assertEqual(b, b"cd") self.assertEqual(bufio.readinto(b), 2) self.assertEqual(b, b"ef") self.assertEqual(bufio.readinto(b), 1) self.assertEqual(b, b"gf") self.assertEqual(bufio.readinto(b), 0) self.assertEqual(b, b"gf") def test_readlines(self): def bufio(): rawio = self.MockRawIO((b"abc\n", b"d\n", b"ef")) return self.tp(rawio) self.assertEqual(bufio().readlines(), [b"abc\n", b"d\n", b"ef"]) self.assertEqual(bufio().readlines(5), [b"abc\n", b"d\n"]) self.assertEqual(bufio().readlines(None), [b"abc\n", b"d\n", b"ef"]) def test_buffering(self): data = b"abcdefghi" dlen = len(data) tests = [ [ 100, [ 3, 1, 4, 8 ], [ dlen, 0 ] ], [ 100, [ 3, 3, 3], [ dlen ] ], [ 4, [ 1, 2, 4, 2 ], [ 4, 4, 1 ] ], ] for bufsize, buf_read_sizes, raw_read_sizes in tests: rawio = self.MockFileIO(data) bufio = self.tp(rawio, buffer_size=bufsize) pos = 0 for nbytes in buf_read_sizes: self.assertEqual(bufio.read(nbytes), data[pos:pos+nbytes]) pos += nbytes # this is mildly implementation-dependent self.assertEqual(rawio.read_history, raw_read_sizes) def test_read_non_blocking(self): # Inject some None's in there to simulate EWOULDBLOCK rawio = self.MockRawIO((b"abc", b"d", None, b"efg", None, None, None)) bufio = self.tp(rawio) self.assertEqual(b"abcd", bufio.read(6)) self.assertEqual(b"e", bufio.read(1)) self.assertEqual(b"fg", bufio.read()) self.assertEqual(b"", bufio.peek(1)) self.assertIsNone(bufio.read()) self.assertEqual(b"", bufio.read()) rawio = self.MockRawIO((b"a", None, None)) self.assertEqual(b"a", rawio.readall()) self.assertIsNone(rawio.readall()) def test_read_past_eof(self): rawio = self.MockRawIO((b"abc", b"d", b"efg")) bufio = self.tp(rawio) self.assertEqual(b"abcdefg", bufio.read(9000)) def test_read_all(self): rawio = self.MockRawIO((b"abc", b"d", b"efg")) bufio = self.tp(rawio) self.assertEqual(b"abcdefg", bufio.read()) @unittest.skipUnless(threading, 'Threading required for this test.') @support.requires_resource('cpu') def test_threads(self): try: # Write out many bytes with exactly the same number of 0's, # 1's... 255's. This will help us check that concurrent reading # doesn't duplicate or forget contents. N = 1000 l = list(range(256)) * N random.shuffle(l) s = bytes(bytearray(l)) with self.open(support.TESTFN, "wb") as f: f.write(s) with self.open(support.TESTFN, self.read_mode, buffering=0) as raw: bufio = self.tp(raw, 8) errors = [] results = [] def f(): try: # Intra-buffer read then buffer-flushing read for n in cycle([1, 19]): s = bufio.read(n) if not s: break # list.append() is atomic results.append(s) except Exception as e: errors.append(e) raise threads = [threading.Thread(target=f) for x in range(20)] with support.start_threads(threads): time.sleep(0.02) # yield self.assertFalse(errors, "the following exceptions were caught: %r" % errors) s = b''.join(results) for i in range(256): c = bytes(bytearray([i])) self.assertEqual(s.count(c), N) finally: support.unlink(support.TESTFN) def test_misbehaved_io(self): rawio = self.MisbehavedRawIO((b"abc", b"d", b"efg")) bufio = self.tp(rawio) self.assertRaises(IOError, bufio.seek, 0) self.assertRaises(IOError, bufio.tell) def test_no_extraneous_read(self): # Issue #9550; when the raw IO object has satisfied the read request, # we should not issue any additional reads, otherwise it may block # (e.g. socket). bufsize = 16 for n in (2, bufsize - 1, bufsize, bufsize + 1, bufsize * 2): rawio = self.MockRawIO([b"x" * n]) bufio = self.tp(rawio, bufsize) self.assertEqual(bufio.read(n), b"x" * n) # Simple case: one raw read is enough to satisfy the request. self.assertEqual(rawio._extraneous_reads, 0, "failed for {}: {} != 0".format(n, rawio._extraneous_reads)) # A more complex case where two raw reads are needed to satisfy # the request. rawio = self.MockRawIO([b"x" * (n - 1), b"x"]) bufio = self.tp(rawio, bufsize) self.assertEqual(bufio.read(n), b"x" * n) self.assertEqual(rawio._extraneous_reads, 0, "failed for {}: {} != 0".format(n, rawio._extraneous_reads)) class CBufferedReaderTest(BufferedReaderTest, SizeofTest): tp = io.BufferedReader def test_constructor(self): BufferedReaderTest.test_constructor(self) # The allocation can succeed on 32-bit builds, e.g. with more # than 2GB RAM and a 64-bit kernel. if sys.maxsize > 0x7FFFFFFF: rawio = self.MockRawIO() bufio = self.tp(rawio) self.assertRaises((OverflowError, MemoryError, ValueError), bufio.__init__, rawio, sys.maxsize) def test_initialization(self): rawio = self.MockRawIO([b"abc"]) bufio = self.tp(rawio) self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0) self.assertRaises(ValueError, bufio.read) self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16) self.assertRaises(ValueError, bufio.read) self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1) self.assertRaises(ValueError, bufio.read) def test_misbehaved_io_read(self): rawio = self.MisbehavedRawIO((b"abc", b"d", b"efg")) bufio = self.tp(rawio) # _pyio.BufferedReader seems to implement reading different, so that # checking this is not so easy. self.assertRaises(IOError, bufio.read, 10) def test_garbage_collection(self): # C BufferedReader objects are collected. # The Python version has __del__, so it ends into gc.garbage instead rawio = self.FileIO(support.TESTFN, "w+b") f = self.tp(rawio) f.f = f wr = weakref.ref(f) del f support.gc_collect() self.assertTrue(wr() is None, wr) def test_args_error(self): # Issue #17275 with self.assertRaisesRegexp(TypeError, "BufferedReader"): self.tp(io.BytesIO(), 1024, 1024, 1024) class PyBufferedReaderTest(BufferedReaderTest): tp = pyio.BufferedReader class BufferedWriterTest(unittest.TestCase, CommonBufferedTests): write_mode = "wb" def test_constructor(self): rawio = self.MockRawIO() bufio = self.tp(rawio) bufio.__init__(rawio) bufio.__init__(rawio, buffer_size=1024) bufio.__init__(rawio, buffer_size=16) self.assertEqual(3, bufio.write(b"abc")) bufio.flush() self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0) self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16) self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1) bufio.__init__(rawio) self.assertEqual(3, bufio.write(b"ghi")) bufio.flush() self.assertEqual(b"".join(rawio._write_stack), b"abcghi") def test_uninitialized(self): bufio = self.tp.__new__(self.tp) del bufio bufio = self.tp.__new__(self.tp) self.assertRaisesRegexp((ValueError, AttributeError), 'uninitialized|has no attribute', bufio.write, b'') bufio.__init__(self.MockRawIO()) self.assertEqual(bufio.write(b''), 0) def test_detach_flush(self): raw = self.MockRawIO() buf = self.tp(raw) buf.write(b"howdy!") self.assertFalse(raw._write_stack) buf.detach() self.assertEqual(raw._write_stack, [b"howdy!"]) def test_write(self): # Write to the buffered IO but don't overflow the buffer. writer = self.MockRawIO() bufio = self.tp(writer, 8) bufio.write(b"abc") self.assertFalse(writer._write_stack) def test_write_overflow(self): writer = self.MockRawIO() bufio = self.tp(writer, 8) contents = b"abcdefghijklmnop" for n in range(0, len(contents), 3): bufio.write(contents[n:n+3]) flushed = b"".join(writer._write_stack) # At least (total - 8) bytes were implicitly flushed, perhaps more # depending on the implementation. self.assertTrue(flushed.startswith(contents[:-8]), flushed) def check_writes(self, intermediate_func): # Lots of writes, test the flushed output is as expected. contents = bytes(range(256)) * 1000 n = 0 writer = self.MockRawIO() bufio = self.tp(writer, 13) # Generator of write sizes: repeat each N 15 times then proceed to N+1 def gen_sizes(): for size in count(1): for i in range(15): yield size sizes = gen_sizes() while n < len(contents): size = min(next(sizes), len(contents) - n) self.assertEqual(bufio.write(contents[n:n+size]), size) intermediate_func(bufio) n += size bufio.flush() self.assertEqual(contents, b"".join(writer._write_stack)) def test_writes(self): self.check_writes(lambda bufio: None) def test_writes_and_flushes(self): self.check_writes(lambda bufio: bufio.flush()) def test_writes_and_seeks(self): def _seekabs(bufio): pos = bufio.tell() bufio.seek(pos + 1, 0) bufio.seek(pos - 1, 0) bufio.seek(pos, 0) self.check_writes(_seekabs) def _seekrel(bufio): pos = bufio.seek(0, 1) bufio.seek(+1, 1) bufio.seek(-1, 1) bufio.seek(pos, 0) self.check_writes(_seekrel) def test_writes_and_truncates(self): self.check_writes(lambda bufio: bufio.truncate(bufio.tell())) def test_write_non_blocking(self): raw = self.MockNonBlockWriterIO() bufio = self.tp(raw, 8) self.assertEqual(bufio.write(b"abcd"), 4) self.assertEqual(bufio.write(b"efghi"), 5) # 1 byte will be written, the rest will be buffered raw.block_on(b"k") self.assertEqual(bufio.write(b"jklmn"), 5) # 8 bytes will be written, 8 will be buffered and the rest will be lost raw.block_on(b"0") try: bufio.write(b"opqrwxyz0123456789") except self.BlockingIOError as e: written = e.characters_written else: self.fail("BlockingIOError should have been raised") self.assertEqual(written, 16) self.assertEqual(raw.pop_written(), b"abcdefghijklmnopqrwxyz") self.assertEqual(bufio.write(b"ABCDEFGHI"), 9) s = raw.pop_written() # Previously buffered bytes were flushed self.assertTrue(s.startswith(b"01234567A"), s) def test_write_and_rewind(self): raw = io.BytesIO() bufio = self.tp(raw, 4) self.assertEqual(bufio.write(b"abcdef"), 6) self.assertEqual(bufio.tell(), 6) bufio.seek(0, 0) self.assertEqual(bufio.write(b"XY"), 2) bufio.seek(6, 0) self.assertEqual(raw.getvalue(), b"XYcdef") self.assertEqual(bufio.write(b"123456"), 6) bufio.flush() self.assertEqual(raw.getvalue(), b"XYcdef123456") def test_flush(self): writer = self.MockRawIO() bufio = self.tp(writer, 8) bufio.write(b"abc") bufio.flush() self.assertEqual(b"abc", writer._write_stack[0]) def test_writelines(self): l = [b'ab', b'cd', b'ef'] writer = self.MockRawIO() bufio = self.tp(writer, 8) bufio.writelines(l) bufio.flush() self.assertEqual(b''.join(writer._write_stack), b'abcdef') def test_writelines_userlist(self): l = UserList([b'ab', b'cd', b'ef']) writer = self.MockRawIO() bufio = self.tp(writer, 8) bufio.writelines(l) bufio.flush() self.assertEqual(b''.join(writer._write_stack), b'abcdef') def test_writelines_error(self): writer = self.MockRawIO() bufio = self.tp(writer, 8) self.assertRaises(TypeError, bufio.writelines, [1, 2, 3]) self.assertRaises(TypeError, bufio.writelines, None) def test_destructor(self): writer = self.MockRawIO() bufio = self.tp(writer, 8) bufio.write(b"abc") del bufio support.gc_collect() self.assertEqual(b"abc", writer._write_stack[0]) def test_truncate(self): # Truncate implicitly flushes the buffer. with self.open(support.TESTFN, self.write_mode, buffering=0) as raw: bufio = self.tp(raw, 8) bufio.write(b"abcdef") self.assertEqual(bufio.truncate(3), 3) self.assertEqual(bufio.tell(), 6) with self.open(support.TESTFN, "rb", buffering=0) as f: self.assertEqual(f.read(), b"abc") @unittest.skipUnless(threading, 'Threading required for this test.') @support.requires_resource('cpu') def test_threads(self): try: # Write out many bytes from many threads and test they were # all flushed. N = 1000 contents = bytes(range(256)) * N sizes = cycle([1, 19]) n = 0 queue = deque() while n < len(contents): size = next(sizes) queue.append(contents[n:n+size]) n += size del contents # We use a real file object because it allows us to # exercise situations where the GIL is released before # writing the buffer to the raw streams. This is in addition # to concurrency issues due to switching threads in the middle # of Python code. with self.open(support.TESTFN, self.write_mode, buffering=0) as raw: bufio = self.tp(raw, 8) errors = [] def f(): try: while True: try: s = queue.popleft() except IndexError: return bufio.write(s) except Exception as e: errors.append(e) raise threads = [threading.Thread(target=f) for x in range(20)] with support.start_threads(threads): time.sleep(0.02) # yield self.assertFalse(errors, "the following exceptions were caught: %r" % errors) bufio.close() with self.open(support.TESTFN, "rb") as f: s = f.read() for i in range(256): self.assertEqual(s.count(bytes([i])), N) finally: support.unlink(support.TESTFN) def test_misbehaved_io(self): rawio = self.MisbehavedRawIO() bufio = self.tp(rawio, 5) self.assertRaises(IOError, bufio.seek, 0) self.assertRaises(IOError, bufio.tell) self.assertRaises(IOError, bufio.write, b"abcdef") def test_max_buffer_size_deprecation(self): with support.check_warnings(("max_buffer_size is deprecated", DeprecationWarning)): self.tp(self.MockRawIO(), 8, 12) def test_write_error_on_close(self): raw = self.MockRawIO() def bad_write(b): raise IOError() raw.write = bad_write b = self.tp(raw) b.write(b'spam') self.assertRaises(IOError, b.close) # exception not swallowed self.assertTrue(b.closed) class CBufferedWriterTest(BufferedWriterTest, SizeofTest): tp = io.BufferedWriter def test_constructor(self): BufferedWriterTest.test_constructor(self) # The allocation can succeed on 32-bit builds, e.g. with more # than 2GB RAM and a 64-bit kernel. if sys.maxsize > 0x7FFFFFFF: rawio = self.MockRawIO() bufio = self.tp(rawio) self.assertRaises((OverflowError, MemoryError, ValueError), bufio.__init__, rawio, sys.maxsize) def test_initialization(self): rawio = self.MockRawIO() bufio = self.tp(rawio) self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0) self.assertRaises(ValueError, bufio.write, b"def") self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16) self.assertRaises(ValueError, bufio.write, b"def") self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1) self.assertRaises(ValueError, bufio.write, b"def") def test_garbage_collection(self): # C BufferedWriter objects are collected, and collecting them flushes # all data to disk. # The Python version has __del__, so it ends into gc.garbage instead rawio = self.FileIO(support.TESTFN, "w+b") f = self.tp(rawio) f.write(b"123xxx") f.x = f wr = weakref.ref(f) del f support.gc_collect() self.assertTrue(wr() is None, wr) with self.open(support.TESTFN, "rb") as f: self.assertEqual(f.read(), b"123xxx") def test_args_error(self): # Issue #17275 with self.assertRaisesRegexp(TypeError, "BufferedWriter"): self.tp(io.BytesIO(), 1024, 1024, 1024) class PyBufferedWriterTest(BufferedWriterTest): tp = pyio.BufferedWriter class BufferedRWPairTest(unittest.TestCase): def test_constructor(self): pair = self.tp(self.MockRawIO(), self.MockRawIO()) self.assertFalse(pair.closed) def test_uninitialized(self): pair = self.tp.__new__(self.tp) del pair pair = self.tp.__new__(self.tp) self.assertRaisesRegexp((ValueError, AttributeError), 'uninitialized|has no attribute', pair.read, 0) self.assertRaisesRegexp((ValueError, AttributeError), 'uninitialized|has no attribute', pair.write, b'') pair.__init__(self.MockRawIO(), self.MockRawIO()) self.assertEqual(pair.read(0), b'') self.assertEqual(pair.write(b''), 0) def test_detach(self): pair = self.tp(self.MockRawIO(), self.MockRawIO()) self.assertRaises(self.UnsupportedOperation, pair.detach) def test_constructor_max_buffer_size_deprecation(self): with support.check_warnings(("max_buffer_size is deprecated", DeprecationWarning)): self.tp(self.MockRawIO(), self.MockRawIO(), 8, 12) def test_constructor_with_not_readable(self): class NotReadable(MockRawIO): def readable(self): return False self.assertRaises(IOError, self.tp, NotReadable(), self.MockRawIO()) def test_constructor_with_not_writeable(self): class NotWriteable(MockRawIO): def writable(self): return False self.assertRaises(IOError, self.tp, self.MockRawIO(), NotWriteable()) def test_read(self): pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO()) self.assertEqual(pair.read(3), b"abc") self.assertEqual(pair.read(1), b"d") self.assertEqual(pair.read(), b"ef") pair = self.tp(self.BytesIO(b"abc"), self.MockRawIO()) self.assertEqual(pair.read(None), b"abc") def test_readlines(self): pair = lambda: self.tp(self.BytesIO(b"abc\ndef\nh"), self.MockRawIO()) self.assertEqual(pair().readlines(), [b"abc\n", b"def\n", b"h"]) self.assertEqual(pair().readlines(), [b"abc\n", b"def\n", b"h"]) self.assertEqual(pair().readlines(5), [b"abc\n", b"def\n"]) def test_read1(self): # .read1() is delegated to the underlying reader object, so this test # can be shallow. pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO()) self.assertEqual(pair.read1(3), b"abc") def test_readinto(self): pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO()) data = bytearray(5) self.assertEqual(pair.readinto(data), 5) self.assertEqual(data, b"abcde") def test_write(self): w = self.MockRawIO() pair = self.tp(self.MockRawIO(), w) pair.write(b"abc") pair.flush() pair.write(b"def") pair.flush() self.assertEqual(w._write_stack, [b"abc", b"def"]) def test_peek(self): pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO()) self.assertTrue(pair.peek(3).startswith(b"abc")) self.assertEqual(pair.read(3), b"abc") def test_readable(self): pair = self.tp(self.MockRawIO(), self.MockRawIO()) self.assertTrue(pair.readable()) def test_writeable(self): pair = self.tp(self.MockRawIO(), self.MockRawIO()) self.assertTrue(pair.writable()) def test_seekable(self): # BufferedRWPairs are never seekable, even if their readers and writers # are. pair = self.tp(self.MockRawIO(), self.MockRawIO()) self.assertFalse(pair.seekable()) # .flush() is delegated to the underlying writer object and has been # tested in the test_write method. def test_close_and_closed(self): pair = self.tp(self.MockRawIO(), self.MockRawIO()) self.assertFalse(pair.closed) pair.close() self.assertTrue(pair.closed) def test_reader_close_error_on_close(self): def reader_close(): reader_non_existing reader = self.MockRawIO() reader.close = reader_close writer = self.MockRawIO() pair = self.tp(reader, writer) with self.assertRaises(NameError) as err: pair.close() self.assertIn('reader_non_existing', str(err.exception)) self.assertTrue(pair.closed) self.assertFalse(reader.closed) self.assertTrue(writer.closed) def test_writer_close_error_on_close(self): def writer_close(): writer_non_existing reader = self.MockRawIO() writer = self.MockRawIO() writer.close = writer_close pair = self.tp(reader, writer) with self.assertRaises(NameError) as err: pair.close() self.assertIn('writer_non_existing', str(err.exception)) self.assertFalse(pair.closed) self.assertTrue(reader.closed) self.assertFalse(writer.closed) def test_reader_writer_close_error_on_close(self): def reader_close(): reader_non_existing def writer_close(): writer_non_existing reader = self.MockRawIO() reader.close = reader_close writer = self.MockRawIO() writer.close = writer_close pair = self.tp(reader, writer) with self.assertRaises(NameError) as err: pair.close() self.assertIn('reader_non_existing', str(err.exception)) self.assertFalse(pair.closed) self.assertFalse(reader.closed) self.assertFalse(writer.closed) def test_isatty(self): class SelectableIsAtty(MockRawIO): def __init__(self, isatty): MockRawIO.__init__(self) self._isatty = isatty def isatty(self): return self._isatty pair = self.tp(SelectableIsAtty(False), SelectableIsAtty(False)) self.assertFalse(pair.isatty()) pair = self.tp(SelectableIsAtty(True), SelectableIsAtty(False)) self.assertTrue(pair.isatty()) pair = self.tp(SelectableIsAtty(False), SelectableIsAtty(True)) self.assertTrue(pair.isatty()) pair = self.tp(SelectableIsAtty(True), SelectableIsAtty(True)) self.assertTrue(pair.isatty()) def test_weakref_clearing(self): brw = self.tp(self.MockRawIO(), self.MockRawIO()) ref = weakref.ref(brw) brw = None ref = None # Shouldn't segfault. class CBufferedRWPairTest(BufferedRWPairTest): tp = io.BufferedRWPair class PyBufferedRWPairTest(BufferedRWPairTest): tp = pyio.BufferedRWPair class BufferedRandomTest(BufferedReaderTest, BufferedWriterTest): read_mode = "rb+" write_mode = "wb+" def test_constructor(self): BufferedReaderTest.test_constructor(self) BufferedWriterTest.test_constructor(self) def test_uninitialized(self): BufferedReaderTest.test_uninitialized(self) BufferedWriterTest.test_uninitialized(self) def test_read_and_write(self): raw = self.MockRawIO((b"asdf", b"ghjk")) rw = self.tp(raw, 8) self.assertEqual(b"as", rw.read(2)) rw.write(b"ddd") rw.write(b"eee") self.assertFalse(raw._write_stack) # Buffer writes self.assertEqual(b"ghjk", rw.read()) self.assertEqual(b"dddeee", raw._write_stack[0]) def test_seek_and_tell(self): raw = self.BytesIO(b"asdfghjkl") rw = self.tp(raw) self.assertEqual(b"as", rw.read(2)) self.assertEqual(2, rw.tell()) rw.seek(0, 0) self.assertEqual(b"asdf", rw.read(4)) rw.write(b"123f") rw.seek(0, 0) self.assertEqual(b"asdf123fl", rw.read()) self.assertEqual(9, rw.tell()) rw.seek(-4, 2) self.assertEqual(5, rw.tell()) rw.seek(2, 1) self.assertEqual(7, rw.tell()) self.assertEqual(b"fl", rw.read(11)) rw.flush() self.assertEqual(b"asdf123fl", raw.getvalue()) self.assertRaises(TypeError, rw.seek, 0.0) def check_flush_and_read(self, read_func): raw = self.BytesIO(b"abcdefghi") bufio = self.tp(raw) self.assertEqual(b"ab", read_func(bufio, 2)) bufio.write(b"12") self.assertEqual(b"ef", read_func(bufio, 2)) self.assertEqual(6, bufio.tell()) bufio.flush() self.assertEqual(6, bufio.tell()) self.assertEqual(b"ghi", read_func(bufio)) raw.seek(0, 0) raw.write(b"XYZ") # flush() resets the read buffer bufio.flush() bufio.seek(0, 0) self.assertEqual(b"XYZ", read_func(bufio, 3)) def test_flush_and_read(self): self.check_flush_and_read(lambda bufio, *args: bufio.read(*args)) def test_flush_and_readinto(self): def _readinto(bufio, n=-1): b = bytearray(n if n >= 0 else 9999) n = bufio.readinto(b) return bytes(b[:n]) self.check_flush_and_read(_readinto) def test_flush_and_peek(self): def _peek(bufio, n=-1): # This relies on the fact that the buffer can contain the whole # raw stream, otherwise peek() can return less. b = bufio.peek(n) if n != -1: b = b[:n] bufio.seek(len(b), 1) return b self.check_flush_and_read(_peek) def test_flush_and_write(self): raw = self.BytesIO(b"abcdefghi") bufio = self.tp(raw) bufio.write(b"123") bufio.flush() bufio.write(b"45") bufio.flush() bufio.seek(0, 0) self.assertEqual(b"12345fghi", raw.getvalue()) self.assertEqual(b"12345fghi", bufio.read()) def test_threads(self): BufferedReaderTest.test_threads(self) BufferedWriterTest.test_threads(self) def test_writes_and_peek(self): def _peek(bufio): bufio.peek(1) self.check_writes(_peek) def _peek(bufio): pos = bufio.tell() bufio.seek(-1, 1) bufio.peek(1) bufio.seek(pos, 0) self.check_writes(_peek) def test_writes_and_reads(self): def _read(bufio): bufio.seek(-1, 1) bufio.read(1) self.check_writes(_read) def test_writes_and_read1s(self): def _read1(bufio): bufio.seek(-1, 1) bufio.read1(1) self.check_writes(_read1) def test_writes_and_readintos(self): def _read(bufio): bufio.seek(-1, 1) bufio.readinto(bytearray(1)) self.check_writes(_read) def test_write_after_readahead(self): # Issue #6629: writing after the buffer was filled by readahead should # first rewind the raw stream. for overwrite_size in [1, 5]: raw = self.BytesIO(b"A" * 10) bufio = self.tp(raw, 4) # Trigger readahead self.assertEqual(bufio.read(1), b"A") self.assertEqual(bufio.tell(), 1) # Overwriting should rewind the raw stream if it needs so bufio.write(b"B" * overwrite_size) self.assertEqual(bufio.tell(), overwrite_size + 1) # If the write size was smaller than the buffer size, flush() and # check that rewind happens. bufio.flush() self.assertEqual(bufio.tell(), overwrite_size + 1) s = raw.getvalue() self.assertEqual(s, b"A" + b"B" * overwrite_size + b"A" * (9 - overwrite_size)) def test_write_rewind_write(self): # Various combinations of reading / writing / seeking backwards / writing again def mutate(bufio, pos1, pos2): assert pos2 >= pos1 # Fill the buffer bufio.seek(pos1) bufio.read(pos2 - pos1) bufio.write(b'\x02') # This writes earlier than the previous write, but still inside # the buffer. bufio.seek(pos1) bufio.write(b'\x01') b = b"\x80\x81\x82\x83\x84" for i in range(0, len(b)): for j in range(i, len(b)): raw = self.BytesIO(b) bufio = self.tp(raw, 100) mutate(bufio, i, j) bufio.flush() expected = bytearray(b) expected[j] = 2 expected[i] = 1 self.assertEqual(raw.getvalue(), expected, "failed result for i=%d, j=%d" % (i, j)) def test_truncate_after_read_or_write(self): raw = self.BytesIO(b"A" * 10) bufio = self.tp(raw, 100) self.assertEqual(bufio.read(2), b"AA") # the read buffer gets filled self.assertEqual(bufio.truncate(), 2) self.assertEqual(bufio.write(b"BB"), 2) # the write buffer increases self.assertEqual(bufio.truncate(), 4) def test_misbehaved_io(self): BufferedReaderTest.test_misbehaved_io(self) BufferedWriterTest.test_misbehaved_io(self) def test_interleaved_read_write(self): # Test for issue #12213 with self.BytesIO(b'abcdefgh') as raw: with self.tp(raw, 100) as f: f.write(b"1") self.assertEqual(f.read(1), b'b') f.write(b'2') self.assertEqual(f.read1(1), b'd') f.write(b'3') buf = bytearray(1) f.readinto(buf) self.assertEqual(buf, b'f') f.write(b'4') self.assertEqual(f.peek(1), b'h') f.flush() self.assertEqual(raw.getvalue(), b'1b2d3f4h') with self.BytesIO(b'abc') as raw: with self.tp(raw, 100) as f: self.assertEqual(f.read(1), b'a') f.write(b"2") self.assertEqual(f.read(1), b'c') f.flush() self.assertEqual(raw.getvalue(), b'a2c') def test_interleaved_readline_write(self): with self.BytesIO(b'ab\ncdef\ng\n') as raw: with self.tp(raw) as f: f.write(b'1') self.assertEqual(f.readline(), b'b\n') f.write(b'2') self.assertEqual(f.readline(), b'def\n') f.write(b'3') self.assertEqual(f.readline(), b'\n') f.flush() self.assertEqual(raw.getvalue(), b'1b\n2def\n3\n') class CBufferedRandomTest(CBufferedReaderTest, CBufferedWriterTest, BufferedRandomTest, SizeofTest): tp = io.BufferedRandom def test_constructor(self): BufferedRandomTest.test_constructor(self) # The allocation can succeed on 32-bit builds, e.g. with more # than 2GB RAM and a 64-bit kernel. if sys.maxsize > 0x7FFFFFFF: rawio = self.MockRawIO() bufio = self.tp(rawio) self.assertRaises((OverflowError, MemoryError, ValueError), bufio.__init__, rawio, sys.maxsize) def test_garbage_collection(self): CBufferedReaderTest.test_garbage_collection(self) CBufferedWriterTest.test_garbage_collection(self) def test_args_error(self): # Issue #17275 with self.assertRaisesRegexp(TypeError, "BufferedRandom"): self.tp(io.BytesIO(), 1024, 1024, 1024) class PyBufferedRandomTest(BufferedRandomTest): tp = pyio.BufferedRandom # To fully exercise seek/tell, the StatefulIncrementalDecoder has these # properties: # - A single output character can correspond to many bytes of input. # - The number of input bytes to complete the character can be # undetermined until the last input byte is received. # - The number of input bytes can vary depending on previous input. # - A single input byte can correspond to many characters of output. # - The number of output characters can be undetermined until the # last input byte is received. # - The number of output characters can vary depending on previous input. class StatefulIncrementalDecoder(codecs.IncrementalDecoder): """ For testing seek/tell behavior with a stateful, buffering decoder. Input is a sequence of words. Words may be fixed-length (length set by input) or variable-length (period-terminated). In variable-length mode, extra periods are ignored. Possible words are: - 'i' followed by a number sets the input length, I (maximum 99). When I is set to 0, words are space-terminated. - 'o' followed by a number sets the output length, O (maximum 99). - Any other word is converted into a word followed by a period on the output. The output word consists of the input word truncated or padded out with hyphens to make its length equal to O. If O is 0, the word is output verbatim without truncating or padding. I and O are initially set to 1. When I changes, any buffered input is re-scanned according to the new I. EOF also terminates the last word. """ def __init__(self, errors='strict'): codecs.IncrementalDecoder.__init__(self, errors) self.reset() def __repr__(self): return '<SID %x>' % id(self) def reset(self): self.i = 1 self.o = 1 self.buffer = bytearray() def getstate(self): i, o = self.i ^ 1, self.o ^ 1 # so that flags = 0 after reset() return bytes(self.buffer), i*100 + o def setstate(self, state): buffer, io = state self.buffer = bytearray(buffer) i, o = divmod(io, 100) self.i, self.o = i ^ 1, o ^ 1 def decode(self, input, final=False): output = '' for b in input: if self.i == 0: # variable-length, terminated with period if b == '.': if self.buffer: output += self.process_word() else: self.buffer.append(b) else: # fixed-length, terminate after self.i bytes self.buffer.append(b) if len(self.buffer) == self.i: output += self.process_word() if final and self.buffer: # EOF terminates the last word output += self.process_word() return output def process_word(self): output = '' if self.buffer[0] == ord('i'): self.i = min(99, int(self.buffer[1:] or 0)) # set input length elif self.buffer[0] == ord('o'): self.o = min(99, int(self.buffer[1:] or 0)) # set output length else: output = self.buffer.decode('ascii') if len(output) < self.o: output += '-'*self.o # pad out with hyphens if self.o: output = output[:self.o] # truncate to output length output += '.' self.buffer = bytearray() return output codecEnabled = False @classmethod def lookupTestDecoder(cls, name): if cls.codecEnabled and name == 'test_decoder': latin1 = codecs.lookup('latin-1') return codecs.CodecInfo( name='test_decoder', encode=latin1.encode, decode=None, incrementalencoder=None, streamreader=None, streamwriter=None, incrementaldecoder=cls) # Register the previous decoder for testing. # Disabled by default, tests will enable it. codecs.register(StatefulIncrementalDecoder.lookupTestDecoder) class StatefulIncrementalDecoderTest(unittest.TestCase): """ Make sure the StatefulIncrementalDecoder actually works. """ test_cases = [ # I=1, O=1 (fixed-length input == fixed-length output) (b'abcd', False, 'a.b.c.d.'), # I=0, O=0 (variable-length input, variable-length output) (b'oiabcd', True, 'abcd.'), # I=0, O=0 (should ignore extra periods) (b'oi...abcd...', True, 'abcd.'), # I=0, O=6 (variable-length input, fixed-length output) (b'i.o6.x.xyz.toolongtofit.', False, 'x-----.xyz---.toolon.'), # I=2, O=6 (fixed-length input < fixed-length output) (b'i.i2.o6xyz', True, 'xy----.z-----.'), # I=6, O=3 (fixed-length input > fixed-length output) (b'i.o3.i6.abcdefghijklmnop', True, 'abc.ghi.mno.'), # I=0, then 3; O=29, then 15 (with longer output) (b'i.o29.a.b.cde.o15.abcdefghijabcdefghij.i3.a.b.c.d.ei00k.l.m', True, 'a----------------------------.' + 'b----------------------------.' + 'cde--------------------------.' + 'abcdefghijabcde.' + 'a.b------------.' + '.c.------------.' + 'd.e------------.' + 'k--------------.' + 'l--------------.' + 'm--------------.') ] def test_decoder(self): # Try a few one-shot test cases. for input, eof, output in self.test_cases: d = StatefulIncrementalDecoder() self.assertEqual(d.decode(input, eof), output) # Also test an unfinished decode, followed by forcing EOF. d = StatefulIncrementalDecoder() self.assertEqual(d.decode(b'oiabcd'), '') self.assertEqual(d.decode(b'', 1), 'abcd.') class TextIOWrapperTest(unittest.TestCase): def setUp(self): self.testdata = b"AAA\r\nBBB\rCCC\r\nDDD\nEEE\r\n" self.normalized = b"AAA\nBBB\nCCC\nDDD\nEEE\n".decode("ascii") support.unlink(support.TESTFN) def tearDown(self): support.unlink(support.TESTFN) def test_constructor(self): r = self.BytesIO(b"\xc3\xa9\n\n") b = self.BufferedReader(r, 1000) t = self.TextIOWrapper(b) t.__init__(b, encoding="latin1", newline="\r\n") self.assertEqual(t.encoding, "latin1") self.assertEqual(t.line_buffering, False) t.__init__(b, encoding="utf8", line_buffering=True) self.assertEqual(t.encoding, "utf8") self.assertEqual(t.line_buffering, True) self.assertEqual("\xe9\n", t.readline()) self.assertRaises(TypeError, t.__init__, b, newline=42) self.assertRaises(ValueError, t.__init__, b, newline='xyzzy') def test_uninitialized(self): t = self.TextIOWrapper.__new__(self.TextIOWrapper) del t t = self.TextIOWrapper.__new__(self.TextIOWrapper) self.assertRaises(Exception, repr, t) self.assertRaisesRegexp((ValueError, AttributeError), 'uninitialized|has no attribute', t.read, 0) t.__init__(self.MockRawIO()) self.assertEqual(t.read(0), u'') def test_detach(self): r = self.BytesIO() b = self.BufferedWriter(r) t = self.TextIOWrapper(b) self.assertIs(t.detach(), b) t = self.TextIOWrapper(b, encoding="ascii") t.write("howdy") self.assertFalse(r.getvalue()) t.detach() self.assertEqual(r.getvalue(), b"howdy") self.assertRaises(ValueError, t.detach) # Operations independent of the detached stream should still work repr(t) self.assertEqual(t.encoding, "ascii") self.assertEqual(t.errors, "strict") self.assertFalse(t.line_buffering) def test_repr(self): raw = self.BytesIO("hello".encode("utf-8")) b = self.BufferedReader(raw) t = self.TextIOWrapper(b, encoding="utf-8") modname = self.TextIOWrapper.__module__ self.assertEqual(repr(t), "<%s.TextIOWrapper encoding='utf-8'>" % modname) raw.name = "dummy" self.assertEqual(repr(t), "<%s.TextIOWrapper name=u'dummy' encoding='utf-8'>" % modname) raw.name = b"dummy" self.assertEqual(repr(t), "<%s.TextIOWrapper name='dummy' encoding='utf-8'>" % modname) t.buffer.detach() repr(t) # Should not raise an exception def test_line_buffering(self): r = self.BytesIO() b = self.BufferedWriter(r, 1000) t = self.TextIOWrapper(b, newline="\n", line_buffering=True) t.write("X") self.assertEqual(r.getvalue(), b"") # No flush happened t.write("Y\nZ") self.assertEqual(r.getvalue(), b"XY\nZ") # All got flushed t.write("A\rB") self.assertEqual(r.getvalue(), b"XY\nZA\rB") def test_encoding(self): # Check the encoding attribute is always set, and valid b = self.BytesIO() t = self.TextIOWrapper(b, encoding="utf8") self.assertEqual(t.encoding, "utf8") t = self.TextIOWrapper(b) self.assertTrue(t.encoding is not None) codecs.lookup(t.encoding) def test_encoding_errors_reading(self): # (1) default b = self.BytesIO(b"abc\n\xff\n") t = self.TextIOWrapper(b, encoding="ascii") self.assertRaises(UnicodeError, t.read) # (2) explicit strict b = self.BytesIO(b"abc\n\xff\n") t = self.TextIOWrapper(b, encoding="ascii", errors="strict") self.assertRaises(UnicodeError, t.read) # (3) ignore b = self.BytesIO(b"abc\n\xff\n") t = self.TextIOWrapper(b, encoding="ascii", errors="ignore") self.assertEqual(t.read(), "abc\n\n") # (4) replace b = self.BytesIO(b"abc\n\xff\n") t = self.TextIOWrapper(b, encoding="ascii", errors="replace") self.assertEqual(t.read(), "abc\n\ufffd\n") def test_encoding_errors_writing(self): # (1) default b = self.BytesIO() t = self.TextIOWrapper(b, encoding="ascii") self.assertRaises(UnicodeError, t.write, "\xff") # (2) explicit strict b = self.BytesIO() t = self.TextIOWrapper(b, encoding="ascii", errors="strict") self.assertRaises(UnicodeError, t.write, "\xff") # (3) ignore b = self.BytesIO() t = self.TextIOWrapper(b, encoding="ascii", errors="ignore", newline="\n") t.write("abc\xffdef\n") t.flush() self.assertEqual(b.getvalue(), b"abcdef\n") # (4) replace b = self.BytesIO() t = self.TextIOWrapper(b, encoding="ascii", errors="replace", newline="\n") t.write("abc\xffdef\n") t.flush() self.assertEqual(b.getvalue(), b"abc?def\n") def test_newlines(self): input_lines = [ "unix\n", "windows\r\n", "os9\r", "last\n", "nonl" ] tests = [ [ None, [ 'unix\n', 'windows\n', 'os9\n', 'last\n', 'nonl' ] ], [ '', input_lines ], [ '\n', [ "unix\n", "windows\r\n", "os9\rlast\n", "nonl" ] ], [ '\r\n', [ "unix\nwindows\r\n", "os9\rlast\nnonl" ] ], [ '\r', [ "unix\nwindows\r", "\nos9\r", "last\nnonl" ] ], ] encodings = ( 'utf-8', 'latin-1', 'utf-16', 'utf-16-le', 'utf-16-be', 'utf-32', 'utf-32-le', 'utf-32-be', ) # Try a range of buffer sizes to test the case where \r is the last # character in TextIOWrapper._pending_line. for encoding in encodings: # XXX: str.encode() should return bytes data = bytes(''.join(input_lines).encode(encoding)) for do_reads in (False, True): for bufsize in range(1, 10): for newline, exp_lines in tests: bufio = self.BufferedReader(self.BytesIO(data), bufsize) textio = self.TextIOWrapper(bufio, newline=newline, encoding=encoding) if do_reads: got_lines = [] while True: c2 = textio.read(2) if c2 == '': break self.assertEqual(len(c2), 2) got_lines.append(c2 + textio.readline()) else: got_lines = list(textio) for got_line, exp_line in zip(got_lines, exp_lines): self.assertEqual(got_line, exp_line) self.assertEqual(len(got_lines), len(exp_lines)) def test_newlines_input(self): testdata = b"AAA\nBB\x00B\nCCC\rDDD\rEEE\r\nFFF\r\nGGG" normalized = testdata.replace(b"\r\n", b"\n").replace(b"\r", b"\n") for newline, expected in [ (None, normalized.decode("ascii").splitlines(True)), ("", testdata.decode("ascii").splitlines(True)), ("\n", ["AAA\n", "BB\x00B\n", "CCC\rDDD\rEEE\r\n", "FFF\r\n", "GGG"]), ("\r\n", ["AAA\nBB\x00B\nCCC\rDDD\rEEE\r\n", "FFF\r\n", "GGG"]), ("\r", ["AAA\nBB\x00B\nCCC\r", "DDD\r", "EEE\r", "\nFFF\r", "\nGGG"]), ]: buf = self.BytesIO(testdata) txt = self.TextIOWrapper(buf, encoding="ascii", newline=newline) self.assertEqual(txt.readlines(), expected) txt.seek(0) self.assertEqual(txt.read(), "".join(expected)) def test_newlines_output(self): testdict = { "": b"AAA\nBBB\nCCC\nX\rY\r\nZ", "\n": b"AAA\nBBB\nCCC\nX\rY\r\nZ", "\r": b"AAA\rBBB\rCCC\rX\rY\r\rZ", "\r\n": b"AAA\r\nBBB\r\nCCC\r\nX\rY\r\r\nZ", } tests = [(None, testdict[os.linesep])] + sorted(testdict.items()) for newline, expected in tests: buf = self.BytesIO() txt = self.TextIOWrapper(buf, encoding="ascii", newline=newline) txt.write("AAA\nB") txt.write("BB\nCCC\n") txt.write("X\rY\r\nZ") txt.flush() self.assertEqual(buf.closed, False) self.assertEqual(buf.getvalue(), expected) def test_destructor(self): l = [] base = self.BytesIO class MyBytesIO(base): def close(self): l.append(self.getvalue()) base.close(self) b = MyBytesIO() t = self.TextIOWrapper(b, encoding="ascii") t.write("abc") del t support.gc_collect() self.assertEqual([b"abc"], l) def test_override_destructor(self): record = [] class MyTextIO(self.TextIOWrapper): def __del__(self): record.append(1) try: f = super(MyTextIO, self).__del__ except AttributeError: pass else: f() def close(self): record.append(2) super(MyTextIO, self).close() def flush(self): record.append(3) super(MyTextIO, self).flush() b = self.BytesIO() t = MyTextIO(b, encoding="ascii") del t support.gc_collect() self.assertEqual(record, [1, 2, 3]) def test_error_through_destructor(self): # Test that the exception state is not modified by a destructor, # even if close() fails. rawio = self.CloseFailureIO() def f(): self.TextIOWrapper(rawio).xyzzy with support.captured_output("stderr") as s: self.assertRaises(AttributeError, f) s = s.getvalue().strip() if s: # The destructor *may* have printed an unraisable error, check it self.assertEqual(len(s.splitlines()), 1) self.assertTrue(s.startswith("Exception IOError: "), s) self.assertTrue(s.endswith(" ignored"), s) # Systematic tests of the text I/O API def test_basic_io(self): for chunksize in (1, 2, 3, 4, 5, 15, 16, 17, 31, 32, 33, 63, 64, 65): for enc in "ascii", "latin1", "utf8" :# , "utf-16-be", "utf-16-le": f = self.open(support.TESTFN, "w+", encoding=enc) f._CHUNK_SIZE = chunksize self.assertEqual(f.write("abc"), 3) f.close() f = self.open(support.TESTFN, "r+", encoding=enc) f._CHUNK_SIZE = chunksize self.assertEqual(f.tell(), 0) self.assertEqual(f.read(), "abc") cookie = f.tell() self.assertEqual(f.seek(0), 0) self.assertEqual(f.read(None), "abc") f.seek(0) self.assertEqual(f.read(2), "ab") self.assertEqual(f.read(1), "c") self.assertEqual(f.read(1), "") self.assertEqual(f.read(), "") self.assertEqual(f.tell(), cookie) self.assertEqual(f.seek(0), 0) self.assertEqual(f.seek(0, 2), cookie) self.assertEqual(f.write("def"), 3) self.assertEqual(f.seek(cookie), cookie) self.assertEqual(f.read(), "def") if enc.startswith("utf"): self.multi_line_test(f, enc) f.close() def multi_line_test(self, f, enc): f.seek(0) f.truncate() sample = "s\xff\u0fff\uffff" wlines = [] for size in (0, 1, 2, 3, 4, 5, 30, 31, 32, 33, 62, 63, 64, 65, 1000): chars = [] for i in range(size): chars.append(sample[i % len(sample)]) line = "".join(chars) + "\n" wlines.append((f.tell(), line)) f.write(line) f.seek(0) rlines = [] while True: pos = f.tell() line = f.readline() if not line: break rlines.append((pos, line)) self.assertEqual(rlines, wlines) def test_telling(self): f = self.open(support.TESTFN, "w+", encoding="utf8") p0 = f.tell() f.write("\xff\n") p1 = f.tell() f.write("\xff\n") p2 = f.tell() f.seek(0) self.assertEqual(f.tell(), p0) self.assertEqual(f.readline(), "\xff\n") self.assertEqual(f.tell(), p1) self.assertEqual(f.readline(), "\xff\n") self.assertEqual(f.tell(), p2) f.seek(0) for line in f: self.assertEqual(line, "\xff\n") self.assertRaises(IOError, f.tell) self.assertEqual(f.tell(), p2) f.close() def test_seeking(self): chunk_size = _default_chunk_size() prefix_size = chunk_size - 2 u_prefix = "a" * prefix_size prefix = bytes(u_prefix.encode("utf-8")) self.assertEqual(len(u_prefix), len(prefix)) u_suffix = "\u8888\n" suffix = bytes(u_suffix.encode("utf-8")) line = prefix + suffix f = self.open(support.TESTFN, "wb") f.write(line*2) f.close() f = self.open(support.TESTFN, "r", encoding="utf-8") s = f.read(prefix_size) self.assertEqual(s, prefix.decode("ascii")) self.assertEqual(f.tell(), prefix_size) self.assertEqual(f.readline(), u_suffix) def test_seeking_too(self): # Regression test for a specific bug data = b'\xe0\xbf\xbf\n' f = self.open(support.TESTFN, "wb") f.write(data) f.close() f = self.open(support.TESTFN, "r", encoding="utf-8") f._CHUNK_SIZE # Just test that it exists f._CHUNK_SIZE = 2 f.readline() f.tell() def test_seek_and_tell(self): #Test seek/tell using the StatefulIncrementalDecoder. # Make test faster by doing smaller seeks CHUNK_SIZE = 128 def test_seek_and_tell_with_data(data, min_pos=0): """Tell/seek to various points within a data stream and ensure that the decoded data returned by read() is consistent.""" f = self.open(support.TESTFN, 'wb') f.write(data) f.close() f = self.open(support.TESTFN, encoding='test_decoder') f._CHUNK_SIZE = CHUNK_SIZE decoded = f.read() f.close() for i in range(min_pos, len(decoded) + 1): # seek positions for j in [1, 5, len(decoded) - i]: # read lengths f = self.open(support.TESTFN, encoding='test_decoder') self.assertEqual(f.read(i), decoded[:i]) cookie = f.tell() self.assertEqual(f.read(j), decoded[i:i + j]) f.seek(cookie) self.assertEqual(f.read(), decoded[i:]) f.close() # Enable the test decoder. StatefulIncrementalDecoder.codecEnabled = 1 # Run the tests. try: # Try each test case. for input, _, _ in StatefulIncrementalDecoderTest.test_cases: test_seek_and_tell_with_data(input) # Position each test case so that it crosses a chunk boundary. for input, _, _ in StatefulIncrementalDecoderTest.test_cases: offset = CHUNK_SIZE - len(input)//2 prefix = b'.'*offset # Don't bother seeking into the prefix (takes too long). min_pos = offset*2 test_seek_and_tell_with_data(prefix + input, min_pos) # Ensure our test decoder won't interfere with subsequent tests. finally: StatefulIncrementalDecoder.codecEnabled = 0 def test_encoded_writes(self): data = "1234567890" tests = ("utf-16", "utf-16-le", "utf-16-be", "utf-32", "utf-32-le", "utf-32-be") for encoding in tests: buf = self.BytesIO() f = self.TextIOWrapper(buf, encoding=encoding) # Check if the BOM is written only once (see issue1753). f.write(data) f.write(data) f.seek(0) self.assertEqual(f.read(), data * 2) f.seek(0) self.assertEqual(f.read(), data * 2) self.assertEqual(buf.getvalue(), (data * 2).encode(encoding)) def test_unreadable(self): class UnReadable(self.BytesIO): def readable(self): return False txt = self.TextIOWrapper(UnReadable()) self.assertRaises(IOError, txt.read) def test_read_one_by_one(self): txt = self.TextIOWrapper(self.BytesIO(b"AA\r\nBB")) reads = "" while True: c = txt.read(1) if not c: break reads += c self.assertEqual(reads, "AA\nBB") def test_readlines(self): txt = self.TextIOWrapper(self.BytesIO(b"AA\nBB\nCC")) self.assertEqual(txt.readlines(), ["AA\n", "BB\n", "CC"]) txt.seek(0) self.assertEqual(txt.readlines(None), ["AA\n", "BB\n", "CC"]) txt.seek(0) self.assertEqual(txt.readlines(5), ["AA\n", "BB\n"]) # read in amounts equal to TextIOWrapper._CHUNK_SIZE which is 128. def test_read_by_chunk(self): # make sure "\r\n" straddles 128 char boundary. txt = self.TextIOWrapper(self.BytesIO(b"A" * 127 + b"\r\nB")) reads = "" while True: c = txt.read(128) if not c: break reads += c self.assertEqual(reads, "A"*127+"\nB") def test_writelines(self): l = ['ab', 'cd', 'ef'] buf = self.BytesIO() txt = self.TextIOWrapper(buf) txt.writelines(l) txt.flush() self.assertEqual(buf.getvalue(), b'abcdef') def test_writelines_userlist(self): l = UserList(['ab', 'cd', 'ef']) buf = self.BytesIO() txt = self.TextIOWrapper(buf) txt.writelines(l) txt.flush() self.assertEqual(buf.getvalue(), b'abcdef') def test_writelines_error(self): txt = self.TextIOWrapper(self.BytesIO()) self.assertRaises(TypeError, txt.writelines, [1, 2, 3]) self.assertRaises(TypeError, txt.writelines, None) self.assertRaises(TypeError, txt.writelines, b'abc') def test_issue1395_1(self): txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") # read one char at a time reads = "" while True: c = txt.read(1) if not c: break reads += c self.assertEqual(reads, self.normalized) def test_issue1395_2(self): txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") txt._CHUNK_SIZE = 4 reads = "" while True: c = txt.read(4) if not c: break reads += c self.assertEqual(reads, self.normalized) def test_issue1395_3(self): txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") txt._CHUNK_SIZE = 4 reads = txt.read(4) reads += txt.read(4) reads += txt.readline() reads += txt.readline() reads += txt.readline() self.assertEqual(reads, self.normalized) def test_issue1395_4(self): txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") txt._CHUNK_SIZE = 4 reads = txt.read(4) reads += txt.read() self.assertEqual(reads, self.normalized) def test_issue1395_5(self): txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") txt._CHUNK_SIZE = 4 reads = txt.read(4) pos = txt.tell() txt.seek(0) txt.seek(pos) self.assertEqual(txt.read(4), "BBB\n") def test_issue2282(self): buffer = self.BytesIO(self.testdata) txt = self.TextIOWrapper(buffer, encoding="ascii") self.assertEqual(buffer.seekable(), txt.seekable()) def test_append_bom(self): # The BOM is not written again when appending to a non-empty file filename = support.TESTFN for charset in ('utf-8-sig', 'utf-16', 'utf-32'): with self.open(filename, 'w', encoding=charset) as f: f.write('aaa') pos = f.tell() with self.open(filename, 'rb') as f: self.assertEqual(f.read(), 'aaa'.encode(charset)) with self.open(filename, 'a', encoding=charset) as f: f.write('xxx') with self.open(filename, 'rb') as f: self.assertEqual(f.read(), 'aaaxxx'.encode(charset)) def test_seek_bom(self): # Same test, but when seeking manually filename = support.TESTFN for charset in ('utf-8-sig', 'utf-16', 'utf-32'): with self.open(filename, 'w', encoding=charset) as f: f.write('aaa') pos = f.tell() with self.open(filename, 'r+', encoding=charset) as f: f.seek(pos) f.write('zzz') f.seek(0) f.write('bbb') with self.open(filename, 'rb') as f: self.assertEqual(f.read(), 'bbbzzz'.encode(charset)) def test_errors_property(self): with self.open(support.TESTFN, "w") as f: self.assertEqual(f.errors, "strict") with self.open(support.TESTFN, "w", errors="replace") as f: self.assertEqual(f.errors, "replace") @unittest.skipUnless(threading, 'Threading required for this test.') def test_threads_write(self): # Issue6750: concurrent writes could duplicate data event = threading.Event() with self.open(support.TESTFN, "w", buffering=1) as f: def run(n): text = "Thread%03d\n" % n event.wait() f.write(text) threads = [threading.Thread(target=run, args=(x,)) for x in range(20)] with support.start_threads(threads, event.set): time.sleep(0.02) with self.open(support.TESTFN) as f: content = f.read() for n in range(20): self.assertEqual(content.count("Thread%03d\n" % n), 1) def test_flush_error_on_close(self): # Test that text file is closed despite failed flush # and that flush() is called before file closed. txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") closed = [] def bad_flush(): closed[:] = [txt.closed, txt.buffer.closed] raise IOError() txt.flush = bad_flush self.assertRaises(IOError, txt.close) # exception not swallowed self.assertTrue(txt.closed) self.assertTrue(txt.buffer.closed) self.assertTrue(closed) # flush() called self.assertFalse(closed[0]) # flush() called before file closed self.assertFalse(closed[1]) txt.flush = lambda: None # break reference loop def test_multi_close(self): txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") txt.close() txt.close() txt.close() self.assertRaises(ValueError, txt.flush) def test_readonly_attributes(self): txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") buf = self.BytesIO(self.testdata) with self.assertRaises((AttributeError, TypeError)): txt.buffer = buf def test_read_nonbytes(self): # Issue #17106 # Crash when underlying read() returns non-bytes class NonbytesStream(self.StringIO): read1 = self.StringIO.read class NonbytesStream(self.StringIO): read1 = self.StringIO.read t = self.TextIOWrapper(NonbytesStream('a')) with self.maybeRaises(TypeError): t.read(1) t = self.TextIOWrapper(NonbytesStream('a')) with self.maybeRaises(TypeError): t.readline() t = self.TextIOWrapper(NonbytesStream('a')) self.assertEqual(t.read(), u'a') def test_illegal_decoder(self): # Issue #17106 # Crash when decoder returns non-string t = self.TextIOWrapper(self.BytesIO(b'aaaaaa'), newline='\n', encoding='quopri_codec') with self.maybeRaises(TypeError): t.read(1) t = self.TextIOWrapper(self.BytesIO(b'aaaaaa'), newline='\n', encoding='quopri_codec') with self.maybeRaises(TypeError): t.readline() t = self.TextIOWrapper(self.BytesIO(b'aaaaaa'), newline='\n', encoding='quopri_codec') with self.maybeRaises(TypeError): t.read() class CTextIOWrapperTest(TextIOWrapperTest): def test_initialization(self): r = self.BytesIO(b"\xc3\xa9\n\n") b = self.BufferedReader(r, 1000) t = self.TextIOWrapper(b) self.assertRaises(TypeError, t.__init__, b, newline=42) self.assertRaises(ValueError, t.read) self.assertRaises(ValueError, t.__init__, b, newline='xyzzy') self.assertRaises(ValueError, t.read) t = self.TextIOWrapper.__new__(self.TextIOWrapper) self.assertRaises(Exception, repr, t) def test_garbage_collection(self): # C TextIOWrapper objects are collected, and collecting them flushes # all data to disk. # The Python version has __del__, so it ends in gc.garbage instead. rawio = io.FileIO(support.TESTFN, "wb") b = self.BufferedWriter(rawio) t = self.TextIOWrapper(b, encoding="ascii") t.write("456def") t.x = t wr = weakref.ref(t) del t support.gc_collect() self.assertTrue(wr() is None, wr) with self.open(support.TESTFN, "rb") as f: self.assertEqual(f.read(), b"456def") def test_rwpair_cleared_before_textio(self): # Issue 13070: TextIOWrapper's finalization would crash when called # after the reference to the underlying BufferedRWPair's writer got # cleared by the GC. for i in range(1000): b1 = self.BufferedRWPair(self.MockRawIO(), self.MockRawIO()) t1 = self.TextIOWrapper(b1, encoding="ascii") b2 = self.BufferedRWPair(self.MockRawIO(), self.MockRawIO()) t2 = self.TextIOWrapper(b2, encoding="ascii") # circular references t1.buddy = t2 t2.buddy = t1 support.gc_collect() maybeRaises = unittest.TestCase.assertRaises class PyTextIOWrapperTest(TextIOWrapperTest): @contextlib.contextmanager def maybeRaises(self, *args, **kwds): yield class IncrementalNewlineDecoderTest(unittest.TestCase): def check_newline_decoding_utf8(self, decoder): # UTF-8 specific tests for a newline decoder def _check_decode(b, s, **kwargs): # We exercise getstate() / setstate() as well as decode() state = decoder.getstate() self.assertEqual(decoder.decode(b, **kwargs), s) decoder.setstate(state) self.assertEqual(decoder.decode(b, **kwargs), s) _check_decode(b'\xe8\xa2\x88', "\u8888") _check_decode(b'\xe8', "") _check_decode(b'\xa2', "") _check_decode(b'\x88', "\u8888") _check_decode(b'\xe8', "") _check_decode(b'\xa2', "") _check_decode(b'\x88', "\u8888") _check_decode(b'\xe8', "") self.assertRaises(UnicodeDecodeError, decoder.decode, b'', final=True) decoder.reset() _check_decode(b'\n', "\n") _check_decode(b'\r', "") _check_decode(b'', "\n", final=True) _check_decode(b'\r', "\n", final=True) _check_decode(b'\r', "") _check_decode(b'a', "\na") _check_decode(b'\r\r\n', "\n\n") _check_decode(b'\r', "") _check_decode(b'\r', "\n") _check_decode(b'\na', "\na") _check_decode(b'\xe8\xa2\x88\r\n', "\u8888\n") _check_decode(b'\xe8\xa2\x88', "\u8888") _check_decode(b'\n', "\n") _check_decode(b'\xe8\xa2\x88\r', "\u8888") _check_decode(b'\n', "\n") def check_newline_decoding(self, decoder, encoding): result = [] if encoding is not None: encoder = codecs.getincrementalencoder(encoding)() def _decode_bytewise(s): # Decode one byte at a time for b in encoder.encode(s): result.append(decoder.decode(b)) else: encoder = None def _decode_bytewise(s): # Decode one char at a time for c in s: result.append(decoder.decode(c)) self.assertEqual(decoder.newlines, None) _decode_bytewise("abc\n\r") self.assertEqual(decoder.newlines, '\n') _decode_bytewise("\nabc") self.assertEqual(decoder.newlines, ('\n', '\r\n')) _decode_bytewise("abc\r") self.assertEqual(decoder.newlines, ('\n', '\r\n')) _decode_bytewise("abc") self.assertEqual(decoder.newlines, ('\r', '\n', '\r\n')) _decode_bytewise("abc\r") self.assertEqual("".join(result), "abc\n\nabcabc\nabcabc") decoder.reset() input = "abc" if encoder is not None: encoder.reset() input = encoder.encode(input) self.assertEqual(decoder.decode(input), "abc") self.assertEqual(decoder.newlines, None) def test_newline_decoder(self): encodings = ( # None meaning the IncrementalNewlineDecoder takes unicode input # rather than bytes input None, 'utf-8', 'latin-1', 'utf-16', 'utf-16-le', 'utf-16-be', 'utf-32', 'utf-32-le', 'utf-32-be', ) for enc in encodings: decoder = enc and codecs.getincrementaldecoder(enc)() decoder = self.IncrementalNewlineDecoder(decoder, translate=True) self.check_newline_decoding(decoder, enc) decoder = codecs.getincrementaldecoder("utf-8")() decoder = self.IncrementalNewlineDecoder(decoder, translate=True) self.check_newline_decoding_utf8(decoder) def test_newline_bytes(self): # Issue 5433: Excessive optimization in IncrementalNewlineDecoder def _check(dec): self.assertEqual(dec.newlines, None) self.assertEqual(dec.decode("\u0D00"), "\u0D00") self.assertEqual(dec.newlines, None) self.assertEqual(dec.decode("\u0A00"), "\u0A00") self.assertEqual(dec.newlines, None) dec = self.IncrementalNewlineDecoder(None, translate=False) _check(dec) dec = self.IncrementalNewlineDecoder(None, translate=True) _check(dec) class CIncrementalNewlineDecoderTest(IncrementalNewlineDecoderTest): pass class PyIncrementalNewlineDecoderTest(IncrementalNewlineDecoderTest): pass # XXX Tests for open() class MiscIOTest(unittest.TestCase): def tearDown(self): support.unlink(support.TESTFN) def test___all__(self): for name in self.io.__all__: obj = getattr(self.io, name, None) self.assertTrue(obj is not None, name) if name == "open": continue elif "error" in name.lower() or name == "UnsupportedOperation": self.assertTrue(issubclass(obj, Exception), name) elif not name.startswith("SEEK_"): self.assertTrue(issubclass(obj, self.IOBase)) def test_attributes(self): f = self.open(support.TESTFN, "wb", buffering=0) self.assertEqual(f.mode, "wb") f.close() f = self.open(support.TESTFN, "U") self.assertEqual(f.name, support.TESTFN) self.assertEqual(f.buffer.name, support.TESTFN) self.assertEqual(f.buffer.raw.name, support.TESTFN) self.assertEqual(f.mode, "U") self.assertEqual(f.buffer.mode, "rb") self.assertEqual(f.buffer.raw.mode, "rb") f.close() f = self.open(support.TESTFN, "w+") self.assertEqual(f.mode, "w+") self.assertEqual(f.buffer.mode, "rb+") # Does it really matter? self.assertEqual(f.buffer.raw.mode, "rb+") g = self.open(f.fileno(), "wb", closefd=False) self.assertEqual(g.mode, "wb") self.assertEqual(g.raw.mode, "wb") self.assertEqual(g.name, f.fileno()) self.assertEqual(g.raw.name, f.fileno()) f.close() g.close() def test_io_after_close(self): for kwargs in [ {"mode": "w"}, {"mode": "wb"}, {"mode": "w", "buffering": 1}, {"mode": "w", "buffering": 2}, {"mode": "wb", "buffering": 0}, {"mode": "r"}, {"mode": "rb"}, {"mode": "r", "buffering": 1}, {"mode": "r", "buffering": 2}, {"mode": "rb", "buffering": 0}, {"mode": "w+"}, {"mode": "w+b"}, {"mode": "w+", "buffering": 1}, {"mode": "w+", "buffering": 2}, {"mode": "w+b", "buffering": 0}, ]: f = self.open(support.TESTFN, **kwargs) f.close() self.assertRaises(ValueError, f.flush) self.assertRaises(ValueError, f.fileno) self.assertRaises(ValueError, f.isatty) self.assertRaises(ValueError, f.__iter__) if hasattr(f, "peek"): self.assertRaises(ValueError, f.peek, 1) self.assertRaises(ValueError, f.read) if hasattr(f, "read1"): self.assertRaises(ValueError, f.read1, 1024) if hasattr(f, "readall"): self.assertRaises(ValueError, f.readall) if hasattr(f, "readinto"): self.assertRaises(ValueError, f.readinto, bytearray(1024)) self.assertRaises(ValueError, f.readline) self.assertRaises(ValueError, f.readlines) self.assertRaises(ValueError, f.seek, 0) self.assertRaises(ValueError, f.tell) self.assertRaises(ValueError, f.truncate) self.assertRaises(ValueError, f.write, b"" if "b" in kwargs['mode'] else "") self.assertRaises(ValueError, f.writelines, []) self.assertRaises(ValueError, next, f) def test_blockingioerror(self): # Various BlockingIOError issues self.assertRaises(TypeError, self.BlockingIOError) self.assertRaises(TypeError, self.BlockingIOError, 1) self.assertRaises(TypeError, self.BlockingIOError, 1, 2, 3, 4) self.assertRaises(TypeError, self.BlockingIOError, 1, "", None) b = self.BlockingIOError(1, "") self.assertEqual(b.characters_written, 0) class C(unicode): pass c = C("") b = self.BlockingIOError(1, c) c.b = b b.c = c wr = weakref.ref(c) del c, b support.gc_collect() self.assertTrue(wr() is None, wr) def test_abcs(self): # Test the visible base classes are ABCs. self.assertIsInstance(self.IOBase, abc.ABCMeta) self.assertIsInstance(self.RawIOBase, abc.ABCMeta) self.assertIsInstance(self.BufferedIOBase, abc.ABCMeta) self.assertIsInstance(self.TextIOBase, abc.ABCMeta) def _check_abc_inheritance(self, abcmodule): with self.open(support.TESTFN, "wb", buffering=0) as f: self.assertIsInstance(f, abcmodule.IOBase) self.assertIsInstance(f, abcmodule.RawIOBase) self.assertNotIsInstance(f, abcmodule.BufferedIOBase) self.assertNotIsInstance(f, abcmodule.TextIOBase) with self.open(support.TESTFN, "wb") as f: self.assertIsInstance(f, abcmodule.IOBase) self.assertNotIsInstance(f, abcmodule.RawIOBase) self.assertIsInstance(f, abcmodule.BufferedIOBase) self.assertNotIsInstance(f, abcmodule.TextIOBase) with self.open(support.TESTFN, "w") as f: self.assertIsInstance(f, abcmodule.IOBase) self.assertNotIsInstance(f, abcmodule.RawIOBase) self.assertNotIsInstance(f, abcmodule.BufferedIOBase) self.assertIsInstance(f, abcmodule.TextIOBase) def test_abc_inheritance(self): # Test implementations inherit from their respective ABCs self._check_abc_inheritance(self) def test_abc_inheritance_official(self): # Test implementations inherit from the official ABCs of the # baseline "io" module. self._check_abc_inheritance(io) @unittest.skipUnless(fcntl, 'fcntl required for this test') def test_nonblock_pipe_write_bigbuf(self): self._test_nonblock_pipe_write(16*1024) @unittest.skipUnless(fcntl, 'fcntl required for this test') def test_nonblock_pipe_write_smallbuf(self): self._test_nonblock_pipe_write(1024) def _set_non_blocking(self, fd): flags = fcntl.fcntl(fd, fcntl.F_GETFL) self.assertNotEqual(flags, -1) res = fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) self.assertEqual(res, 0) def _test_nonblock_pipe_write(self, bufsize): sent = [] received = [] r, w = os.pipe() self._set_non_blocking(r) self._set_non_blocking(w) # To exercise all code paths in the C implementation we need # to play with buffer sizes. For instance, if we choose a # buffer size less than or equal to _PIPE_BUF (4096 on Linux) # then we will never get a partial write of the buffer. rf = self.open(r, mode='rb', closefd=True, buffering=bufsize) wf = self.open(w, mode='wb', closefd=True, buffering=bufsize) with rf, wf: for N in 9999, 73, 7574: try: i = 0 while True: msg = bytes([i % 26 + 97]) * N sent.append(msg) wf.write(msg) i += 1 except self.BlockingIOError as e: self.assertEqual(e.args[0], errno.EAGAIN) sent[-1] = sent[-1][:e.characters_written] received.append(rf.read()) msg = b'BLOCKED' wf.write(msg) sent.append(msg) while True: try: wf.flush() break except self.BlockingIOError as e: self.assertEqual(e.args[0], errno.EAGAIN) self.assertEqual(e.characters_written, 0) received.append(rf.read()) received += iter(rf.read, None) sent, received = b''.join(sent), b''.join(received) self.assertTrue(sent == received) self.assertTrue(wf.closed) self.assertTrue(rf.closed) class CMiscIOTest(MiscIOTest): io = io class PyMiscIOTest(MiscIOTest): io = pyio @unittest.skipIf(os.name == 'nt', 'POSIX signals required for this test.') class SignalsTest(unittest.TestCase): def setUp(self): self.oldalrm = signal.signal(signal.SIGALRM, self.alarm_interrupt) def tearDown(self): signal.signal(signal.SIGALRM, self.oldalrm) def alarm_interrupt(self, sig, frame): 1 // 0 @unittest.skipUnless(threading, 'Threading required for this test.') @unittest.skipIf(sys.platform in ('freebsd5', 'freebsd6', 'freebsd7'), 'issue #12429: skip test on FreeBSD <= 7') def check_interrupted_write(self, item, bytes, **fdopen_kwargs): """Check that a partial write, when it gets interrupted, properly invokes the signal handler, and bubbles up the exception raised in the latter.""" read_results = [] def _read(): s = os.read(r, 1) read_results.append(s) t = threading.Thread(target=_read) t.daemon = True r, w = os.pipe() try: wio = self.io.open(w, **fdopen_kwargs) t.start() signal.alarm(1) # Fill the pipe enough that the write will be blocking. # It will be interrupted by the timer armed above. Since the # other thread has read one byte, the low-level write will # return with a successful (partial) result rather than an EINTR. # The buffered IO layer must check for pending signal # handlers, which in this case will invoke alarm_interrupt(). try: with self.assertRaises(ZeroDivisionError): wio.write(item * (support.PIPE_MAX_SIZE // len(item) + 1)) finally: t.join() # We got one byte, get another one and check that it isn't a # repeat of the first one. read_results.append(os.read(r, 1)) self.assertEqual(read_results, [bytes[0:1], bytes[1:2]]) finally: os.close(w) os.close(r) # This is deliberate. If we didn't close the file descriptor # before closing wio, wio would try to flush its internal # buffer, and block again. try: wio.close() except IOError as e: if e.errno != errno.EBADF: raise def test_interrupted_write_unbuffered(self): self.check_interrupted_write(b"xy", b"xy", mode="wb", buffering=0) def test_interrupted_write_buffered(self): self.check_interrupted_write(b"xy", b"xy", mode="wb") def test_interrupted_write_text(self): self.check_interrupted_write("xy", b"xy", mode="w", encoding="ascii") def check_reentrant_write(self, data, **fdopen_kwargs): def on_alarm(*args): # Will be called reentrantly from the same thread wio.write(data) 1//0 signal.signal(signal.SIGALRM, on_alarm) r, w = os.pipe() wio = self.io.open(w, **fdopen_kwargs) try: signal.alarm(1) # Either the reentrant call to wio.write() fails with RuntimeError, # or the signal handler raises ZeroDivisionError. with self.assertRaises((ZeroDivisionError, RuntimeError)) as cm: while 1: for i in range(100): wio.write(data) wio.flush() # Make sure the buffer doesn't fill up and block further writes os.read(r, len(data) * 100) exc = cm.exception if isinstance(exc, RuntimeError): self.assertTrue(str(exc).startswith("reentrant call"), str(exc)) finally: wio.close() os.close(r) def test_reentrant_write_buffered(self): self.check_reentrant_write(b"xy", mode="wb") def test_reentrant_write_text(self): self.check_reentrant_write("xy", mode="w", encoding="ascii") def check_interrupted_read_retry(self, decode, **fdopen_kwargs): """Check that a buffered read, when it gets interrupted (either returning a partial result or EINTR), properly invokes the signal handler and retries if the latter returned successfully.""" r, w = os.pipe() fdopen_kwargs["closefd"] = False def alarm_handler(sig, frame): os.write(w, b"bar") signal.signal(signal.SIGALRM, alarm_handler) try: rio = self.io.open(r, **fdopen_kwargs) os.write(w, b"foo") signal.alarm(1) # Expected behaviour: # - first raw read() returns partial b"foo" # - second raw read() returns EINTR # - third raw read() returns b"bar" self.assertEqual(decode(rio.read(6)), "foobar") finally: rio.close() os.close(w) os.close(r) def test_interrupterd_read_retry_buffered(self): self.check_interrupted_read_retry(lambda x: x.decode('latin1'), mode="rb") def test_interrupterd_read_retry_text(self): self.check_interrupted_read_retry(lambda x: x, mode="r") @unittest.skipUnless(threading, 'Threading required for this test.') def check_interrupted_write_retry(self, item, **fdopen_kwargs): """Check that a buffered write, when it gets interrupted (either returning a partial result or EINTR), properly invokes the signal handler and retries if the latter returned successfully.""" select = support.import_module("select") # A quantity that exceeds the buffer size of an anonymous pipe's # write end. N = support.PIPE_MAX_SIZE r, w = os.pipe() fdopen_kwargs["closefd"] = False # We need a separate thread to read from the pipe and allow the # write() to finish. This thread is started after the SIGALRM is # received (forcing a first EINTR in write()). read_results = [] write_finished = False error = [None] def _read(): try: while not write_finished: while r in select.select([r], [], [], 1.0)[0]: s = os.read(r, 1024) read_results.append(s) except BaseException as exc: error[0] = exc t = threading.Thread(target=_read) t.daemon = True def alarm1(sig, frame): signal.signal(signal.SIGALRM, alarm2) signal.alarm(1) def alarm2(sig, frame): t.start() signal.signal(signal.SIGALRM, alarm1) try: wio = self.io.open(w, **fdopen_kwargs) signal.alarm(1) # Expected behaviour: # - first raw write() is partial (because of the limited pipe buffer # and the first alarm) # - second raw write() returns EINTR (because of the second alarm) # - subsequent write()s are successful (either partial or complete) self.assertEqual(N, wio.write(item * N)) wio.flush() write_finished = True t.join() self.assertIsNone(error[0]) self.assertEqual(N, sum(len(x) for x in read_results)) finally: write_finished = True os.close(w) os.close(r) # This is deliberate. If we didn't close the file descriptor # before closing wio, wio would try to flush its internal # buffer, and could block (in case of failure). try: wio.close() except IOError as e: if e.errno != errno.EBADF: raise def test_interrupterd_write_retry_buffered(self): self.check_interrupted_write_retry(b"x", mode="wb") def test_interrupterd_write_retry_text(self): self.check_interrupted_write_retry("x", mode="w", encoding="latin1") class CSignalsTest(SignalsTest): io = io class PySignalsTest(SignalsTest): io = pyio # Handling reentrancy issues would slow down _pyio even more, so the # tests are disabled. test_reentrant_write_buffered = None test_reentrant_write_text = None def test_main(): tests = (CIOTest, PyIOTest, CBufferedReaderTest, PyBufferedReaderTest, CBufferedWriterTest, PyBufferedWriterTest, CBufferedRWPairTest, PyBufferedRWPairTest, CBufferedRandomTest, PyBufferedRandomTest, StatefulIncrementalDecoderTest, CIncrementalNewlineDecoderTest, PyIncrementalNewlineDecoderTest, CTextIOWrapperTest, PyTextIOWrapperTest, CMiscIOTest, PyMiscIOTest, CSignalsTest, PySignalsTest, ) # Put the namespaces of the IO module we are testing and some useful mock # classes in the __dict__ of each test. mocks = (MockRawIO, MisbehavedRawIO, MockFileIO, CloseFailureIO, MockNonBlockWriterIO, MockRawIOWithoutRead) all_members = io.__all__ + ["IncrementalNewlineDecoder"] c_io_ns = dict((name, getattr(io, name)) for name in all_members) py_io_ns = dict((name, getattr(pyio, name)) for name in all_members) globs = globals() c_io_ns.update((x.__name__, globs["C" + x.__name__]) for x in mocks) py_io_ns.update((x.__name__, globs["Py" + x.__name__]) for x in mocks) # Avoid turning open into a bound method. py_io_ns["open"] = pyio.OpenWrapper for test in tests: if test.__name__.startswith("C"): for name, obj in c_io_ns.items(): setattr(test, name, obj) elif test.__name__.startswith("Py"): for name, obj in py_io_ns.items(): setattr(test, name, obj) support.run_unittest(*tests) if __name__ == "__main__": test_main()
svanschalkwyk/datafari
windows/python/Lib/test/test_io.py
Python
apache-2.0
120,213
"""Default variable filters.""" import re from decimal import Decimal, InvalidOperation, ROUND_HALF_UP import random as random_module try: from functools import wraps except ImportError: from django.utils.functional import wraps # Python 2.4 fallback. from django.template import Variable, Library from django.conf import settings from django.utils import formats from django.utils.translation import ugettext, ungettext from django.utils.encoding import force_unicode, iri_to_uri from django.utils.safestring import mark_safe, SafeData register = Library() ####################### # STRING DECORATOR # ####################### def stringfilter(func): """ Decorator for filters which should only receive unicode objects. The object passed as the first positional argument will be converted to a unicode object. """ def _dec(*args, **kwargs): if args: args = list(args) args[0] = force_unicode(args[0]) if isinstance(args[0], SafeData) and getattr(func, 'is_safe', False): return mark_safe(func(*args, **kwargs)) return func(*args, **kwargs) # Include a reference to the real function (used to check original # arguments by the template parser). _dec._decorated_function = getattr(func, '_decorated_function', func) for attr in ('is_safe', 'needs_autoescape'): if hasattr(func, attr): setattr(_dec, attr, getattr(func, attr)) return wraps(func)(_dec) ################### # STRINGS # ################### def addslashes(value): """ Adds slashes before quotes. Useful for escaping strings in CSV, for example. Less useful for escaping JavaScript; use the ``escapejs`` filter instead. """ return value.replace('\\', '\\\\').replace('"', '\\"').replace("'", "\\'") addslashes.is_safe = True addslashes = stringfilter(addslashes) def capfirst(value): """Capitalizes the first character of the value.""" return value and value[0].upper() + value[1:] capfirst.is_safe=True capfirst = stringfilter(capfirst) _base_js_escapes = ( ('\\', r'\u005C'), ('\'', r'\u0027'), ('"', r'\u0022'), ('>', r'\u003E'), ('<', r'\u003C'), ('&', r'\u0026'), ('=', r'\u003D'), ('-', r'\u002D'), (';', r'\u003B'), (u'\u2028', r'\u2028'), (u'\u2029', r'\u2029') ) # Escape every ASCII character with a value less than 32. _js_escapes = (_base_js_escapes + tuple([('%c' % z, '\\u%04X' % z) for z in range(32)])) def escapejs(value): """Hex encodes characters for use in JavaScript strings.""" for bad, good in _js_escapes: value = value.replace(bad, good) return value escapejs = stringfilter(escapejs) def fix_ampersands(value): """Replaces ampersands with ``&amp;`` entities.""" from django.utils.html import fix_ampersands return fix_ampersands(value) fix_ampersands.is_safe=True fix_ampersands = stringfilter(fix_ampersands) # Values for testing floatformat input against infinity and NaN representations, # which differ across platforms and Python versions. Some (i.e. old Windows # ones) are not recognized by Decimal but we want to return them unchanged vs. # returning an empty string as we do for completley invalid input. Note these # need to be built up from values that are not inf/nan, since inf/nan values do # not reload properly from .pyc files on Windows prior to some level of Python 2.5 # (see Python Issue757815 and Issue1080440). pos_inf = 1e200 * 1e200 neg_inf = -1e200 * 1e200 nan = (1e200 * 1e200) / (1e200 * 1e200) special_floats = [str(pos_inf), str(neg_inf), str(nan)] def floatformat(text, arg=-1): """ Displays a float to a specified number of decimal places. If called without an argument, it displays the floating point number with one decimal place -- but only if there's a decimal place to be displayed: * num1 = 34.23234 * num2 = 34.00000 * num3 = 34.26000 * {{ num1|floatformat }} displays "34.2" * {{ num2|floatformat }} displays "34" * {{ num3|floatformat }} displays "34.3" If arg is positive, it will always display exactly arg number of decimal places: * {{ num1|floatformat:3 }} displays "34.232" * {{ num2|floatformat:3 }} displays "34.000" * {{ num3|floatformat:3 }} displays "34.260" If arg is negative, it will display arg number of decimal places -- but only if there are places to be displayed: * {{ num1|floatformat:"-3" }} displays "34.232" * {{ num2|floatformat:"-3" }} displays "34" * {{ num3|floatformat:"-3" }} displays "34.260" If the input float is infinity or NaN, the (platform-dependent) string representation of that value will be displayed. """ try: input_val = force_unicode(text) d = Decimal(input_val) except UnicodeEncodeError: return u'' except InvalidOperation: if input_val in special_floats: return input_val try: d = Decimal(force_unicode(float(text))) except (ValueError, InvalidOperation, TypeError, UnicodeEncodeError): return u'' try: p = int(arg) except ValueError: return input_val try: m = int(d) - d except (ValueError, OverflowError, InvalidOperation): return input_val if not m and p < 0: return mark_safe(formats.number_format(u'%d' % (int(d)), 0)) if p == 0: exp = Decimal(1) else: exp = Decimal('1.0') / (Decimal(10) ** abs(p)) try: return mark_safe(formats.number_format(u'%s' % str(d.quantize(exp, ROUND_HALF_UP)), abs(p))) except InvalidOperation: return input_val floatformat.is_safe = True def iriencode(value): """Escapes an IRI value for use in a URL.""" return force_unicode(iri_to_uri(value)) iriencode.is_safe = True iriencode = stringfilter(iriencode) def linenumbers(value, autoescape=None): """Displays text with line numbers.""" from django.utils.html import escape lines = value.split(u'\n') # Find the maximum width of the line count, for use with zero padding # string format command width = unicode(len(unicode(len(lines)))) if not autoescape or isinstance(value, SafeData): for i, line in enumerate(lines): lines[i] = (u"%0" + width + u"d. %s") % (i + 1, line) else: for i, line in enumerate(lines): lines[i] = (u"%0" + width + u"d. %s") % (i + 1, escape(line)) return mark_safe(u'\n'.join(lines)) linenumbers.is_safe = True linenumbers.needs_autoescape = True linenumbers = stringfilter(linenumbers) def lower(value): """Converts a string into all lowercase.""" return value.lower() lower.is_safe = True lower = stringfilter(lower) def make_list(value): """ Returns the value turned into a list. For an integer, it's a list of digits. For a string, it's a list of characters. """ return list(value) make_list.is_safe = False make_list = stringfilter(make_list) def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. """ import unicodedata value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore') value = unicode(re.sub('[^\w\s-]', '', value).strip().lower()) return mark_safe(re.sub('[-\s]+', '-', value)) slugify.is_safe = True slugify = stringfilter(slugify) def stringformat(value, arg): """ Formats the variable according to the arg, a string formatting specifier. This specifier uses Python string formating syntax, with the exception that the leading "%" is dropped. See http://docs.python.org/lib/typesseq-strings.html for documentation of Python string formatting """ try: return (u"%" + unicode(arg)) % value except (ValueError, TypeError): return u"" stringformat.is_safe = True def title(value): """Converts a string into titlecase.""" t = re.sub("([a-z])'([A-Z])", lambda m: m.group(0).lower(), value.title()) return re.sub("\d([A-Z])", lambda m: m.group(0).lower(), t) title.is_safe = True title = stringfilter(title) def truncatewords(value, arg): """ Truncates a string after a certain number of words. Argument: Number of words to truncate after. """ from django.utils.text import truncate_words try: length = int(arg) except ValueError: # Invalid literal for int(). return value # Fail silently. return truncate_words(value, length) truncatewords.is_safe = True truncatewords = stringfilter(truncatewords) def truncatewords_html(value, arg): """ Truncates HTML after a certain number of words. Argument: Number of words to truncate after. """ from django.utils.text import truncate_html_words try: length = int(arg) except ValueError: # invalid literal for int() return value # Fail silently. return truncate_html_words(value, length) truncatewords_html.is_safe = True truncatewords_html = stringfilter(truncatewords_html) def upper(value): """Converts a string into all uppercase.""" return value.upper() upper.is_safe = False upper = stringfilter(upper) def urlencode(value): """Escapes a value for use in a URL.""" from django.utils.http import urlquote return urlquote(value) urlencode.is_safe = False urlencode = stringfilter(urlencode) def urlize(value, autoescape=None): """Converts URLs in plain text into clickable links.""" from django.utils.html import urlize return mark_safe(urlize(value, nofollow=True, autoescape=autoescape)) urlize.is_safe=True urlize.needs_autoescape = True urlize = stringfilter(urlize) def urlizetrunc(value, limit, autoescape=None): """ Converts URLs into clickable links, truncating URLs to the given character limit, and adding 'rel=nofollow' attribute to discourage spamming. Argument: Length to truncate URLs to. """ from django.utils.html import urlize return mark_safe(urlize(value, trim_url_limit=int(limit), nofollow=True, autoescape=autoescape)) urlizetrunc.is_safe = True urlizetrunc.needs_autoescape = True urlizetrunc = stringfilter(urlizetrunc) def wordcount(value): """Returns the number of words.""" return len(value.split()) wordcount.is_safe = False wordcount = stringfilter(wordcount) def wordwrap(value, arg): """ Wraps words at specified line length. Argument: number of characters to wrap the text at. """ from django.utils.text import wrap return wrap(value, int(arg)) wordwrap.is_safe = True wordwrap = stringfilter(wordwrap) def ljust(value, arg): """ Left-aligns the value in a field of a given width. Argument: field size. """ return value.ljust(int(arg)) ljust.is_safe = True ljust = stringfilter(ljust) def rjust(value, arg): """ Right-aligns the value in a field of a given width. Argument: field size. """ return value.rjust(int(arg)) rjust.is_safe = True rjust = stringfilter(rjust) def center(value, arg): """Centers the value in a field of a given width.""" return value.center(int(arg)) center.is_safe = True center = stringfilter(center) def cut(value, arg): """ Removes all values of arg from the given string. """ safe = isinstance(value, SafeData) value = value.replace(arg, u'') if safe and arg != ';': return mark_safe(value) return value cut = stringfilter(cut) ################### # HTML STRINGS # ################### def escape(value): """ Marks the value as a string that should not be auto-escaped. """ from django.utils.safestring import mark_for_escaping return mark_for_escaping(value) escape.is_safe = True escape = stringfilter(escape) def force_escape(value): """ Escapes a string's HTML. This returns a new string containing the escaped characters (as opposed to "escape", which marks the content for later possible escaping). """ from django.utils.html import escape return mark_safe(escape(value)) force_escape = stringfilter(force_escape) force_escape.is_safe = True def linebreaks(value, autoescape=None): """ Replaces line breaks in plain text with appropriate HTML; a single newline becomes an HTML line break (``<br />``) and a new line followed by a blank line becomes a paragraph break (``</p>``). """ from django.utils.html import linebreaks autoescape = autoescape and not isinstance(value, SafeData) return mark_safe(linebreaks(value, autoescape)) linebreaks.is_safe = True linebreaks.needs_autoescape = True linebreaks = stringfilter(linebreaks) def linebreaksbr(value, autoescape=None): """ Converts all newlines in a piece of plain text to HTML line breaks (``<br />``). """ if autoescape and not isinstance(value, SafeData): from django.utils.html import escape value = escape(value) return mark_safe(value.replace('\n', '<br />')) linebreaksbr.is_safe = True linebreaksbr.needs_autoescape = True linebreaksbr = stringfilter(linebreaksbr) def safe(value): """ Marks the value as a string that should not be auto-escaped. """ return mark_safe(value) safe.is_safe = True safe = stringfilter(safe) def safeseq(value): """ A "safe" filter for sequences. Marks each element in the sequence, individually, as safe, after converting them to unicode. Returns a list with the results. """ return [mark_safe(force_unicode(obj)) for obj in value] safeseq.is_safe = True def removetags(value, tags): """Removes a space separated list of [X]HTML tags from the output.""" tags = [re.escape(tag) for tag in tags.split()] tags_re = u'(%s)' % u'|'.join(tags) starttag_re = re.compile(ur'<%s(/?>|(\s+[^>]*>))' % tags_re, re.U) endtag_re = re.compile(u'</%s>' % tags_re) value = starttag_re.sub(u'', value) value = endtag_re.sub(u'', value) return value removetags.is_safe = True removetags = stringfilter(removetags) def striptags(value): """Strips all [X]HTML tags.""" from django.utils.html import strip_tags return strip_tags(value) striptags.is_safe = True striptags = stringfilter(striptags) ################### # LISTS # ################### def dictsort(value, arg): """ Takes a list of dicts, returns that list sorted by the property given in the argument. """ var_resolve = Variable(arg).resolve decorated = [(var_resolve(item), item) for item in value] decorated.sort() return [item[1] for item in decorated] dictsort.is_safe = False def dictsortreversed(value, arg): """ Takes a list of dicts, returns that list sorted in reverse order by the property given in the argument. """ var_resolve = Variable(arg).resolve decorated = [(var_resolve(item), item) for item in value] decorated.sort() decorated.reverse() return [item[1] for item in decorated] dictsortreversed.is_safe = False def first(value): """Returns the first item in a list.""" try: return value[0] except IndexError: return u'' first.is_safe = False def join(value, arg, autoescape=None): """ Joins a list with a string, like Python's ``str.join(list)``. """ value = map(force_unicode, value) if autoescape: from django.utils.html import conditional_escape value = [conditional_escape(v) for v in value] try: data = arg.join(value) except AttributeError: # fail silently but nicely return value return mark_safe(data) join.is_safe = True join.needs_autoescape = True def last(value): "Returns the last item in a list" try: return value[-1] except IndexError: return u'' last.is_safe = True def length(value): """Returns the length of the value - useful for lists.""" try: return len(value) except (ValueError, TypeError): return '' length.is_safe = True def length_is(value, arg): """Returns a boolean of whether the value's length is the argument.""" try: return len(value) == int(arg) except (ValueError, TypeError): return '' length_is.is_safe = False def random(value): """Returns a random item from the list.""" return random_module.choice(value) random.is_safe = True def slice_(value, arg): """ Returns a slice of the list. Uses the same syntax as Python's list slicing; see http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice for an introduction. """ try: bits = [] for x in arg.split(u':'): if len(x) == 0: bits.append(None) else: bits.append(int(x)) return value[slice(*bits)] except (ValueError, TypeError): return value # Fail silently. slice_.is_safe = True def unordered_list(value, autoescape=None): """ Recursively takes a self-nested list and returns an HTML unordered list -- WITHOUT opening and closing <ul> tags. The list is assumed to be in the proper format. For example, if ``var`` contains: ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then ``{{ var|unordered_list }}`` would return:: <li>States <ul> <li>Kansas <ul> <li>Lawrence</li> <li>Topeka</li> </ul> </li> <li>Illinois</li> </ul> </li> """ if autoescape: from django.utils.html import conditional_escape escaper = conditional_escape else: escaper = lambda x: x def convert_old_style_list(list_): """ Converts old style lists to the new easier to understand format. The old list format looked like: ['Item 1', [['Item 1.1', []], ['Item 1.2', []]] And it is converted to: ['Item 1', ['Item 1.1', 'Item 1.2]] """ if not isinstance(list_, (tuple, list)) or len(list_) != 2: return list_, False first_item, second_item = list_ if second_item == []: return [first_item], True old_style_list = True new_second_item = [] for sublist in second_item: item, old_style_list = convert_old_style_list(sublist) if not old_style_list: break new_second_item.extend(item) if old_style_list: second_item = new_second_item return [first_item, second_item], old_style_list def _helper(list_, tabs=1): indent = u'\t' * tabs output = [] list_length = len(list_) i = 0 while i < list_length: title = list_[i] sublist = '' sublist_item = None if isinstance(title, (list, tuple)): sublist_item = title title = '' elif i < list_length - 1: next_item = list_[i+1] if next_item and isinstance(next_item, (list, tuple)): # The next item is a sub-list. sublist_item = next_item # We've processed the next item now too. i += 1 if sublist_item: sublist = _helper(sublist_item, tabs+1) sublist = '\n%s<ul>\n%s\n%s</ul>\n%s' % (indent, sublist, indent, indent) output.append('%s<li>%s%s</li>' % (indent, escaper(force_unicode(title)), sublist)) i += 1 return '\n'.join(output) value, converted = convert_old_style_list(value) return mark_safe(_helper(value)) unordered_list.is_safe = True unordered_list.needs_autoescape = True ################### # INTEGERS # ################### def add(value, arg): """Adds the arg to the value.""" try: return int(value) + int(arg) except (ValueError, TypeError): try: return value + arg except: return value add.is_safe = False def get_digit(value, arg): """ Given a whole number, returns the requested digit of it, where 1 is the right-most digit, 2 is the second-right-most digit, etc. Returns the original value for invalid input (if input or argument is not an integer, or if argument is less than 1). Otherwise, output is always an integer. """ try: arg = int(arg) value = int(value) except ValueError: return value # Fail silently for an invalid argument if arg < 1: return value try: return int(str(value)[-arg]) except IndexError: return 0 get_digit.is_safe = False ################### # DATES # ################### def date(value, arg=None): """Formats a date according to the given format.""" from django.utils.dateformat import format if not value: return u'' if arg is None: arg = settings.DATE_FORMAT try: return formats.date_format(value, arg) except AttributeError: try: return format(value, arg) except AttributeError: return '' date.is_safe = False def time(value, arg=None): """Formats a time according to the given format.""" from django.utils import dateformat if value in (None, u''): return u'' if arg is None: arg = settings.TIME_FORMAT try: return formats.time_format(value, arg) except AttributeError: try: return dateformat.time_format(value, arg) except AttributeError: return '' time.is_safe = False def timesince(value, arg=None): """Formats a date as the time since that date (i.e. "4 days, 6 hours").""" from django.utils.timesince import timesince if not value: return u'' try: if arg: return timesince(value, arg) return timesince(value) except (ValueError, TypeError): return u'' timesince.is_safe = False def timeuntil(value, arg=None): """Formats a date as the time until that date (i.e. "4 days, 6 hours").""" from django.utils.timesince import timeuntil from datetime import datetime if not value: return u'' try: return timeuntil(value, arg) except (ValueError, TypeError): return u'' timeuntil.is_safe = False ################### # LOGIC # ################### def default(value, arg): """If value is unavailable, use given default.""" return value or arg default.is_safe = False def default_if_none(value, arg): """If value is None, use given default.""" if value is None: return arg return value default_if_none.is_safe = False def divisibleby(value, arg): """Returns True if the value is devisible by the argument.""" return int(value) % int(arg) == 0 divisibleby.is_safe = False def yesno(value, arg=None): """ Given a string mapping values for true, false and (optionally) None, returns one of those strings accoding to the value: ========== ====================== ================================== Value Argument Outputs ========== ====================== ================================== ``True`` ``"yeah,no,maybe"`` ``yeah`` ``False`` ``"yeah,no,maybe"`` ``no`` ``None`` ``"yeah,no,maybe"`` ``maybe`` ``None`` ``"yeah,no"`` ``"no"`` (converts None to False if no mapping for None is given. ========== ====================== ================================== """ if arg is None: arg = ugettext('yes,no,maybe') bits = arg.split(u',') if len(bits) < 2: return value # Invalid arg. try: yes, no, maybe = bits except ValueError: # Unpack list of wrong size (no "maybe" value provided). yes, no, maybe = bits[0], bits[1], bits[1] if value is None: return maybe if value: return yes return no yesno.is_safe = False ################### # MISC # ################### def filesizeformat(bytes): """ Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc). """ try: bytes = float(bytes) except (TypeError,ValueError,UnicodeDecodeError): return u"0 bytes" if bytes < 1024: return ungettext("%(size)d byte", "%(size)d bytes", bytes) % {'size': bytes} if bytes < 1024 * 1024: return ugettext("%.1f KB") % (bytes / 1024) if bytes < 1024 * 1024 * 1024: return ugettext("%.1f MB") % (bytes / (1024 * 1024)) return ugettext("%.1f GB") % (bytes / (1024 * 1024 * 1024)) filesizeformat.is_safe = True def pluralize(value, arg=u's'): """ Returns a plural suffix if the value is not 1. By default, 's' is used as the suffix: * If value is 0, vote{{ value|pluralize }} displays "0 votes". * If value is 1, vote{{ value|pluralize }} displays "1 vote". * If value is 2, vote{{ value|pluralize }} displays "2 votes". If an argument is provided, that string is used instead: * If value is 0, class{{ value|pluralize:"es" }} displays "0 classes". * If value is 1, class{{ value|pluralize:"es" }} displays "1 class". * If value is 2, class{{ value|pluralize:"es" }} displays "2 classes". If the provided argument contains a comma, the text before the comma is used for the singular case and the text after the comma is used for the plural case: * If value is 0, cand{{ value|pluralize:"y,ies" }} displays "0 candies". * If value is 1, cand{{ value|pluralize:"y,ies" }} displays "1 candy". * If value is 2, cand{{ value|pluralize:"y,ies" }} displays "2 candies". """ if not u',' in arg: arg = u',' + arg bits = arg.split(u',') if len(bits) > 2: return u'' singular_suffix, plural_suffix = bits[:2] try: if int(value) != 1: return plural_suffix except ValueError: # Invalid string that's not a number. pass except TypeError: # Value isn't a string or a number; maybe it's a list? try: if len(value) != 1: return plural_suffix except TypeError: # len() of unsized object. pass return singular_suffix pluralize.is_safe = False def phone2numeric(value): """Takes a phone number and converts it in to its numerical equivalent.""" from django.utils.text import phone2numeric return phone2numeric(value) phone2numeric.is_safe = True def pprint(value): """A wrapper around pprint.pprint -- for debugging, really.""" from pprint import pformat try: return pformat(value) except Exception, e: return u"Error in formatting: %s" % force_unicode(e, errors="replace") pprint.is_safe = True # Syntax: register.filter(name of filter, callback) register.filter(add) register.filter(addslashes) register.filter(capfirst) register.filter(center) register.filter(cut) register.filter(date) register.filter(default) register.filter(default_if_none) register.filter(dictsort) register.filter(dictsortreversed) register.filter(divisibleby) register.filter(escape) register.filter(escapejs) register.filter(filesizeformat) register.filter(first) register.filter(fix_ampersands) register.filter(floatformat) register.filter(force_escape) register.filter(get_digit) register.filter(iriencode) register.filter(join) register.filter(last) register.filter(length) register.filter(length_is) register.filter(linebreaks) register.filter(linebreaksbr) register.filter(linenumbers) register.filter(ljust) register.filter(lower) register.filter(make_list) register.filter(phone2numeric) register.filter(pluralize) register.filter(pprint) register.filter(removetags) register.filter(random) register.filter(rjust) register.filter(safe) register.filter(safeseq) register.filter('slice', slice_) register.filter(slugify) register.filter(stringformat) register.filter(striptags) register.filter(time) register.filter(timesince) register.filter(timeuntil) register.filter(title) register.filter(truncatewords) register.filter(truncatewords_html) register.filter(unordered_list) register.filter(upper) register.filter(urlencode) register.filter(urlize) register.filter(urlizetrunc) register.filter(wordcount) register.filter(wordwrap) register.filter(yesno)
nycholas/ask-undrgz
src/ask-undrgz/django/template/defaultfilters.py
Python
bsd-3-clause
28,636
r""" ================================== Constants (:mod:`scipy.constants`) ================================== .. currentmodule:: scipy.constants Physical and mathematical constants and units. Mathematical constants ====================== ================ ================================================================= ``pi`` Pi ``golden`` Golden ratio ``golden_ratio`` Golden ratio ================ ================================================================= Physical constants ================== =========================== ================================================================= ``c`` speed of light in vacuum ``speed_of_light`` speed of light in vacuum ``mu_0`` the magnetic constant :math:`\mu_0` ``epsilon_0`` the electric constant (vacuum permittivity), :math:`\epsilon_0` ``h`` the Planck constant :math:`h` ``Planck`` the Planck constant :math:`h` ``hbar`` :math:`\hbar = h/(2\pi)` ``G`` Newtonian constant of gravitation ``gravitational_constant`` Newtonian constant of gravitation ``g`` standard acceleration of gravity ``e`` elementary charge ``elementary_charge`` elementary charge ``R`` molar gas constant ``gas_constant`` molar gas constant ``alpha`` fine-structure constant ``fine_structure`` fine-structure constant ``N_A`` Avogadro constant ``Avogadro`` Avogadro constant ``k`` Boltzmann constant ``Boltzmann`` Boltzmann constant ``sigma`` Stefan-Boltzmann constant :math:`\sigma` ``Stefan_Boltzmann`` Stefan-Boltzmann constant :math:`\sigma` ``Wien`` Wien displacement law constant ``Rydberg`` Rydberg constant ``m_e`` electron mass ``electron_mass`` electron mass ``m_p`` proton mass ``proton_mass`` proton mass ``m_n`` neutron mass ``neutron_mass`` neutron mass =========================== ================================================================= Constants database ------------------ In addition to the above variables, :mod:`scipy.constants` also contains the 2018 CODATA recommended values [CODATA2018]_ database containing more physical constants. .. autosummary:: :toctree: generated/ value -- Value in physical_constants indexed by key unit -- Unit in physical_constants indexed by key precision -- Relative precision in physical_constants indexed by key find -- Return list of physical_constant keys with a given string ConstantWarning -- Constant sought not in newest CODATA data set .. data:: physical_constants Dictionary of physical constants, of the format ``physical_constants[name] = (value, unit, uncertainty)``. Available constants: ====================================================================== ==== %(constant_names)s ====================================================================== ==== Units ===== SI prefixes ----------- ============ ================================================================= ``yotta`` :math:`10^{24}` ``zetta`` :math:`10^{21}` ``exa`` :math:`10^{18}` ``peta`` :math:`10^{15}` ``tera`` :math:`10^{12}` ``giga`` :math:`10^{9}` ``mega`` :math:`10^{6}` ``kilo`` :math:`10^{3}` ``hecto`` :math:`10^{2}` ``deka`` :math:`10^{1}` ``deci`` :math:`10^{-1}` ``centi`` :math:`10^{-2}` ``milli`` :math:`10^{-3}` ``micro`` :math:`10^{-6}` ``nano`` :math:`10^{-9}` ``pico`` :math:`10^{-12}` ``femto`` :math:`10^{-15}` ``atto`` :math:`10^{-18}` ``zepto`` :math:`10^{-21}` ============ ================================================================= Binary prefixes --------------- ============ ================================================================= ``kibi`` :math:`2^{10}` ``mebi`` :math:`2^{20}` ``gibi`` :math:`2^{30}` ``tebi`` :math:`2^{40}` ``pebi`` :math:`2^{50}` ``exbi`` :math:`2^{60}` ``zebi`` :math:`2^{70}` ``yobi`` :math:`2^{80}` ============ ================================================================= Mass ---- ================= ============================================================ ``gram`` :math:`10^{-3}` kg ``metric_ton`` :math:`10^{3}` kg ``grain`` one grain in kg ``lb`` one pound (avoirdupous) in kg ``pound`` one pound (avoirdupous) in kg ``blob`` one inch version of a slug in kg (added in 1.0.0) ``slinch`` one inch version of a slug in kg (added in 1.0.0) ``slug`` one slug in kg (added in 1.0.0) ``oz`` one ounce in kg ``ounce`` one ounce in kg ``stone`` one stone in kg ``grain`` one grain in kg ``long_ton`` one long ton in kg ``short_ton`` one short ton in kg ``troy_ounce`` one Troy ounce in kg ``troy_pound`` one Troy pound in kg ``carat`` one carat in kg ``m_u`` atomic mass constant (in kg) ``u`` atomic mass constant (in kg) ``atomic_mass`` atomic mass constant (in kg) ================= ============================================================ Angle ----- ================= ============================================================ ``degree`` degree in radians ``arcmin`` arc minute in radians ``arcminute`` arc minute in radians ``arcsec`` arc second in radians ``arcsecond`` arc second in radians ================= ============================================================ Time ---- ================= ============================================================ ``minute`` one minute in seconds ``hour`` one hour in seconds ``day`` one day in seconds ``week`` one week in seconds ``year`` one year (365 days) in seconds ``Julian_year`` one Julian year (365.25 days) in seconds ================= ============================================================ Length ------ ===================== ============================================================ ``inch`` one inch in meters ``foot`` one foot in meters ``yard`` one yard in meters ``mile`` one mile in meters ``mil`` one mil in meters ``pt`` one point in meters ``point`` one point in meters ``survey_foot`` one survey foot in meters ``survey_mile`` one survey mile in meters ``nautical_mile`` one nautical mile in meters ``fermi`` one Fermi in meters ``angstrom`` one Angstrom in meters ``micron`` one micron in meters ``au`` one astronomical unit in meters ``astronomical_unit`` one astronomical unit in meters ``light_year`` one light year in meters ``parsec`` one parsec in meters ===================== ============================================================ Pressure -------- ================= ============================================================ ``atm`` standard atmosphere in pascals ``atmosphere`` standard atmosphere in pascals ``bar`` one bar in pascals ``torr`` one torr (mmHg) in pascals ``mmHg`` one torr (mmHg) in pascals ``psi`` one psi in pascals ================= ============================================================ Area ---- ================= ============================================================ ``hectare`` one hectare in square meters ``acre`` one acre in square meters ================= ============================================================ Volume ------ =================== ======================================================== ``liter`` one liter in cubic meters ``litre`` one liter in cubic meters ``gallon`` one gallon (US) in cubic meters ``gallon_US`` one gallon (US) in cubic meters ``gallon_imp`` one gallon (UK) in cubic meters ``fluid_ounce`` one fluid ounce (US) in cubic meters ``fluid_ounce_US`` one fluid ounce (US) in cubic meters ``fluid_ounce_imp`` one fluid ounce (UK) in cubic meters ``bbl`` one barrel in cubic meters ``barrel`` one barrel in cubic meters =================== ======================================================== Speed ----- ================== ========================================================== ``kmh`` kilometers per hour in meters per second ``mph`` miles per hour in meters per second ``mach`` one Mach (approx., at 15 C, 1 atm) in meters per second ``speed_of_sound`` one Mach (approx., at 15 C, 1 atm) in meters per second ``knot`` one knot in meters per second ================== ========================================================== Temperature ----------- ===================== ======================================================= ``zero_Celsius`` zero of Celsius scale in Kelvin ``degree_Fahrenheit`` one Fahrenheit (only differences) in Kelvins ===================== ======================================================= .. autosummary:: :toctree: generated/ convert_temperature Energy ------ ==================== ======================================================= ``eV`` one electron volt in Joules ``electron_volt`` one electron volt in Joules ``calorie`` one calorie (thermochemical) in Joules ``calorie_th`` one calorie (thermochemical) in Joules ``calorie_IT`` one calorie (International Steam Table calorie, 1956) in Joules ``erg`` one erg in Joules ``Btu`` one British thermal unit (International Steam Table) in Joules ``Btu_IT`` one British thermal unit (International Steam Table) in Joules ``Btu_th`` one British thermal unit (thermochemical) in Joules ``ton_TNT`` one ton of TNT in Joules ==================== ======================================================= Power ----- ==================== ======================================================= ``hp`` one horsepower in watts ``horsepower`` one horsepower in watts ==================== ======================================================= Force ----- ==================== ======================================================= ``dyn`` one dyne in newtons ``dyne`` one dyne in newtons ``lbf`` one pound force in newtons ``pound_force`` one pound force in newtons ``kgf`` one kilogram force in newtons ``kilogram_force`` one kilogram force in newtons ==================== ======================================================= Optics ------ .. autosummary:: :toctree: generated/ lambda2nu nu2lambda References ========== .. [CODATA2018] CODATA Recommended Values of the Fundamental Physical Constants 2018. https://physics.nist.gov/cuu/Constants/ """ # Modules contributed by BasSw (wegwerp@gmail.com) from .codata import * from .constants import * from .codata import _obsolete_constants _constant_names = [(_k.lower(), _k, _v) for _k, _v in physical_constants.items() if _k not in _obsolete_constants] _constant_names = "\n".join(["``%s``%s %s %s" % (_x[1], " "*(66-len(_x[1])), _x[2][0], _x[2][1]) for _x in sorted(_constant_names)]) if __doc__: __doc__ = __doc__ % dict(constant_names=_constant_names) del _constant_names __all__ = [s for s in dir() if not s.startswith('_')] from scipy._lib._testutils import PytestTester test = PytestTester(__name__) del PytestTester
WarrenWeckesser/scipy
scipy/constants/__init__.py
Python
bsd-3-clause
12,116
from __future__ import print_function, division from sympy.core.basic import Basic from sympy.core.mul import Mul from sympy.core.singleton import S, Singleton from sympy.core.symbol import Dummy, Symbol from sympy.core.compatibility import (range, integer_types, with_metaclass, is_sequence, iterable, ordered) from sympy.core.decorators import call_highest_priority from sympy.core.cache import cacheit from sympy.core.sympify import sympify from sympy.core.containers import Tuple from sympy.core.evaluate import global_evaluate from sympy.polys import lcm, factor from sympy.sets.sets import Interval, Intersection from sympy.utilities.iterables import flatten from sympy.tensor.indexed import Idx from sympy.simplify import simplify from sympy import expand ############################################################################### # SEQUENCES # ############################################################################### class SeqBase(Basic): """Base class for sequences""" is_commutative = True _op_priority = 15 @staticmethod def _start_key(expr): """Return start (if possible) else S.Infinity. adapted from Set._infimum_key """ try: start = expr.start except (NotImplementedError, AttributeError, ValueError): start = S.Infinity return start def _intersect_interval(self, other): """Returns start and stop. Takes intersection over the two intervals. """ interval = Intersection(self.interval, other.interval) return interval.inf, interval.sup @property def gen(self): """Returns the generator for the sequence""" raise NotImplementedError("(%s).gen" % self) @property def interval(self): """The interval on which the sequence is defined""" raise NotImplementedError("(%s).interval" % self) @property def start(self): """The starting point of the sequence. This point is included""" raise NotImplementedError("(%s).start" % self) @property def stop(self): """The ending point of the sequence. This point is included""" raise NotImplementedError("(%s).stop" % self) @property def length(self): """Length of the sequence""" raise NotImplementedError("(%s).length" % self) @property def variables(self): """Returns a tuple of variables that are bounded""" return () @property def free_symbols(self): """ This method returns the symbols in the object, excluding those that take on a specific value (i.e. the dummy symbols). Examples ======== >>> from sympy import SeqFormula >>> from sympy.abc import n, m >>> SeqFormula(m*n**2, (n, 0, 5)).free_symbols {m} """ return (set(j for i in self.args for j in i.free_symbols .difference(self.variables))) @cacheit def coeff(self, pt): """Returns the coefficient at point pt""" if pt < self.start or pt > self.stop: raise IndexError("Index %s out of bounds %s" % (pt, self.interval)) return self._eval_coeff(pt) def _eval_coeff(self, pt): raise NotImplementedError("The _eval_coeff method should be added to" "%s to return coefficient so it is available" "when coeff calls it." % self.func) def _ith_point(self, i): """Returns the i'th point of a sequence. If start point is negative infinity, point is returned from the end. Assumes the first point to be indexed zero. Examples ========= >>> from sympy import oo >>> from sympy.series.sequences import SeqPer bounded >>> SeqPer((1, 2, 3), (-10, 10))._ith_point(0) -10 >>> SeqPer((1, 2, 3), (-10, 10))._ith_point(5) -5 End is at infinity >>> SeqPer((1, 2, 3), (0, oo))._ith_point(5) 5 Starts at negative infinity >>> SeqPer((1, 2, 3), (-oo, 0))._ith_point(5) -5 """ if self.start is S.NegativeInfinity: initial = self.stop else: initial = self.start if self.start is S.NegativeInfinity: step = -1 else: step = 1 return initial + i*step def _add(self, other): """ Should only be used internally. self._add(other) returns a new, term-wise added sequence if self knows how to add with other, otherwise it returns ``None``. ``other`` should only be a sequence object. Used within :class:`SeqAdd` class. """ return None def _mul(self, other): """ Should only be used internally. self._mul(other) returns a new, term-wise multiplied sequence if self knows how to multiply with other, otherwise it returns ``None``. ``other`` should only be a sequence object. Used within :class:`SeqMul` class. """ return None def coeff_mul(self, other): """ Should be used when ``other`` is not a sequence. Should be defined to define custom behaviour. Examples ======== >>> from sympy import S, oo, SeqFormula >>> from sympy.abc import n >>> SeqFormula(n**2).coeff_mul(2) SeqFormula(2*n**2, (n, 0, oo)) Notes ===== '*' defines multiplication of sequences with sequences only. """ return Mul(self, other) def __add__(self, other): """Returns the term-wise addition of 'self' and 'other'. ``other`` should be a sequence. Examples ======== >>> from sympy import S, oo, SeqFormula >>> from sympy.abc import n >>> SeqFormula(n**2) + SeqFormula(n**3) SeqFormula(n**3 + n**2, (n, 0, oo)) """ if not isinstance(other, SeqBase): raise TypeError('cannot add sequence and %s' % type(other)) return SeqAdd(self, other) @call_highest_priority('__add__') def __radd__(self, other): return self + other def __sub__(self, other): """Returns the term-wise subtraction of 'self' and 'other'. ``other`` should be a sequence. Examples ======== >>> from sympy import S, oo, SeqFormula >>> from sympy.abc import n >>> SeqFormula(n**2) - (SeqFormula(n)) SeqFormula(n**2 - n, (n, 0, oo)) """ if not isinstance(other, SeqBase): raise TypeError('cannot subtract sequence and %s' % type(other)) return SeqAdd(self, -other) @call_highest_priority('__sub__') def __rsub__(self, other): return (-self) + other def __neg__(self): """Negates the sequence. Examples ======== >>> from sympy import S, oo, SeqFormula >>> from sympy.abc import n >>> -SeqFormula(n**2) SeqFormula(-n**2, (n, 0, oo)) """ return self.coeff_mul(-1) def __mul__(self, other): """Returns the term-wise multiplication of 'self' and 'other'. ``other`` should be a sequence. For ``other`` not being a sequence see :func:`coeff_mul` method. Examples ======== >>> from sympy import S, oo, SeqFormula >>> from sympy.abc import n >>> SeqFormula(n**2) * (SeqFormula(n)) SeqFormula(n**3, (n, 0, oo)) """ if not isinstance(other, SeqBase): raise TypeError('cannot multiply sequence and %s' % type(other)) return SeqMul(self, other) @call_highest_priority('__mul__') def __rmul__(self, other): return self * other def __iter__(self): for i in range(self.length): pt = self._ith_point(i) yield self.coeff(pt) def __getitem__(self, index): if isinstance(index, integer_types): index = self._ith_point(index) return self.coeff(index) elif isinstance(index, slice): start, stop = index.start, index.stop if start is None: start = 0 if stop is None: stop = self.length return [self.coeff(self._ith_point(i)) for i in range(start, stop, index.step or 1)] def find_linear_recurrence(self,n,d=None,gfvar=None): r""" Finds the shortest linear recurrence that satisfies the first n terms of sequence of order `\leq` n/2 if possible. If d is specified, find shortest linear recurrence of order `\leq` min(d, n/2) if possible. Returns list of coefficients ``[b(1), b(2), ...]`` corresponding to the recurrence relation ``x(n) = b(1)*x(n-1) + b(2)*x(n-2) + ...`` Returns ``[]`` if no recurrence is found. If gfvar is specified, also returns ordinary generating function as a function of gfvar. Examples ======== >>> from sympy import sequence, sqrt, oo, lucas >>> from sympy.abc import n, x, y >>> sequence(n**2).find_linear_recurrence(10, 2) [] >>> sequence(n**2).find_linear_recurrence(10) [3, -3, 1] >>> sequence(2**n).find_linear_recurrence(10) [2] >>> sequence(23*n**4+91*n**2).find_linear_recurrence(10) [5, -10, 10, -5, 1] >>> sequence(sqrt(5)*(((1 + sqrt(5))/2)**n - (-(1 + sqrt(5))/2)**(-n))/5).find_linear_recurrence(10) [1, 1] >>> sequence(x+y*(-2)**(-n), (n, 0, oo)).find_linear_recurrence(30) [1/2, 1/2] >>> sequence(3*5**n + 12).find_linear_recurrence(20,gfvar=x) ([6, -5], 3*(-21*x + 5)/((x - 1)*(5*x - 1))) >>> sequence(lucas(n)).find_linear_recurrence(15,gfvar=x) ([1, 1], (x - 2)/(x**2 + x - 1)) """ from sympy.matrices import Matrix x = [simplify(expand(t)) for t in self[:n]] lx = len(x) if d == None: r = lx//2 else: r = min(d,lx//2) coeffs = [] for l in range(1, r+1): l2 = 2*l mlist = [] for k in range(l): mlist.append(x[k:k+l]) m = Matrix(mlist) if m.det() != 0: y = simplify(m.LUsolve(Matrix(x[l:l2]))) if lx == l2: coeffs = flatten(y[::-1]) break mlist = [] for k in range(l,lx-l): mlist.append(x[k:k+l]) m = Matrix(mlist) if m*y == Matrix(x[l2:]): coeffs = flatten(y[::-1]) break if gfvar == None: return coeffs else: l = len(coeffs) if l == 0: return [], None else: n, d = x[l-1]*gfvar**(l-1), 1 - coeffs[l-1]*gfvar**l for i in range(l-1): n += x[i]*gfvar**i for j in range(l-i-1): n -= coeffs[i]*x[j]*gfvar**(i+j+1) d -= coeffs[i]*gfvar**(i+1) return coeffs, simplify(factor(n)/factor(d)) class EmptySequence(with_metaclass(Singleton, SeqBase)): """Represents an empty sequence. The empty sequence is available as a singleton as ``S.EmptySequence``. Examples ======== >>> from sympy import S, SeqPer, oo >>> from sympy.abc import x >>> S.EmptySequence EmptySequence() >>> SeqPer((1, 2), (x, 0, 10)) + S.EmptySequence SeqPer((1, 2), (x, 0, 10)) >>> SeqPer((1, 2)) * S.EmptySequence EmptySequence() >>> S.EmptySequence.coeff_mul(-1) EmptySequence() """ @property def interval(self): return S.EmptySet @property def length(self): return S.Zero def coeff_mul(self, coeff): """See docstring of SeqBase.coeff_mul""" return self def __iter__(self): return iter([]) class SeqExpr(SeqBase): """Sequence expression class. Various sequences should inherit from this class. Examples ======== >>> from sympy.series.sequences import SeqExpr >>> from sympy.abc import x >>> s = SeqExpr((1, 2, 3), (x, 0, 10)) >>> s.gen (1, 2, 3) >>> s.interval Interval(0, 10) >>> s.length 11 See Also ======== sympy.series.sequences.SeqPer sympy.series.sequences.SeqFormula """ @property def gen(self): return self.args[0] @property def interval(self): return Interval(self.args[1][1], self.args[1][2]) @property def start(self): return self.interval.inf @property def stop(self): return self.interval.sup @property def length(self): return self.stop - self.start + 1 @property def variables(self): return (self.args[1][0],) class SeqPer(SeqExpr): """Represents a periodic sequence. The elements are repeated after a given period. Examples ======== >>> from sympy import SeqPer, oo >>> from sympy.abc import k >>> s = SeqPer((1, 2, 3), (0, 5)) >>> s.periodical (1, 2, 3) >>> s.period 3 For value at a particular point >>> s.coeff(3) 1 supports slicing >>> s[:] [1, 2, 3, 1, 2, 3] iterable >>> list(s) [1, 2, 3, 1, 2, 3] sequence starts from negative infinity >>> SeqPer((1, 2, 3), (-oo, 0))[0:6] [1, 2, 3, 1, 2, 3] Periodic formulas >>> SeqPer((k, k**2, k**3), (k, 0, oo))[0:6] [0, 1, 8, 3, 16, 125] See Also ======== sympy.series.sequences.SeqFormula """ def __new__(cls, periodical, limits=None): periodical = sympify(periodical) def _find_x(periodical): free = periodical.free_symbols if len(periodical.free_symbols) == 1: return free.pop() else: return Dummy('k') x, start, stop = None, None, None if limits is None: x, start, stop = _find_x(periodical), 0, S.Infinity if is_sequence(limits, Tuple): if len(limits) == 3: x, start, stop = limits elif len(limits) == 2: x = _find_x(periodical) start, stop = limits if not isinstance(x, (Symbol, Idx)) or start is None or stop is None: raise ValueError('Invalid limits given: %s' % str(limits)) if start is S.NegativeInfinity and stop is S.Infinity: raise ValueError("Both the start and end value" "cannot be unbounded") limits = sympify((x, start, stop)) if is_sequence(periodical, Tuple): periodical = sympify(tuple(flatten(periodical))) else: raise ValueError("invalid period %s should be something " "like e.g (1, 2) " % periodical) if Interval(limits[1], limits[2]) is S.EmptySet: return S.EmptySequence return Basic.__new__(cls, periodical, limits) @property def period(self): return len(self.gen) @property def periodical(self): return self.gen def _eval_coeff(self, pt): if self.start is S.NegativeInfinity: idx = (self.stop - pt) % self.period else: idx = (pt - self.start) % self.period return self.periodical[idx].subs(self.variables[0], pt) def _add(self, other): """See docstring of SeqBase._add""" if isinstance(other, SeqPer): per1, lper1 = self.periodical, self.period per2, lper2 = other.periodical, other.period per_length = lcm(lper1, lper2) new_per = [] for x in range(per_length): ele1 = per1[x % lper1] ele2 = per2[x % lper2] new_per.append(ele1 + ele2) start, stop = self._intersect_interval(other) return SeqPer(new_per, (self.variables[0], start, stop)) def _mul(self, other): """See docstring of SeqBase._mul""" if isinstance(other, SeqPer): per1, lper1 = self.periodical, self.period per2, lper2 = other.periodical, other.period per_length = lcm(lper1, lper2) new_per = [] for x in range(per_length): ele1 = per1[x % lper1] ele2 = per2[x % lper2] new_per.append(ele1 * ele2) start, stop = self._intersect_interval(other) return SeqPer(new_per, (self.variables[0], start, stop)) def coeff_mul(self, coeff): """See docstring of SeqBase.coeff_mul""" coeff = sympify(coeff) per = [x * coeff for x in self.periodical] return SeqPer(per, self.args[1]) class SeqFormula(SeqExpr): """Represents sequence based on a formula. Elements are generated using a formula. Examples ======== >>> from sympy import SeqFormula, oo, Symbol >>> n = Symbol('n') >>> s = SeqFormula(n**2, (n, 0, 5)) >>> s.formula n**2 For value at a particular point >>> s.coeff(3) 9 supports slicing >>> s[:] [0, 1, 4, 9, 16, 25] iterable >>> list(s) [0, 1, 4, 9, 16, 25] sequence starts from negative infinity >>> SeqFormula(n**2, (-oo, 0))[0:6] [0, 1, 4, 9, 16, 25] See Also ======== sympy.series.sequences.SeqPer """ def __new__(cls, formula, limits=None): formula = sympify(formula) def _find_x(formula): free = formula.free_symbols if len(formula.free_symbols) == 1: return free.pop() elif len(formula.free_symbols) == 0: return Dummy('k') else: raise ValueError( " specify dummy variables for %s. If the formula contains" " more than one free symbol, a dummy variable should be" " supplied explicitly e.g., SeqFormula(m*n**2, (n, 0, 5))" % formula) x, start, stop = None, None, None if limits is None: x, start, stop = _find_x(formula), 0, S.Infinity if is_sequence(limits, Tuple): if len(limits) == 3: x, start, stop = limits elif len(limits) == 2: x = _find_x(formula) start, stop = limits if not isinstance(x, (Symbol, Idx)) or start is None or stop is None: raise ValueError('Invalid limits given: %s' % str(limits)) if start is S.NegativeInfinity and stop is S.Infinity: raise ValueError("Both the start and end value" "cannot be unbounded") limits = sympify((x, start, stop)) if Interval(limits[1], limits[2]) is S.EmptySet: return S.EmptySequence return Basic.__new__(cls, formula, limits) @property def formula(self): return self.gen def _eval_coeff(self, pt): d = self.variables[0] return self.formula.subs(d, pt) def _add(self, other): """See docstring of SeqBase._add""" if isinstance(other, SeqFormula): form1, v1 = self.formula, self.variables[0] form2, v2 = other.formula, other.variables[0] formula = form1 + form2.subs(v2, v1) start, stop = self._intersect_interval(other) return SeqFormula(formula, (v1, start, stop)) def _mul(self, other): """See docstring of SeqBase._mul""" if isinstance(other, SeqFormula): form1, v1 = self.formula, self.variables[0] form2, v2 = other.formula, other.variables[0] formula = form1 * form2.subs(v2, v1) start, stop = self._intersect_interval(other) return SeqFormula(formula, (v1, start, stop)) def coeff_mul(self, coeff): """See docstring of SeqBase.coeff_mul""" coeff = sympify(coeff) formula = self.formula * coeff return SeqFormula(formula, self.args[1]) def sequence(seq, limits=None): """Returns appropriate sequence object. If ``seq`` is a sympy sequence, returns :class:`SeqPer` object otherwise returns :class:`SeqFormula` object. Examples ======== >>> from sympy import sequence, SeqPer, SeqFormula >>> from sympy.abc import n >>> sequence(n**2, (n, 0, 5)) SeqFormula(n**2, (n, 0, 5)) >>> sequence((1, 2, 3), (n, 0, 5)) SeqPer((1, 2, 3), (n, 0, 5)) See Also ======== sympy.series.sequences.SeqPer sympy.series.sequences.SeqFormula """ seq = sympify(seq) if is_sequence(seq, Tuple): return SeqPer(seq, limits) else: return SeqFormula(seq, limits) ############################################################################### # OPERATIONS # ############################################################################### class SeqExprOp(SeqBase): """Base class for operations on sequences. Examples ======== >>> from sympy.series.sequences import SeqExprOp, sequence >>> from sympy.abc import n >>> s1 = sequence(n**2, (n, 0, 10)) >>> s2 = sequence((1, 2, 3), (n, 5, 10)) >>> s = SeqExprOp(s1, s2) >>> s.gen (n**2, (1, 2, 3)) >>> s.interval Interval(5, 10) >>> s.length 6 See Also ======== sympy.series.sequences.SeqAdd sympy.series.sequences.SeqMul """ @property def gen(self): """Generator for the sequence. returns a tuple of generators of all the argument sequences. """ return tuple(a.gen for a in self.args) @property def interval(self): """Sequence is defined on the intersection of all the intervals of respective sequences """ return Intersection(a.interval for a in self.args) @property def start(self): return self.interval.inf @property def stop(self): return self.interval.sup @property def variables(self): """Cumulative of all the bound variables""" return tuple(flatten([a.variables for a in self.args])) @property def length(self): return self.stop - self.start + 1 class SeqAdd(SeqExprOp): """Represents term-wise addition of sequences. Rules: * The interval on which sequence is defined is the intersection of respective intervals of sequences. * Anything + :class:`EmptySequence` remains unchanged. * Other rules are defined in ``_add`` methods of sequence classes. Examples ======== >>> from sympy import S, oo, SeqAdd, SeqPer, SeqFormula >>> from sympy.abc import n >>> SeqAdd(SeqPer((1, 2), (n, 0, oo)), S.EmptySequence) SeqPer((1, 2), (n, 0, oo)) >>> SeqAdd(SeqPer((1, 2), (n, 0, 5)), SeqPer((1, 2), (n, 6, 10))) EmptySequence() >>> SeqAdd(SeqPer((1, 2), (n, 0, oo)), SeqFormula(n**2, (n, 0, oo))) SeqAdd(SeqFormula(n**2, (n, 0, oo)), SeqPer((1, 2), (n, 0, oo))) >>> SeqAdd(SeqFormula(n**3), SeqFormula(n**2)) SeqFormula(n**3 + n**2, (n, 0, oo)) See Also ======== sympy.series.sequences.SeqMul """ def __new__(cls, *args, **kwargs): evaluate = kwargs.get('evaluate', global_evaluate[0]) # flatten inputs args = list(args) # adapted from sympy.sets.sets.Union def _flatten(arg): if isinstance(arg, SeqBase): if isinstance(arg, SeqAdd): return sum(map(_flatten, arg.args), []) else: return [arg] if iterable(arg): return sum(map(_flatten, arg), []) raise TypeError("Input must be Sequences or " " iterables of Sequences") args = _flatten(args) args = [a for a in args if a is not S.EmptySequence] # Addition of no sequences is EmptySequence if not args: return S.EmptySequence if Intersection(a.interval for a in args) is S.EmptySet: return S.EmptySequence # reduce using known rules if evaluate: return SeqAdd.reduce(args) args = list(ordered(args, SeqBase._start_key)) return Basic.__new__(cls, *args) @staticmethod def reduce(args): """Simplify :class:`SeqAdd` using known rules. Iterates through all pairs and ask the constituent sequences if they can simplify themselves with any other constituent. Notes ===== adapted from ``Union.reduce`` """ new_args = True while(new_args): for id1, s in enumerate(args): new_args = False for id2, t in enumerate(args): if id1 == id2: continue new_seq = s._add(t) # This returns None if s does not know how to add # with t. Returns the newly added sequence otherwise if new_seq is not None: new_args = [a for a in args if a not in (s, t)] new_args.append(new_seq) break if new_args: args = new_args break if len(args) == 1: return args.pop() else: return SeqAdd(args, evaluate=False) def _eval_coeff(self, pt): """adds up the coefficients of all the sequences at point pt""" return sum(a.coeff(pt) for a in self.args) class SeqMul(SeqExprOp): r"""Represents term-wise multiplication of sequences. Handles multiplication of sequences only. For multiplication with other objects see :func:`SeqBase.coeff_mul`. Rules: * The interval on which sequence is defined is the intersection of respective intervals of sequences. * Anything \* :class:`EmptySequence` returns :class:`EmptySequence`. * Other rules are defined in ``_mul`` methods of sequence classes. Examples ======== >>> from sympy import S, oo, SeqMul, SeqPer, SeqFormula >>> from sympy.abc import n >>> SeqMul(SeqPer((1, 2), (n, 0, oo)), S.EmptySequence) EmptySequence() >>> SeqMul(SeqPer((1, 2), (n, 0, 5)), SeqPer((1, 2), (n, 6, 10))) EmptySequence() >>> SeqMul(SeqPer((1, 2), (n, 0, oo)), SeqFormula(n**2)) SeqMul(SeqFormula(n**2, (n, 0, oo)), SeqPer((1, 2), (n, 0, oo))) >>> SeqMul(SeqFormula(n**3), SeqFormula(n**2)) SeqFormula(n**5, (n, 0, oo)) See Also ======== sympy.series.sequences.SeqAdd """ def __new__(cls, *args, **kwargs): evaluate = kwargs.get('evaluate', global_evaluate[0]) # flatten inputs args = list(args) # adapted from sympy.sets.sets.Union def _flatten(arg): if isinstance(arg, SeqBase): if isinstance(arg, SeqMul): return sum(map(_flatten, arg.args), []) else: return [arg] elif iterable(arg): return sum(map(_flatten, arg), []) raise TypeError("Input must be Sequences or " " iterables of Sequences") args = _flatten(args) # Multiplication of no sequences is EmptySequence if not args: return S.EmptySequence if Intersection(a.interval for a in args) is S.EmptySet: return S.EmptySequence # reduce using known rules if evaluate: return SeqMul.reduce(args) args = list(ordered(args, SeqBase._start_key)) return Basic.__new__(cls, *args) @staticmethod def reduce(args): """Simplify a :class:`SeqMul` using known rules. Iterates through all pairs and ask the constituent sequences if they can simplify themselves with any other constituent. Notes ===== adapted from ``Union.reduce`` """ new_args = True while(new_args): for id1, s in enumerate(args): new_args = False for id2, t in enumerate(args): if id1 == id2: continue new_seq = s._mul(t) # This returns None if s does not know how to multiply # with t. Returns the newly multiplied sequence otherwise if new_seq is not None: new_args = [a for a in args if a not in (s, t)] new_args.append(new_seq) break if new_args: args = new_args break if len(args) == 1: return args.pop() else: return SeqMul(args, evaluate=False) def _eval_coeff(self, pt): """multiplies the coefficients of all the sequences at point pt""" val = 1 for a in self.args: val *= a.coeff(pt) return val
wxgeo/geophar
wxgeometrie/sympy/series/sequences.py
Python
gpl-2.0
29,580
from functools import update_wrapper, wraps from unittest import TestCase from django.contrib.admin.views.decorators import staff_member_required from django.contrib.auth.decorators import ( login_required, permission_required, user_passes_test, ) from django.http import HttpRequest, HttpResponse, HttpResponseNotAllowed from django.middleware.clickjacking import XFrameOptionsMiddleware from django.test import SimpleTestCase from django.utils.decorators import method_decorator from django.utils.functional import keep_lazy, keep_lazy_text, lazy from django.utils.safestring import mark_safe from django.views.decorators.cache import ( cache_control, cache_page, never_cache, ) from django.views.decorators.clickjacking import ( xframe_options_deny, xframe_options_exempt, xframe_options_sameorigin, ) from django.views.decorators.http import ( condition, require_GET, require_http_methods, require_POST, require_safe, ) from django.views.decorators.vary import vary_on_cookie, vary_on_headers def fully_decorated(request): """Expected __doc__""" return HttpResponse('<html><body>dummy</body></html>') fully_decorated.anything = "Expected __dict__" def compose(*functions): # compose(f, g)(*args, **kwargs) == f(g(*args, **kwargs)) functions = list(reversed(functions)) def _inner(*args, **kwargs): result = functions[0](*args, **kwargs) for f in functions[1:]: result = f(result) return result return _inner full_decorator = compose( # django.views.decorators.http require_http_methods(["GET"]), require_GET, require_POST, require_safe, condition(lambda r: None, lambda r: None), # django.views.decorators.vary vary_on_headers('Accept-language'), vary_on_cookie, # django.views.decorators.cache cache_page(60 * 15), cache_control(private=True), never_cache, # django.contrib.auth.decorators # Apply user_passes_test twice to check #9474 user_passes_test(lambda u: True), login_required, permission_required('change_world'), # django.contrib.admin.views.decorators staff_member_required, # django.utils.functional keep_lazy(HttpResponse), keep_lazy_text, lazy, # django.utils.safestring mark_safe, ) fully_decorated = full_decorator(fully_decorated) class DecoratorsTest(TestCase): def test_attributes(self): """ Built-in decorators set certain attributes of the wrapped function. """ self.assertEqual(fully_decorated.__name__, 'fully_decorated') self.assertEqual(fully_decorated.__doc__, 'Expected __doc__') self.assertEqual(fully_decorated.__dict__['anything'], 'Expected __dict__') def test_user_passes_test_composition(self): """ The user_passes_test decorator can be applied multiple times (#9474). """ def test1(user): user.decorators_applied.append('test1') return True def test2(user): user.decorators_applied.append('test2') return True def callback(request): return request.user.decorators_applied callback = user_passes_test(test1)(callback) callback = user_passes_test(test2)(callback) class DummyUser: pass class DummyRequest: pass request = DummyRequest() request.user = DummyUser() request.user.decorators_applied = [] response = callback(request) self.assertEqual(response, ['test2', 'test1']) def test_cache_page(self): def my_view(request): return "response" my_view_cached = cache_page(123)(my_view) self.assertEqual(my_view_cached(HttpRequest()), "response") my_view_cached2 = cache_page(123, key_prefix="test")(my_view) self.assertEqual(my_view_cached2(HttpRequest()), "response") def test_require_safe_accepts_only_safe_methods(self): """ Test for the require_safe decorator. A view returns either a response or an exception. Refs #15637. """ def my_view(request): return HttpResponse("OK") my_safe_view = require_safe(my_view) request = HttpRequest() request.method = 'GET' self.assertIsInstance(my_safe_view(request), HttpResponse) request.method = 'HEAD' self.assertIsInstance(my_safe_view(request), HttpResponse) request.method = 'POST' self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed) request.method = 'PUT' self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed) request.method = 'DELETE' self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed) # For testing method_decorator, a decorator that assumes a single argument. # We will get type arguments if there is a mismatch in the number of arguments. def simple_dec(func): def wrapper(arg): return func("test:" + arg) return wraps(func)(wrapper) simple_dec_m = method_decorator(simple_dec) # For testing method_decorator, two decorators that add an attribute to the function def myattr_dec(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) wrapper.myattr = True return wrapper myattr_dec_m = method_decorator(myattr_dec) def myattr2_dec(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) wrapper.myattr2 = True return wrapper myattr2_dec_m = method_decorator(myattr2_dec) class ClsDec: def __init__(self, myattr): self.myattr = myattr def __call__(self, f): def wrapped(): return f() and self.myattr return update_wrapper(wrapped, f) class MethodDecoratorTests(SimpleTestCase): """ Tests for method_decorator """ def test_preserve_signature(self): class Test: @simple_dec_m def say(self, arg): return arg self.assertEqual("test:hello", Test().say("hello")) def test_preserve_attributes(self): # Sanity check myattr_dec and myattr2_dec @myattr_dec def func(): pass self.assertIs(getattr(func, 'myattr', False), True) @myattr2_dec def func(): pass self.assertIs(getattr(func, 'myattr2', False), True) @myattr_dec @myattr2_dec def func(): pass self.assertIs(getattr(func, 'myattr', False), True) self.assertIs(getattr(func, 'myattr2', False), False) # Decorate using method_decorator() on the method. class TestPlain: @myattr_dec_m @myattr2_dec_m def method(self): "A method" pass # Decorate using method_decorator() on both the class and the method. # The decorators applied to the methods are applied before the ones # applied to the class. @method_decorator(myattr_dec_m, "method") class TestMethodAndClass: @method_decorator(myattr2_dec_m) def method(self): "A method" pass # Decorate using an iterable of function decorators. @method_decorator((myattr_dec, myattr2_dec), 'method') class TestFunctionIterable: def method(self): "A method" pass # Decorate using an iterable of method decorators. decorators = (myattr_dec_m, myattr2_dec_m) @method_decorator(decorators, "method") class TestMethodIterable: def method(self): "A method" pass tests = (TestPlain, TestMethodAndClass, TestFunctionIterable, TestMethodIterable) for Test in tests: with self.subTest(Test=Test): self.assertIs(getattr(Test().method, 'myattr', False), True) self.assertIs(getattr(Test().method, 'myattr2', False), True) self.assertIs(getattr(Test.method, 'myattr', False), True) self.assertIs(getattr(Test.method, 'myattr2', False), True) self.assertEqual(Test.method.__doc__, 'A method') self.assertEqual(Test.method.__name__, 'method') def test_new_attribute(self): """A decorator that sets a new attribute on the method.""" def decorate(func): func.x = 1 return func class MyClass: @method_decorator(decorate) def method(self): return True obj = MyClass() self.assertEqual(obj.method.x, 1) self.assertIs(obj.method(), True) def test_bad_iterable(self): decorators = {myattr_dec_m, myattr2_dec_m} msg = "'set' object is not subscriptable" with self.assertRaisesMessage(TypeError, msg): @method_decorator(decorators, "method") class TestIterable: def method(self): "A method" pass # Test for argumented decorator def test_argumented(self): class Test: @method_decorator(ClsDec(False)) def method(self): return True self.assertIs(Test().method(), False) def test_descriptors(self): def original_dec(wrapped): def _wrapped(arg): return wrapped(arg) return _wrapped method_dec = method_decorator(original_dec) class bound_wrapper: def __init__(self, wrapped): self.wrapped = wrapped self.__name__ = wrapped.__name__ def __call__(self, arg): return self.wrapped(arg) def __get__(self, instance, cls=None): return self class descriptor_wrapper: def __init__(self, wrapped): self.wrapped = wrapped self.__name__ = wrapped.__name__ def __get__(self, instance, cls=None): return bound_wrapper(self.wrapped.__get__(instance, cls)) class Test: @method_dec @descriptor_wrapper def method(self, arg): return arg self.assertEqual(Test().method(1), 1) def test_class_decoration(self): """ @method_decorator can be used to decorate a class and its methods. """ def deco(func): def _wrapper(*args, **kwargs): return True return _wrapper @method_decorator(deco, name="method") class Test: def method(self): return False self.assertTrue(Test().method()) def test_tuple_of_decorators(self): """ @method_decorator can accept a tuple of decorators. """ def add_question_mark(func): def _wrapper(*args, **kwargs): return func(*args, **kwargs) + "?" return _wrapper def add_exclamation_mark(func): def _wrapper(*args, **kwargs): return func(*args, **kwargs) + "!" return _wrapper # The order should be consistent with the usual order in which # decorators are applied, e.g. # @add_exclamation_mark # @add_question_mark # def func(): # ... decorators = (add_exclamation_mark, add_question_mark) @method_decorator(decorators, name="method") class TestFirst: def method(self): return "hello world" class TestSecond: @method_decorator(decorators) def method(self): return "hello world" self.assertEqual(TestFirst().method(), "hello world?!") self.assertEqual(TestSecond().method(), "hello world?!") def test_invalid_non_callable_attribute_decoration(self): """ @method_decorator on a non-callable attribute raises an error. """ msg = ( "Cannot decorate 'prop' as it isn't a callable attribute of " "<class 'Test'> (1)" ) with self.assertRaisesMessage(TypeError, msg): @method_decorator(lambda: None, name="prop") class Test: prop = 1 @classmethod def __module__(cls): return "tests" def test_invalid_method_name_to_decorate(self): """ @method_decorator on a nonexistent method raises an error. """ msg = ( "The keyword argument `name` must be the name of a method of the " "decorated class: <class 'Test'>. Got 'nonexistent_method' instead" ) with self.assertRaisesMessage(ValueError, msg): @method_decorator(lambda: None, name='nonexistent_method') class Test: @classmethod def __module__(cls): return "tests" class XFrameOptionsDecoratorsTests(TestCase): """ Tests for the X-Frame-Options decorators. """ def test_deny_decorator(self): """ Ensures @xframe_options_deny properly sets the X-Frame-Options header. """ @xframe_options_deny def a_view(request): return HttpResponse() r = a_view(HttpRequest()) self.assertEqual(r.headers['X-Frame-Options'], 'DENY') def test_sameorigin_decorator(self): """ Ensures @xframe_options_sameorigin properly sets the X-Frame-Options header. """ @xframe_options_sameorigin def a_view(request): return HttpResponse() r = a_view(HttpRequest()) self.assertEqual(r.headers['X-Frame-Options'], 'SAMEORIGIN') def test_exempt_decorator(self): """ Ensures @xframe_options_exempt properly instructs the XFrameOptionsMiddleware to NOT set the header. """ @xframe_options_exempt def a_view(request): return HttpResponse() req = HttpRequest() resp = a_view(req) self.assertIsNone(resp.get('X-Frame-Options', None)) self.assertTrue(resp.xframe_options_exempt) # Since the real purpose of the exempt decorator is to suppress # the middleware's functionality, let's make sure it actually works... r = XFrameOptionsMiddleware(a_view)(req) self.assertIsNone(r.get('X-Frame-Options', None)) class NeverCacheDecoratorTest(SimpleTestCase): def test_never_cache_decorator(self): @never_cache def a_view(request): return HttpResponse() r = a_view(HttpRequest()) self.assertEqual( set(r.headers['Cache-Control'].split(', ')), {'max-age=0', 'no-cache', 'no-store', 'must-revalidate', 'private'}, ) def test_never_cache_decorator_http_request(self): class MyClass: @never_cache def a_view(self, request): return HttpResponse() msg = ( "never_cache didn't receive an HttpRequest. If you are decorating " "a classmethod, be sure to use @method_decorator." ) with self.assertRaisesMessage(TypeError, msg): MyClass().a_view(HttpRequest()) class CacheControlDecoratorTest(SimpleTestCase): def test_cache_control_decorator_http_request(self): class MyClass: @cache_control(a='b') def a_view(self, request): return HttpResponse() msg = ( "cache_control didn't receive an HttpRequest. If you are " "decorating a classmethod, be sure to use @method_decorator." ) with self.assertRaisesMessage(TypeError, msg): MyClass().a_view(HttpRequest())
atul-bhouraskar/django
tests/decorators/tests.py
Python
bsd-3-clause
15,914
""" The main purpose of this module is to expose LinkCollector.collect_links(). """ import cgi import functools import itertools import logging import mimetypes import os import re from collections import OrderedDict from pip._vendor import html5lib, requests from pip._vendor.distlib.compat import unescape from pip._vendor.requests.exceptions import RetryError, SSLError from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._vendor.six.moves.urllib import request as urllib_request from pip._internal.exceptions import NetworkConnectionError from pip._internal.models.link import Link from pip._internal.models.search_scope import SearchScope from pip._internal.network.utils import raise_for_status from pip._internal.utils.filetypes import ARCHIVE_EXTENSIONS from pip._internal.utils.misc import pairwise, redact_auth_from_url from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import path_to_url, url_to_path from pip._internal.vcs import is_url, vcs if MYPY_CHECK_RUNNING: from optparse import Values from typing import ( Callable, Iterable, List, MutableMapping, Optional, Protocol, Sequence, Tuple, TypeVar, Union, ) import xml.etree.ElementTree from pip._vendor.requests import Response from pip._internal.network.session import PipSession HTMLElement = xml.etree.ElementTree.Element ResponseHeaders = MutableMapping[str, str] # Used in the @lru_cache polyfill. F = TypeVar('F') class LruCache(Protocol): def __call__(self, maxsize=None): # type: (Optional[int]) -> Callable[[F], F] raise NotImplementedError logger = logging.getLogger(__name__) # Fallback to noop_lru_cache in Python 2 # TODO: this can be removed when python 2 support is dropped! def noop_lru_cache(maxsize=None): # type: (Optional[int]) -> Callable[[F], F] def _wrapper(f): # type: (F) -> F return f return _wrapper _lru_cache = getattr(functools, "lru_cache", noop_lru_cache) # type: LruCache def _match_vcs_scheme(url): # type: (str) -> Optional[str] """Look for VCS schemes in the URL. Returns the matched VCS scheme, or None if there's no match. """ for scheme in vcs.schemes: if url.lower().startswith(scheme) and url[len(scheme)] in '+:': return scheme return None def _is_url_like_archive(url): # type: (str) -> bool """Return whether the URL looks like an archive. """ filename = Link(url).filename for bad_ext in ARCHIVE_EXTENSIONS: if filename.endswith(bad_ext): return True return False class _NotHTML(Exception): def __init__(self, content_type, request_desc): # type: (str, str) -> None super(_NotHTML, self).__init__(content_type, request_desc) self.content_type = content_type self.request_desc = request_desc def _ensure_html_header(response): # type: (Response) -> None """Check the Content-Type header to ensure the response contains HTML. Raises `_NotHTML` if the content type is not text/html. """ content_type = response.headers.get("Content-Type", "") if not content_type.lower().startswith("text/html"): raise _NotHTML(content_type, response.request.method) class _NotHTTP(Exception): pass def _ensure_html_response(url, session): # type: (str, PipSession) -> None """Send a HEAD request to the URL, and ensure the response contains HTML. Raises `_NotHTTP` if the URL is not available for a HEAD request, or `_NotHTML` if the content type is not text/html. """ scheme, netloc, path, query, fragment = urllib_parse.urlsplit(url) if scheme not in {'http', 'https'}: raise _NotHTTP() resp = session.head(url, allow_redirects=True) raise_for_status(resp) _ensure_html_header(resp) def _get_html_response(url, session): # type: (str, PipSession) -> Response """Access an HTML page with GET, and return the response. This consists of three parts: 1. If the URL looks suspiciously like an archive, send a HEAD first to check the Content-Type is HTML, to avoid downloading a large file. Raise `_NotHTTP` if the content type cannot be determined, or `_NotHTML` if it is not HTML. 2. Actually perform the request. Raise HTTP exceptions on network failures. 3. Check the Content-Type header to make sure we got HTML, and raise `_NotHTML` otherwise. """ if _is_url_like_archive(url): _ensure_html_response(url, session=session) logger.debug('Getting page %s', redact_auth_from_url(url)) resp = session.get( url, headers={ "Accept": "text/html", # We don't want to blindly returned cached data for # /simple/, because authors generally expecting that # twine upload && pip install will function, but if # they've done a pip install in the last ~10 minutes # it won't. Thus by setting this to zero we will not # blindly use any cached data, however the benefit of # using max-age=0 instead of no-cache, is that we will # still support conditional requests, so we will still # minimize traffic sent in cases where the page hasn't # changed at all, we will just always incur the round # trip for the conditional GET now instead of only # once per 10 minutes. # For more information, please see pypa/pip#5670. "Cache-Control": "max-age=0", }, ) raise_for_status(resp) # The check for archives above only works if the url ends with # something that looks like an archive. However that is not a # requirement of an url. Unless we issue a HEAD request on every # url we cannot know ahead of time for sure if something is HTML # or not. However we can check after we've downloaded it. _ensure_html_header(resp) return resp def _get_encoding_from_headers(headers): # type: (ResponseHeaders) -> Optional[str] """Determine if we have any encoding information in our headers. """ if headers and "Content-Type" in headers: content_type, params = cgi.parse_header(headers["Content-Type"]) if "charset" in params: return params['charset'] return None def _determine_base_url(document, page_url): # type: (HTMLElement, str) -> str """Determine the HTML document's base URL. This looks for a ``<base>`` tag in the HTML document. If present, its href attribute denotes the base URL of anchor tags in the document. If there is no such tag (or if it does not have a valid href attribute), the HTML file's URL is used as the base URL. :param document: An HTML document representation. The current implementation expects the result of ``html5lib.parse()``. :param page_url: The URL of the HTML document. """ for base in document.findall(".//base"): href = base.get("href") if href is not None: return href return page_url def _clean_url_path_part(part): # type: (str) -> str """ Clean a "part" of a URL path (i.e. after splitting on "@" characters). """ # We unquote prior to quoting to make sure nothing is double quoted. return urllib_parse.quote(urllib_parse.unquote(part)) def _clean_file_url_path(part): # type: (str) -> str """ Clean the first part of a URL path that corresponds to a local filesystem path (i.e. the first part after splitting on "@" characters). """ # We unquote prior to quoting to make sure nothing is double quoted. # Also, on Windows the path part might contain a drive letter which # should not be quoted. On Linux where drive letters do not # exist, the colon should be quoted. We rely on urllib.request # to do the right thing here. return urllib_request.pathname2url(urllib_request.url2pathname(part)) # percent-encoded: / _reserved_chars_re = re.compile('(@|%2F)', re.IGNORECASE) def _clean_url_path(path, is_local_path): # type: (str, bool) -> str """ Clean the path portion of a URL. """ if is_local_path: clean_func = _clean_file_url_path else: clean_func = _clean_url_path_part # Split on the reserved characters prior to cleaning so that # revision strings in VCS URLs are properly preserved. parts = _reserved_chars_re.split(path) cleaned_parts = [] for to_clean, reserved in pairwise(itertools.chain(parts, [''])): cleaned_parts.append(clean_func(to_clean)) # Normalize %xx escapes (e.g. %2f -> %2F) cleaned_parts.append(reserved.upper()) return ''.join(cleaned_parts) def _clean_link(url): # type: (str) -> str """ Make sure a link is fully quoted. For example, if ' ' occurs in the URL, it will be replaced with "%20", and without double-quoting other characters. """ # Split the URL into parts according to the general structure # `scheme://netloc/path;parameters?query#fragment`. result = urllib_parse.urlparse(url) # If the netloc is empty, then the URL refers to a local filesystem path. is_local_path = not result.netloc path = _clean_url_path(result.path, is_local_path=is_local_path) return urllib_parse.urlunparse(result._replace(path=path)) def _create_link_from_element( anchor, # type: HTMLElement page_url, # type: str base_url, # type: str ): # type: (...) -> Optional[Link] """ Convert an anchor element in a simple repository page to a Link. """ href = anchor.get("href") if not href: return None url = _clean_link(urllib_parse.urljoin(base_url, href)) pyrequire = anchor.get('data-requires-python') pyrequire = unescape(pyrequire) if pyrequire else None yanked_reason = anchor.get('data-yanked') if yanked_reason: # This is a unicode string in Python 2 (and 3). yanked_reason = unescape(yanked_reason) link = Link( url, comes_from=page_url, requires_python=pyrequire, yanked_reason=yanked_reason, ) return link class CacheablePageContent(object): def __init__(self, page): # type: (HTMLPage) -> None assert page.cache_link_parsing self.page = page def __eq__(self, other): # type: (object) -> bool return (isinstance(other, type(self)) and self.page.url == other.page.url) def __hash__(self): # type: () -> int return hash(self.page.url) def with_cached_html_pages( fn, # type: Callable[[HTMLPage], Iterable[Link]] ): # type: (...) -> Callable[[HTMLPage], List[Link]] """ Given a function that parses an Iterable[Link] from an HTMLPage, cache the function's result (keyed by CacheablePageContent), unless the HTMLPage `page` has `page.cache_link_parsing == False`. """ @_lru_cache(maxsize=None) def wrapper(cacheable_page): # type: (CacheablePageContent) -> List[Link] return list(fn(cacheable_page.page)) @functools.wraps(fn) def wrapper_wrapper(page): # type: (HTMLPage) -> List[Link] if page.cache_link_parsing: return wrapper(CacheablePageContent(page)) return list(fn(page)) return wrapper_wrapper @with_cached_html_pages def parse_links(page): # type: (HTMLPage) -> Iterable[Link] """ Parse an HTML document, and yield its anchor elements as Link objects. """ document = html5lib.parse( page.content, transport_encoding=page.encoding, namespaceHTMLElements=False, ) url = page.url base_url = _determine_base_url(document, url) for anchor in document.findall(".//a"): link = _create_link_from_element( anchor, page_url=url, base_url=base_url, ) if link is None: continue yield link class HTMLPage(object): """Represents one page, along with its URL""" def __init__( self, content, # type: bytes encoding, # type: Optional[str] url, # type: str cache_link_parsing=True, # type: bool ): # type: (...) -> None """ :param encoding: the encoding to decode the given content. :param url: the URL from which the HTML was downloaded. :param cache_link_parsing: whether links parsed from this page's url should be cached. PyPI index urls should have this set to False, for example. """ self.content = content self.encoding = encoding self.url = url self.cache_link_parsing = cache_link_parsing def __str__(self): # type: () -> str return redact_auth_from_url(self.url) def _handle_get_page_fail( link, # type: Link reason, # type: Union[str, Exception] meth=None # type: Optional[Callable[..., None]] ): # type: (...) -> None if meth is None: meth = logger.debug meth("Could not fetch URL %s: %s - skipping", link, reason) def _make_html_page(response, cache_link_parsing=True): # type: (Response, bool) -> HTMLPage encoding = _get_encoding_from_headers(response.headers) return HTMLPage( response.content, encoding=encoding, url=response.url, cache_link_parsing=cache_link_parsing) def _get_html_page(link, session=None): # type: (Link, Optional[PipSession]) -> Optional[HTMLPage] if session is None: raise TypeError( "_get_html_page() missing 1 required keyword argument: 'session'" ) url = link.url.split('#', 1)[0] # Check for VCS schemes that do not support lookup as web pages. vcs_scheme = _match_vcs_scheme(url) if vcs_scheme: logger.warning('Cannot look at %s URL %s because it does not support ' 'lookup as web pages.', vcs_scheme, link) return None # Tack index.html onto file:// URLs that point to directories scheme, _, path, _, _, _ = urllib_parse.urlparse(url) if (scheme == 'file' and os.path.isdir(urllib_request.url2pathname(path))): # add trailing slash if not present so urljoin doesn't trim # final segment if not url.endswith('/'): url += '/' url = urllib_parse.urljoin(url, 'index.html') logger.debug(' file: URL is directory, getting %s', url) try: resp = _get_html_response(url, session=session) except _NotHTTP: logger.warning( 'Skipping page %s because it looks like an archive, and cannot ' 'be checked by a HTTP HEAD request.', link, ) except _NotHTML as exc: logger.warning( 'Skipping page %s because the %s request got Content-Type: %s.' 'The only supported Content-Type is text/html', link, exc.request_desc, exc.content_type, ) except NetworkConnectionError as exc: _handle_get_page_fail(link, exc) except RetryError as exc: _handle_get_page_fail(link, exc) except SSLError as exc: reason = "There was a problem confirming the ssl certificate: " reason += str(exc) _handle_get_page_fail(link, reason, meth=logger.info) except requests.ConnectionError as exc: _handle_get_page_fail(link, "connection error: {}".format(exc)) except requests.Timeout: _handle_get_page_fail(link, "timed out") else: return _make_html_page(resp, cache_link_parsing=link.cache_link_parsing) return None def _remove_duplicate_links(links): # type: (Iterable[Link]) -> List[Link] """ Return a list of links, with duplicates removed and ordering preserved. """ # We preserve the ordering when removing duplicates because we can. return list(OrderedDict.fromkeys(links)) def group_locations(locations, expand_dir=False): # type: (Sequence[str], bool) -> Tuple[List[str], List[str]] """ Divide a list of locations into two groups: "files" (archives) and "urls." :return: A pair of lists (files, urls). """ files = [] urls = [] # puts the url for the given file path into the appropriate list def sort_path(path): # type: (str) -> None url = path_to_url(path) if mimetypes.guess_type(url, strict=False)[0] == 'text/html': urls.append(url) else: files.append(url) for url in locations: is_local_path = os.path.exists(url) is_file_url = url.startswith('file:') if is_local_path or is_file_url: if is_local_path: path = url else: path = url_to_path(url) if os.path.isdir(path): if expand_dir: path = os.path.realpath(path) for item in os.listdir(path): sort_path(os.path.join(path, item)) elif is_file_url: urls.append(url) else: logger.warning( "Path '%s' is ignored: it is a directory.", path, ) elif os.path.isfile(path): sort_path(path) else: logger.warning( "Url '%s' is ignored: it is neither a file " "nor a directory.", url, ) elif is_url(url): # Only add url with clear scheme urls.append(url) else: logger.warning( "Url '%s' is ignored. It is either a non-existing " "path or lacks a specific scheme.", url, ) return files, urls class CollectedLinks(object): """ Encapsulates the return value of a call to LinkCollector.collect_links(). The return value includes both URLs to project pages containing package links, as well as individual package Link objects collected from other sources. This info is stored separately as: (1) links from the configured file locations, (2) links from the configured find_links, and (3) urls to HTML project pages, as described by the PEP 503 simple repository API. """ def __init__( self, files, # type: List[Link] find_links, # type: List[Link] project_urls, # type: List[Link] ): # type: (...) -> None """ :param files: Links from file locations. :param find_links: Links from find_links. :param project_urls: URLs to HTML project pages, as described by the PEP 503 simple repository API. """ self.files = files self.find_links = find_links self.project_urls = project_urls class LinkCollector(object): """ Responsible for collecting Link objects from all configured locations, making network requests as needed. The class's main method is its collect_links() method. """ def __init__( self, session, # type: PipSession search_scope, # type: SearchScope ): # type: (...) -> None self.search_scope = search_scope self.session = session @classmethod def create(cls, session, options, suppress_no_index=False): # type: (PipSession, Values, bool) -> LinkCollector """ :param session: The Session to use to make requests. :param suppress_no_index: Whether to ignore the --no-index option when constructing the SearchScope object. """ index_urls = [options.index_url] + options.extra_index_urls if options.no_index and not suppress_no_index: logger.debug( 'Ignoring indexes: %s', ','.join(redact_auth_from_url(url) for url in index_urls), ) index_urls = [] # Make sure find_links is a list before passing to create(). find_links = options.find_links or [] search_scope = SearchScope.create( find_links=find_links, index_urls=index_urls, ) link_collector = LinkCollector( session=session, search_scope=search_scope, ) return link_collector @property def find_links(self): # type: () -> List[str] return self.search_scope.find_links def fetch_page(self, location): # type: (Link) -> Optional[HTMLPage] """ Fetch an HTML page containing package links. """ return _get_html_page(location, session=self.session) def collect_links(self, project_name): # type: (str) -> CollectedLinks """Find all available links for the given project name. :return: All the Link objects (unfiltered), as a CollectedLinks object. """ search_scope = self.search_scope index_locations = search_scope.get_index_urls_locations(project_name) index_file_loc, index_url_loc = group_locations(index_locations) fl_file_loc, fl_url_loc = group_locations( self.find_links, expand_dir=True, ) file_links = [ Link(url) for url in itertools.chain(index_file_loc, fl_file_loc) ] # We trust every directly linked archive in find_links find_link_links = [Link(url, '-f') for url in self.find_links] # We trust every url that the user has given us whether it was given # via --index-url or --find-links. # We want to filter out anything that does not have a secure origin. url_locations = [ link for link in itertools.chain( # Mark PyPI indices as "cache_link_parsing == False" -- this # will avoid caching the result of parsing the page for links. (Link(url, cache_link_parsing=False) for url in index_url_loc), (Link(url) for url in fl_url_loc), ) if self.session.is_secure_origin(link) ] url_locations = _remove_duplicate_links(url_locations) lines = [ '{} location(s) to search for versions of {}:'.format( len(url_locations), project_name, ), ] for link in url_locations: lines.append('* {}'.format(link)) logger.debug('\n'.join(lines)) return CollectedLinks( files=file_links, find_links=find_link_links, project_urls=url_locations, )
sserrot/champion_relationships
venv/Lib/site-packages/pip/_internal/index/collector.py
Python
mit
22,838
# Eve W-Space # Copyright (C) 2013 Andrew Austin and other contributors # # 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. An additional term under section # 7 of the GPL is included in the LICENSE file. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from django.db import models from django.contrib.auth.models import Group, User # Create your models here. class TeamspeakServer(models.Model): """Stores teamspeak server configuration.""" host = models.CharField(max_length=100) queryuser = models.CharField(max_length=100) querypass = models.CharField(max_length=100) queryport = models.IntegerField() voiceport = models.IntegerField() # If enforcegroups = True, any TS users who do not have a GroupMap entry will have no groups enforcegroups = models.BooleanField() # If enforceusers = True, any TS users without a Django user mapping will be removed enforeceusers = models.BooleanField() class GroupMap(models.Model): """Maps Django user groups to Teamspeak groups.""" tsserver = models.ForeignKey(TeamspeakServer, related_name="groupmaps") usergroup = models.ForeignKey(Group, related_name="teamspeakgroups") tsgroup = models.CharField(max_length=100)
djrscally/eve-wspace
evewspace/Teamspeak/models.py
Python
gpl-3.0
1,834
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. ## this functions are taken from the setuptools package (version 0.6c8) ## http://peak.telecommunity.com/DevCenter/PkgResources#parsing-utilities from __future__ import print_function import re from odoo.tools import pycompat component_re = re.compile(r'(\d+ | [a-z]+ | \.| -)', re.VERBOSE) replace = {'pre':'c', 'preview':'c','-':'final-','_':'final-','rc':'c','dev':'@','saas':'','~':''}.get def _parse_version_parts(s): for part in component_re.split(s): part = replace(part,part) if not part or part=='.': continue if part[:1] in '0123456789': yield part.zfill(8) # pad for numeric comparison else: yield '*'+part yield '*final' # ensure that alpha/beta/candidate are before final def parse_version(s): """Convert a version string to a chronologically-sortable key This is a rough cross between distutils' StrictVersion and LooseVersion; if you give it versions that would work with StrictVersion, then it behaves the same; otherwise it acts like a slightly-smarter LooseVersion. It is *possible* to create pathological version coding schemes that will fool this parser, but they should be very rare in practice. The returned value will be a tuple of strings. Numeric portions of the version are padded to 8 digits so they will compare numerically, but without relying on how numbers compare relative to strings. Dots are dropped, but dashes are retained. Trailing zeros between alpha segments or dashes are suppressed, so that e.g. "2.4.0" is considered the same as "2.4". Alphanumeric parts are lower-cased. The algorithm assumes that strings like "-" and any alpha string that alphabetically follows "final" represents a "patch level". So, "2.4-1" is assumed to be a branch or patch of "2.4", and therefore "2.4.1" is considered newer than "2.4-1", whic in turn is newer than "2.4". Strings like "a", "b", "c", "alpha", "beta", "candidate" and so on (that come before "final" alphabetically) are assumed to be pre-release versions, so that the version "2.4" is considered newer than "2.4a1". Finally, to handle miscellaneous cases, the strings "pre", "preview", and "rc" are treated as if they were "c", i.e. as though they were release candidates, and therefore are not as new as a version string that does not contain them. """ parts = [] for part in _parse_version_parts((s or '0.1').lower()): if part.startswith('*'): if part<'*final': # remove '-' before a prerelease tag while parts and parts[-1]=='*final-': parts.pop() # remove trailing zeros from each series of numeric parts while parts and parts[-1]=='00000000': parts.pop() parts.append(part) return tuple(parts) if __name__ == '__main__': def chk(lst, verbose=False): pvs = [] for v in lst: pv = parse_version(v) pvs.append(pv) if verbose: print(v, pv) for a, b in pycompat.izip(pvs, pvs[1:]): assert a < b, '%s < %s == %s' % (a, b, a < b) chk(('0', '4.2', '4.2.3.4', '5.0.0-alpha', '5.0.0-rc1', '5.0.0-rc1.1', '5.0.0_rc2', '5.0.0_rc3', '5.0.0'), False) chk(('5.0.0-0_rc3', '5.0.0-1dev', '5.0.0-1'), False)
Aravinthu/odoo
odoo/tools/parse_version.py
Python
agpl-3.0
3,532
from typing import NewType SomeType = NewType("SomeType", bytes) SomeType(b"va<caret>lue")
smmribeiro/intellij-community
python/testData/refactoring/introduceVariable/argumentToUnnamedParameter.py
Python
apache-2.0
90
#!/usr/bin/env python # # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest import math class test_vector_map(gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block() def tearDown (self): self.tb = None def test_reversing(self): # Chunk data in blocks of N and reverse the block contents. N = 5 src_data = range(0, 20) expected_result = [] for i in range(N-1, len(src_data), N): for j in range(0, N): expected_result.append(1.0*(i-j)) mapping = [list(reversed([(0, i) for i in range(0, N)]))] src = gr.vector_source_f(src_data, False, N) vmap = gr.vector_map(gr.sizeof_float, (N, ), mapping) dst = gr.vector_sink_f(N) self.tb.connect(src, vmap, dst) self.tb.run() result_data = list(dst.data()) self.assertEqual(expected_result, result_data) def test_vector_to_streams(self): # Split an input vector into N streams. N = 5 M = 20 src_data = range(0, M) expected_results = [] for n in range(0, N): expected_results.append(range(n, M, N)) mapping = [[(0, n)] for n in range(0, N)] src = gr.vector_source_f(src_data, False, N) vmap = gr.vector_map(gr.sizeof_float, (N, ), mapping) dsts = [gr.vector_sink_f(1) for n in range(0, N)] self.tb.connect(src, vmap) for n in range(0, N): self.tb.connect((vmap, n), dsts[n]) self.tb.run() for n in range(0, N): result_data = list(dsts[n].data()) self.assertEqual(expected_results[n], result_data) def test_interleaving(self): # Takes 3 streams (a, b and c) # Outputs 2 streams. # First (d) is interleaving of a and b. # Second (e) is interleaving of a and b and c. c is taken in # chunks of 2 which are reversed. A = (1, 2, 3, 4, 5) B = (11, 12, 13, 14, 15) C = (99, 98, 97, 96, 95, 94, 93, 92, 91, 90) expected_D = (1, 11, 2, 12, 3, 13, 4, 14, 5, 15) expected_E = (1, 11, 98, 99, 2, 12, 96, 97, 3, 13, 94, 95, 4, 14, 92, 93, 5, 15, 90, 91) mapping = [[(0, 0), (1, 0)], # mapping to produce D [(0, 0), (1, 0), (2, 1), (2, 0)], # mapping to produce E ] srcA = gr.vector_source_f(A, False, 1) srcB = gr.vector_source_f(B, False, 1) srcC = gr.vector_source_f(C, False, 2) vmap = gr.vector_map(gr.sizeof_int, (1, 1, 2), mapping) dstD = gr.vector_sink_f(2) dstE = gr.vector_sink_f(4) self.tb.connect(srcA, (vmap, 0)) self.tb.connect(srcB, (vmap, 1)) self.tb.connect(srcC, (vmap, 2)) self.tb.connect((vmap, 0), dstD) self.tb.connect((vmap, 1), dstE) self.tb.run() self.assertEqual(expected_D, dstD.data()) self.assertEqual(expected_E, dstE.data()) if __name__ == '__main__': gr_unittest.run(test_vector_map, "test_vector_map.xml")
manojgudi/sandhi
modules/gr36/gnuradio-core/src/python/gnuradio/gr/qa_vector_map.py
Python
gpl-3.0
3,870
# Copyright 2014 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from nova.api.openstack.compute.contrib import hypervisors from nova.tests.api.openstack.compute.contrib import test_hypervisors from nova.tests.api.openstack import fakes class ExtendedHypervisorsTest(test_hypervisors.HypervisorsTest): def setUp(self): super(ExtendedHypervisorsTest, self).setUp() self.ext_mgr.extensions['os-extended-hypervisors'] = True self.controller = hypervisors.HypervisorsController(self.ext_mgr) def test_view_hypervisor_detail_noservers(self): result = self.controller._view_hypervisor( test_hypervisors.TEST_HYPERS[0], True) self.assertEqual(result, dict( id=1, hypervisor_hostname="hyper1", vcpus=4, memory_mb=10 * 1024, local_gb=250, vcpus_used=2, memory_mb_used=5 * 1024, local_gb_used=125, hypervisor_type="xen", hypervisor_version=3, free_ram_mb=5 * 1024, free_disk_gb=125, current_workload=2, running_vms=2, cpu_info='cpu_info', disk_available_least=100, host_ip='1.1.1.1', service=dict(id=1, host='compute1'))) def test_detail(self): req = fakes.HTTPRequest.blank('/v2/fake/os-hypervisors/detail', use_admin_context=True) result = self.controller.detail(req) self.assertEqual(result, dict(hypervisors=[ dict(id=1, service=dict(id=1, host="compute1"), vcpus=4, memory_mb=10 * 1024, local_gb=250, vcpus_used=2, memory_mb_used=5 * 1024, local_gb_used=125, hypervisor_type="xen", hypervisor_version=3, hypervisor_hostname="hyper1", free_ram_mb=5 * 1024, free_disk_gb=125, current_workload=2, running_vms=2, cpu_info='cpu_info', disk_available_least=100, host_ip='1.1.1.1'), dict(id=2, service=dict(id=2, host="compute2"), vcpus=4, memory_mb=10 * 1024, local_gb=250, vcpus_used=2, memory_mb_used=5 * 1024, local_gb_used=125, hypervisor_type="xen", hypervisor_version=3, hypervisor_hostname="hyper2", free_ram_mb=5 * 1024, free_disk_gb=125, current_workload=2, running_vms=2, cpu_info='cpu_info', disk_available_least=100, host_ip='2.2.2.2')])) def test_show_withid(self): req = fakes.HTTPRequest.blank('/v2/fake/os-hypervisors/1') result = self.controller.show(req, '1') self.assertEqual(result, dict(hypervisor=dict( id=1, service=dict(id=1, host="compute1"), vcpus=4, memory_mb=10 * 1024, local_gb=250, vcpus_used=2, memory_mb_used=5 * 1024, local_gb_used=125, hypervisor_type="xen", hypervisor_version=3, hypervisor_hostname="hyper1", free_ram_mb=5 * 1024, free_disk_gb=125, current_workload=2, running_vms=2, cpu_info='cpu_info', disk_available_least=100, host_ip='1.1.1.1')))
eharney/nova
nova/tests/api/openstack/compute/contrib/test_extended_hypervisors.py
Python
apache-2.0
4,737
import os import sys import codecs from contextlib import contextmanager from itertools import repeat from functools import update_wrapper from .types import convert_type, IntRange, BOOL from .utils import make_str, make_default_short_help, echo from .exceptions import ClickException, UsageError, BadParameter, Abort, \ MissingParameter from .termui import prompt, confirm from .formatting import HelpFormatter, join_options from .parser import OptionParser, split_opt from .globals import push_context, pop_context from ._compat import PY2, isidentifier, iteritems, _check_for_unicode_literals _missing = object() SUBCOMMAND_METAVAR = 'COMMAND [ARGS]...' SUBCOMMANDS_METAVAR = 'COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]...' def _bashcomplete(cmd, prog_name, complete_var=None): """Internal handler for the bash completion support.""" if complete_var is None: complete_var = '_%s_COMPLETE' % (prog_name.replace('-', '_')).upper() complete_instr = os.environ.get(complete_var) if not complete_instr: return from ._bashcomplete import bashcomplete if bashcomplete(cmd, prog_name, complete_var, complete_instr): sys.exit(1) def batch(iterable, batch_size): return list(zip(*repeat(iter(iterable), batch_size))) def invoke_param_callback(callback, ctx, param, value): code = getattr(callback, '__code__', None) args = getattr(code, 'co_argcount', 3) if args < 3: # This will become a warning in Click 3.0: from warnings import warn warn(Warning('Invoked legacy parameter callback "%s". The new ' 'signature for such callbacks starting with ' 'click 2.0 is (ctx, param, value).' % callback), stacklevel=3) return callback(ctx, value) return callback(ctx, param, value) @contextmanager def augment_usage_errors(ctx, param=None): """Context manager that attaches extra information to exceptions that fly. """ try: yield except BadParameter as e: if e.ctx is None: e.ctx = ctx if param is not None and e.param is None: e.param = param raise except UsageError as e: if e.ctx is None: e.ctx = ctx raise def iter_params_for_processing(invocation_order, declaration_order): """Given a sequence of parameters in the order as should be considered for processing and an iterable of parameters that exist, this returns a list in the correct order as they should be processed. """ def sort_key(item): try: idx = invocation_order.index(item) except ValueError: idx = float('inf') return (not item.is_eager, idx) return sorted(declaration_order, key=sort_key) class Context(object): """The context is a special internal object that holds state relevant for the script execution at every single level. It's normally invisible to commands unless they opt-in to getting access to it. The context is useful as it can pass internal objects around and can control special execution features such as reading data from environment variables. A context can be used as context manager in which case it will call :meth:`close` on teardown. .. versionadded:: 2.0 Added the `resilient_parsing`, `help_option_names`, `token_normalize_func` parameters. .. versionadded:: 3.0 Added the `allow_extra_args` and `allow_interspersed_args` parameters. .. versionadded:: 4.0 Added the `color`, `ignore_unknown_options`, and `max_content_width` parameters. :param command: the command class for this context. :param parent: the parent context. :param info_name: the info name for this invocation. Generally this is the most descriptive name for the script or command. For the toplevel script it is usually the name of the script, for commands below it it's the name of the script. :param obj: an arbitrary object of user data. :param auto_envvar_prefix: the prefix to use for automatic environment variables. If this is `None` then reading from environment variables is disabled. This does not affect manually set environment variables which are always read. :param default_map: a dictionary (like object) with default values for parameters. :param terminal_width: the width of the terminal. The default is inherit from parent context. If no context defines the terminal width then auto detection will be applied. :param max_content_width: the maximum width for content rendered by Click (this currently only affects help pages). This defaults to 80 characters if not overridden. In other words: even if the terminal is larger than that, Click will not format things wider than 80 characters by default. In addition to that, formatters might add some safety mapping on the right. :param resilient_parsing: if this flag is enabled then Click will parse without any interactivity or callback invocation. This is useful for implementing things such as completion support. :param allow_extra_args: if this is set to `True` then extra arguments at the end will not raise an error and will be kept on the context. The default is to inherit from the command. :param allow_interspersed_args: if this is set to `False` then options and arguments cannot be mixed. The default is to inherit from the command. :param ignore_unknown_options: instructs click to ignore options it does not know and keeps them for later processing. :param help_option_names: optionally a list of strings that define how the default help parameter is named. The default is ``['--help']``. :param token_normalize_func: an optional function that is used to normalize tokens (options, choices, etc.). This for instance can be used to implement case insensitive behavior. :param color: controls if the terminal supports ANSI colors or not. The default is autodetection. This is only needed if ANSI codes are used in texts that Click prints which is by default not the case. This for instance would affect help output. """ def __init__(self, command, parent=None, info_name=None, obj=None, auto_envvar_prefix=None, default_map=None, terminal_width=None, max_content_width=None, resilient_parsing=False, allow_extra_args=None, allow_interspersed_args=None, ignore_unknown_options=None, help_option_names=None, token_normalize_func=None, color=None): #: the parent context or `None` if none exists. self.parent = parent #: the :class:`Command` for this context. self.command = command #: the descriptive information name self.info_name = info_name #: the parsed parameters except if the value is hidden in which #: case it's not remembered. self.params = {} #: the leftover arguments. self.args = [] if obj is None and parent is not None: obj = parent.obj #: the user object stored. self.obj = obj self._meta = getattr(parent, 'meta', {}) #: A dictionary (-like object) with defaults for parameters. if default_map is None \ and parent is not None \ and parent.default_map is not None: default_map = parent.default_map.get(info_name) self.default_map = default_map #: This flag indicates if a subcommand is going to be executed. A #: group callback can use this information to figure out if it's #: being executed directly or because the execution flow passes #: onwards to a subcommand. By default it's None, but it can be #: the name of the subcommand to execute. #: #: If chaining is enabled this will be set to ``'*'`` in case #: any commands are executed. It is however not possible to #: figure out which ones. If you require this knowledge you #: should use a :func:`resultcallback`. self.invoked_subcommand = None if terminal_width is None and parent is not None: terminal_width = parent.terminal_width #: The width of the terminal (None is autodetection). self.terminal_width = terminal_width if max_content_width is None and parent is not None: max_content_width = parent.max_content_width #: The maximum width of formatted content (None implies a sensible #: default which is 80 for most things). self.max_content_width = max_content_width if allow_extra_args is None: allow_extra_args = command.allow_extra_args #: Indicates if the context allows extra args or if it should #: fail on parsing. #: #: .. versionadded:: 3.0 self.allow_extra_args = allow_extra_args if allow_interspersed_args is None: allow_interspersed_args = command.allow_interspersed_args #: Indicates if the context allows mixing of arguments and #: options or not. #: #: .. versionadded:: 3.0 self.allow_interspersed_args = allow_interspersed_args if ignore_unknown_options is None: ignore_unknown_options = command.ignore_unknown_options #: Instructs click to ignore options that a command does not #: understand and will store it on the context for later #: processing. This is primarily useful for situations where you #: want to call into external programs. Generally this pattern is #: strongly discouraged because it's not possibly to losslessly #: forward all arguments. #: #: .. versionadded:: 4.0 self.ignore_unknown_options = ignore_unknown_options if help_option_names is None: if parent is not None: help_option_names = parent.help_option_names else: help_option_names = ['--help'] #: The names for the help options. self.help_option_names = help_option_names if token_normalize_func is None and parent is not None: token_normalize_func = parent.token_normalize_func #: An optional normalization function for tokens. This is #: options, choices, commands etc. self.token_normalize_func = token_normalize_func #: Indicates if resilient parsing is enabled. In that case Click #: will do its best to not cause any failures. self.resilient_parsing = resilient_parsing # If there is no envvar prefix yet, but the parent has one and # the command on this level has a name, we can expand the envvar # prefix automatically. if auto_envvar_prefix is None: if parent is not None \ and parent.auto_envvar_prefix is not None and \ self.info_name is not None: auto_envvar_prefix = '%s_%s' % (parent.auto_envvar_prefix, self.info_name.upper()) else: self.auto_envvar_prefix = auto_envvar_prefix.upper() self.auto_envvar_prefix = auto_envvar_prefix if color is None and parent is not None: color = parent.color #: Controls if styling output is wanted or not. self.color = color self._close_callbacks = [] self._depth = 0 def __enter__(self): self._depth += 1 push_context(self) return self def __exit__(self, exc_type, exc_value, tb): pop_context() self._depth -= 1 if self._depth == 0: self.close() @contextmanager def scope(self, cleanup=True): """This helper method can be used with the context object to promote it to the current thread local (see :func:`get_current_context`). The default behavior of this is to invoke the cleanup functions which can be disabled by setting `cleanup` to `False`. The cleanup functions are typically used for things such as closing file handles. If the cleanup is intended the context object can also be directly used as a context manager. Example usage:: with ctx.scope(): assert get_current_context() is ctx This is equivalent:: with ctx: assert get_current_context() is ctx .. versionadded:: 5.0 :param cleanup: controls if the cleanup functions should be run or not. The default is to run these functions. In some situations the context only wants to be temporarily pushed in which case this can be disabled. Nested pushes automatically defer the cleanup. """ if not cleanup: self._depth += 1 try: with self as rv: yield rv finally: if not cleanup: self._depth -= 1 @property def meta(self): """This is a dictionary which is shared with all the contexts that are nested. It exists so that click utiltiies can store some state here if they need to. It is however the responsibility of that code to manage this dictionary well. The keys are supposed to be unique dotted strings. For instance module paths are a good choice for it. What is stored in there is irrelevant for the operation of click. However what is important is that code that places data here adheres to the general semantics of the system. Example usage:: LANG_KEY = __name__ + '.lang' def set_language(value): ctx = get_current_context() ctx.meta[LANG_KEY] = value def get_language(): return get_current_context().meta.get(LANG_KEY, 'en_US') .. versionadded:: 5.0 """ return self._meta def make_formatter(self): """Creates the formatter for the help and usage output.""" return HelpFormatter(width=self.terminal_width, max_width=self.max_content_width) def call_on_close(self, f): """This decorator remembers a function as callback that should be executed when the context tears down. This is most useful to bind resource handling to the script execution. For instance, file objects opened by the :class:`File` type will register their close callbacks here. :param f: the function to execute on teardown. """ self._close_callbacks.append(f) return f def close(self): """Invokes all close callbacks.""" for cb in self._close_callbacks: cb() self._close_callbacks = [] @property def command_path(self): """The computed command path. This is used for the ``usage`` information on the help page. It's automatically created by combining the info names of the chain of contexts to the root. """ rv = '' if self.info_name is not None: rv = self.info_name if self.parent is not None: rv = self.parent.command_path + ' ' + rv return rv.lstrip() def find_root(self): """Finds the outermost context.""" node = self while node.parent is not None: node = node.parent return node def find_object(self, object_type): """Finds the closest object of a given type.""" node = self while node is not None: if isinstance(node.obj, object_type): return node.obj node = node.parent def ensure_object(self, object_type): """Like :meth:`find_object` but sets the innermost object to a new instance of `object_type` if it does not exist. """ rv = self.find_object(object_type) if rv is None: self.obj = rv = object_type() return rv def lookup_default(self, name): """Looks up the default for a parameter name. This by default looks into the :attr:`default_map` if available. """ if self.default_map is not None: rv = self.default_map.get(name) if callable(rv): rv = rv() return rv def fail(self, message): """Aborts the execution of the program with a specific error message. :param message: the error message to fail with. """ raise UsageError(message, self) def abort(self): """Aborts the script.""" raise Abort() def exit(self, code=0): """Exits the application with a given exit code.""" sys.exit(code) def get_usage(self): """Helper method to get formatted usage string for the current context and command. """ return self.command.get_usage(self) def get_help(self): """Helper method to get formatted help page for the current context and command. """ return self.command.get_help(self) def invoke(*args, **kwargs): """Invokes a command callback in exactly the way it expects. There are two ways to invoke this method: 1. the first argument can be a callback and all other arguments and keyword arguments are forwarded directly to the function. 2. the first argument is a click command object. In that case all arguments are forwarded as well but proper click parameters (options and click arguments) must be keyword arguments and Click will fill in defaults. Note that before Click 3.2 keyword arguments were not properly filled in against the intention of this code and no context was created. For more information about this change and why it was done in a bugfix release see :ref:`upgrade-to-3.2`. """ self, callback = args[:2] ctx = self # It's also possible to invoke another command which might or # might not have a callback. In that case we also fill # in defaults and make a new context for this command. if isinstance(callback, Command): other_cmd = callback callback = other_cmd.callback ctx = Context(other_cmd, info_name=other_cmd.name, parent=self) if callback is None: raise TypeError('The given command does not have a ' 'callback that can be invoked.') for param in other_cmd.params: if param.name not in kwargs and param.expose_value: kwargs[param.name] = param.get_default(ctx) args = args[2:] with augment_usage_errors(self): with ctx: return callback(*args, **kwargs) def forward(*args, **kwargs): """Similar to :meth:`invoke` but fills in default keyword arguments from the current context if the other command expects it. This cannot invoke callbacks directly, only other commands. """ self, cmd = args[:2] # It's also possible to invoke another command which might or # might not have a callback. if not isinstance(cmd, Command): raise TypeError('Callback is not a command.') for param in self.params: if param not in kwargs: kwargs[param] = self.params[param] return self.invoke(cmd, **kwargs) class BaseCommand(object): """The base command implements the minimal API contract of commands. Most code will never use this as it does not implement a lot of useful functionality but it can act as the direct subclass of alternative parsing methods that do not depend on the Click parser. For instance, this can be used to bridge Click and other systems like argparse or docopt. Because base commands do not implement a lot of the API that other parts of Click take for granted, they are not supported for all operations. For instance, they cannot be used with the decorators usually and they have no built-in callback system. .. versionchanged:: 2.0 Added the `context_settings` parameter. :param name: the name of the command to use unless a group overrides it. :param context_settings: an optional dictionary with defaults that are passed to the context object. """ #: the default for the :attr:`Context.allow_extra_args` flag. allow_extra_args = False #: the default for the :attr:`Context.allow_interspersed_args` flag. allow_interspersed_args = True #: the default for the :attr:`Context.ignore_unknown_options` flag. ignore_unknown_options = False def __init__(self, name, context_settings=None): #: the name the command thinks it has. Upon registering a command #: on a :class:`Group` the group will default the command name #: with this information. You should instead use the #: :class:`Context`\'s :attr:`~Context.info_name` attribute. self.name = name if context_settings is None: context_settings = {} #: an optional dictionary with defaults passed to the context. self.context_settings = context_settings def get_usage(self, ctx): raise NotImplementedError('Base commands cannot get usage') def get_help(self, ctx): raise NotImplementedError('Base commands cannot get help') def make_context(self, info_name, args, parent=None, **extra): """This function when given an info name and arguments will kick off the parsing and create a new :class:`Context`. It does not invoke the actual command callback though. :param info_name: the info name for this invokation. Generally this is the most descriptive name for the script or command. For the toplevel script it's usually the name of the script, for commands below it it's the name of the script. :param args: the arguments to parse as list of strings. :param parent: the parent context if available. :param extra: extra keyword arguments forwarded to the context constructor. """ for key, value in iteritems(self.context_settings): if key not in extra: extra[key] = value ctx = Context(self, info_name=info_name, parent=parent, **extra) with ctx.scope(cleanup=False): self.parse_args(ctx, args) return ctx def parse_args(self, ctx, args): """Given a context and a list of arguments this creates the parser and parses the arguments, then modifies the context as necessary. This is automatically invoked by :meth:`make_context`. """ raise NotImplementedError('Base commands do not know how to parse ' 'arguments.') def invoke(self, ctx): """Given a context, this invokes the command. The default implementation is raising a not implemented error. """ raise NotImplementedError('Base commands are not invokable by default') def main(self, args=None, prog_name=None, complete_var=None, standalone_mode=True, **extra): """This is the way to invoke a script with all the bells and whistles as a command line application. This will always terminate the application after a call. If this is not wanted, ``SystemExit`` needs to be caught. This method is also available by directly calling the instance of a :class:`Command`. .. versionadded:: 3.0 Added the `standalone_mode` flag to control the standalone mode. :param args: the arguments that should be used for parsing. If not provided, ``sys.argv[1:]`` is used. :param prog_name: the program name that should be used. By default the program name is constructed by taking the file name from ``sys.argv[0]``. :param complete_var: the environment variable that controls the bash completion support. The default is ``"_<prog_name>_COMPLETE"`` with prog name in uppercase. :param standalone_mode: the default behavior is to invoke the script in standalone mode. Click will then handle exceptions and convert them into error messages and the function will never return but shut down the interpreter. If this is set to `False` they will be propagated to the caller and the return value of this function is the return value of :meth:`invoke`. :param extra: extra keyword arguments are forwarded to the context constructor. See :class:`Context` for more information. """ # If we are in Python 3, we will verify that the environment is # sane at this point of reject further execution to avoid a # broken script. if not PY2: try: import locale fs_enc = codecs.lookup(locale.getpreferredencoding()).name except Exception: fs_enc = 'ascii' if fs_enc == 'ascii': raise RuntimeError('Click will abort further execution ' 'because Python 3 was configured to use ' 'ASCII as encoding for the environment. ' 'Either switch to Python 2 or consult ' 'http://click.pocoo.org/python3/ ' 'for mitigation steps.') else: _check_for_unicode_literals() if args is None: args = sys.argv[1:] else: args = list(args) if prog_name is None: prog_name = make_str(os.path.basename( sys.argv and sys.argv[0] or __file__)) # Hook for the Bash completion. This only activates if the Bash # completion is actually enabled, otherwise this is quite a fast # noop. _bashcomplete(self, prog_name, complete_var) try: try: with self.make_context(prog_name, args, **extra) as ctx: rv = self.invoke(ctx) if not standalone_mode: return rv ctx.exit() except (EOFError, KeyboardInterrupt): echo(file=sys.stderr) raise Abort() except ClickException as e: if not standalone_mode: raise e.show() sys.exit(e.exit_code) except Abort: if not standalone_mode: raise echo('Aborted!', file=sys.stderr) sys.exit(1) def __call__(self, *args, **kwargs): """Alias for :meth:`main`.""" return self.main(*args, **kwargs) class Command(BaseCommand): """Commands are the basic building block of command line interfaces in Click. A basic command handles command line parsing and might dispatch more parsing to commands nested below it. .. versionchanged:: 2.0 Added the `context_settings` parameter. :param name: the name of the command to use unless a group overrides it. :param context_settings: an optional dictionary with defaults that are passed to the context object. :param callback: the callback to invoke. This is optional. :param params: the parameters to register with this command. This can be either :class:`Option` or :class:`Argument` objects. :param help: the help string to use for this command. :param epilog: like the help string but it's printed at the end of the help page after everything else. :param short_help: the short help to use for this command. This is shown on the command listing of the parent command. :param add_help_option: by default each command registers a ``--help`` option. This can be disabled by this parameter. """ def __init__(self, name, context_settings=None, callback=None, params=None, help=None, epilog=None, short_help=None, options_metavar='[OPTIONS]', add_help_option=True): BaseCommand.__init__(self, name, context_settings) #: the callback to execute when the command fires. This might be #: `None` in which case nothing happens. self.callback = callback #: the list of parameters for this command in the order they #: should show up in the help page and execute. Eager parameters #: will automatically be handled before non eager ones. self.params = params or [] self.help = help self.epilog = epilog self.options_metavar = options_metavar if short_help is None and help: short_help = make_default_short_help(help) self.short_help = short_help self.add_help_option = add_help_option def get_usage(self, ctx): formatter = ctx.make_formatter() self.format_usage(ctx, formatter) return formatter.getvalue().rstrip('\n') def get_params(self, ctx): rv = self.params help_option = self.get_help_option(ctx) if help_option is not None: rv = rv + [help_option] return rv def format_usage(self, ctx, formatter): """Writes the usage line into the formatter.""" pieces = self.collect_usage_pieces(ctx) formatter.write_usage(ctx.command_path, ' '.join(pieces)) def collect_usage_pieces(self, ctx): """Returns all the pieces that go into the usage line and returns it as a list of strings. """ rv = [self.options_metavar] for param in self.get_params(ctx): rv.extend(param.get_usage_pieces(ctx)) return rv def get_help_option_names(self, ctx): """Returns the names for the help option.""" all_names = set(ctx.help_option_names) for param in self.params: all_names.difference_update(param.opts) all_names.difference_update(param.secondary_opts) return all_names def get_help_option(self, ctx): """Returns the help option object.""" help_options = self.get_help_option_names(ctx) if not help_options or not self.add_help_option: return def show_help(ctx, param, value): if value and not ctx.resilient_parsing: echo(ctx.get_help(), color=ctx.color) ctx.exit() return Option(help_options, is_flag=True, is_eager=True, expose_value=False, callback=show_help, help='Show this message and exit.') def make_parser(self, ctx): """Creates the underlying option parser for this command.""" parser = OptionParser(ctx) parser.allow_interspersed_args = ctx.allow_interspersed_args parser.ignore_unknown_options = ctx.ignore_unknown_options for param in self.get_params(ctx): param.add_to_parser(parser, ctx) return parser def get_help(self, ctx): """Formats the help into a string and returns it. This creates a formatter and will call into the following formatting methods: """ formatter = ctx.make_formatter() self.format_help(ctx, formatter) return formatter.getvalue().rstrip('\n') def format_help(self, ctx, formatter): """Writes the help into the formatter if it exists. This calls into the following methods: - :meth:`format_usage` - :meth:`format_help_text` - :meth:`format_options` - :meth:`format_epilog` """ self.format_usage(ctx, formatter) self.format_help_text(ctx, formatter) self.format_options(ctx, formatter) self.format_epilog(ctx, formatter) def format_help_text(self, ctx, formatter): """Writes the help text to the formatter if it exists.""" if self.help: formatter.write_paragraph() with formatter.indentation(): formatter.write_text(self.help) def format_options(self, ctx, formatter): """Writes all the options into the formatter if they exist.""" opts = [] for param in self.get_params(ctx): rv = param.get_help_record(ctx) if rv is not None: opts.append(rv) if opts: with formatter.section('Options'): formatter.write_dl(opts) def format_epilog(self, ctx, formatter): """Writes the epilog into the formatter if it exists.""" if self.epilog: formatter.write_paragraph() with formatter.indentation(): formatter.write_text(self.epilog) def parse_args(self, ctx, args): parser = self.make_parser(ctx) opts, args, param_order = parser.parse_args(args=args) for param in iter_params_for_processing( param_order, self.get_params(ctx)): value, args = param.handle_parse_result(ctx, opts, args) if args and not ctx.allow_extra_args and not ctx.resilient_parsing: ctx.fail('Got unexpected extra argument%s (%s)' % (len(args) != 1 and 's' or '', ' '.join(map(make_str, args)))) ctx.args = args return args def invoke(self, ctx): """Given a context, this invokes the attached callback (if it exists) in the right way. """ if self.callback is not None: return ctx.invoke(self.callback, **ctx.params) class MultiCommand(Command): """A multi command is the basic implementation of a command that dispatches to subcommands. The most common version is the :class:`Group`. :param invoke_without_command: this controls how the multi command itself is invoked. By default it's only invoked if a subcommand is provided. :param no_args_is_help: this controls what happens if no arguments are provided. This option is enabled by default if `invoke_without_command` is disabled or disabled if it's enabled. If enabled this will add ``--help`` as argument if no arguments are passed. :param subcommand_metavar: the string that is used in the documentation to indicate the subcommand place. :param chain: if this is set to `True` chaining of multiple subcommands is enabled. This restricts the form of commands in that they cannot have optional arguments but it allows multiple commands to be chained together. :param result_callback: the result callback to attach to this multi command. """ allow_extra_args = True allow_interspersed_args = False def __init__(self, name=None, invoke_without_command=False, no_args_is_help=None, subcommand_metavar=None, chain=False, result_callback=None, **attrs): Command.__init__(self, name, **attrs) if no_args_is_help is None: no_args_is_help = not invoke_without_command self.no_args_is_help = no_args_is_help self.invoke_without_command = invoke_without_command if subcommand_metavar is None: if chain: subcommand_metavar = SUBCOMMANDS_METAVAR else: subcommand_metavar = SUBCOMMAND_METAVAR self.subcommand_metavar = subcommand_metavar self.chain = chain #: The result callback that is stored. This can be set or #: overridden with the :func:`resultcallback` decorator. self.result_callback = result_callback def collect_usage_pieces(self, ctx): rv = Command.collect_usage_pieces(self, ctx) rv.append(self.subcommand_metavar) return rv def format_options(self, ctx, formatter): Command.format_options(self, ctx, formatter) self.format_commands(ctx, formatter) def resultcallback(self, replace=False): """Adds a result callback to the chain command. By default if a result callback is already registered this will chain them but this can be disabled with the `replace` parameter. The result callback is invoked with the return value of the subcommand (or the list of return values from all subcommands if chaining is enabled) as well as the parameters as they would be passed to the main callback. Example:: @click.group() @click.option('-i', '--input', default=23) def cli(input): return 42 @cli.resultcallback() def process_result(result, input): return result + input .. versionadded:: 3.0 :param replace: if set to `True` an already existing result callback will be removed. """ def decorator(f): old_callback = self.result_callback if old_callback is None or replace: self.result_callback = f return f def function(__value, *args, **kwargs): return f(old_callback(__value, *args, **kwargs), *args, **kwargs) self.result_callback = rv = update_wrapper(function, f) return rv return decorator def format_commands(self, ctx, formatter): """Extra format methods for multi methods that adds all the commands after the options. """ rows = [] for subcommand in self.list_commands(ctx): cmd = self.get_command(ctx, subcommand) # What is this, the tool lied about a command. Ignore it if cmd is None: continue help = cmd.short_help or '' rows.append((subcommand, help)) if rows: with formatter.section('Commands'): formatter.write_dl(rows) def parse_args(self, ctx, args): if not args and self.no_args_is_help and not ctx.resilient_parsing: echo(ctx.get_help(), color=ctx.color) ctx.exit() return Command.parse_args(self, ctx, args) def invoke(self, ctx): def _process_result(value): if self.result_callback is not None: value = ctx.invoke(self.result_callback, value, **ctx.params) return value if not ctx.args: # If we are invoked without command the chain flag controls # how this happens. If we are not in chain mode, the return # value here is the return value of the command. # If however we are in chain mode, the return value is the # return value of the result processor invoked with an empty # list (which means that no subcommand actually was executed). if self.invoke_without_command: if not self.chain: return Command.invoke(self, ctx) with ctx: Command.invoke(self, ctx) return _process_result([]) ctx.fail('Missing command.') args = ctx.args # If we're not in chain mode, we only allow the invocation of a # single command but we also inform the current context about the # name of the command to invoke. if not self.chain: # Make sure the context is entered so we do not clean up # resources until the result processor has worked. with ctx: cmd_name, cmd, args = self.resolve_command(ctx, args) ctx.invoked_subcommand = cmd_name Command.invoke(self, ctx) sub_ctx = cmd.make_context(cmd_name, args, parent=ctx) with sub_ctx: return _process_result(sub_ctx.command.invoke(sub_ctx)) # In chain mode we create the contexts step by step, but after the # base command has been invoked. Because at that point we do not # know the subcommands yet, the invoked subcommand attribute is # set to ``*`` to inform the command that subcommands are executed # but nothing else. with ctx: ctx.invoked_subcommand = args and '*' or None Command.invoke(self, ctx) # Otherwise we make every single context and invoke them in a # chain. In that case the return value to the result processor # is the list of all invoked subcommand's results. contexts = [] while args: cmd_name, cmd, args = self.resolve_command(ctx, args) sub_ctx = cmd.make_context(cmd_name, args, parent=ctx, allow_extra_args=True, allow_interspersed_args=False) contexts.append(sub_ctx) args = sub_ctx.args rv = [] for sub_ctx in contexts: with sub_ctx: rv.append(sub_ctx.command.invoke(sub_ctx)) return _process_result(rv) def resolve_command(self, ctx, args): cmd_name = make_str(args[0]) original_cmd_name = cmd_name # Get the command cmd = self.get_command(ctx, cmd_name) # If we can't find the command but there is a normalization # function available, we try with that one. if cmd is None and ctx.token_normalize_func is not None: cmd_name = ctx.token_normalize_func(cmd_name) cmd = self.get_command(ctx, cmd_name) # If we don't find the command we want to show an error message # to the user that it was not provided. However, there is # something else we should do: if the first argument looks like # an option we want to kick off parsing again for arguments to # resolve things like --help which now should go to the main # place. if cmd is None: if split_opt(cmd_name)[0]: self.parse_args(ctx, ctx.args) ctx.fail('No such command "%s".' % original_cmd_name) return cmd_name, cmd, args[1:] def get_command(self, ctx, cmd_name): """Given a context and a command name, this returns a :class:`Command` object if it exists or returns `None`. """ raise NotImplementedError() def list_commands(self, ctx): """Returns a list of subcommand names in the order they should appear. """ return [] class Group(MultiCommand): """A group allows a command to have subcommands attached. This is the most common way to implement nesting in Click. :param commands: a dictionary of commands. """ def __init__(self, name=None, commands=None, **attrs): MultiCommand.__init__(self, name, **attrs) #: the registered subcommands by their exported names. self.commands = commands or {} def add_command(self, cmd, name=None): """Registers another :class:`Command` with this group. If the name is not provided, the name of the command is used. """ name = name or cmd.name if name is None: raise TypeError('Command has no name.') self.commands[name] = cmd def command(self, *args, **kwargs): """A shortcut decorator for declaring and attaching a command to the group. This takes the same arguments as :func:`command` but immediately registers the created command with this instance by calling into :meth:`add_command`. """ def decorator(f): cmd = command(*args, **kwargs)(f) self.add_command(cmd) return cmd return decorator def group(self, *args, **kwargs): """A shortcut decorator for declaring and attaching a group to the group. This takes the same arguments as :func:`group` but immediately registers the created command with this instance by calling into :meth:`add_command`. """ def decorator(f): cmd = group(*args, **kwargs)(f) self.add_command(cmd) return cmd return decorator def get_command(self, ctx, cmd_name): return self.commands.get(cmd_name) def list_commands(self, ctx): return sorted(self.commands) class CommandCollection(MultiCommand): """A command collection is a multi command that merges multiple multi commands together into one. This is a straightforward implementation that accepts a list of different multi commands as sources and provides all the commands for each of them. """ def __init__(self, name=None, sources=None, **attrs): MultiCommand.__init__(self, name, **attrs) #: The list of registered multi commands. self.sources = sources or [] def add_source(self, multi_cmd): """Adds a new multi command to the chain dispatcher.""" self.sources.append(multi_cmd) def get_command(self, ctx, cmd_name): for source in self.sources: rv = source.get_command(ctx, cmd_name) if rv is not None: return rv def list_commands(self, ctx): rv = set() for source in self.sources: rv.update(source.list_commands(ctx)) return sorted(rv) class Parameter(object): """A parameter to a command comes in two versions: they are either :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently not supported by design as some of the internals for parsing are intentionally not finalized. Some settings are supported by both options and arguments. .. versionchanged:: 2.0 Changed signature for parameter callback to also be passed the parameter. In Click 2.0, the old callback format will still work, but it will raise a warning to give you change to migrate the code easier. :param param_decls: the parameter declarations for this option or argument. This is a list of flags or argument names. :param type: the type that should be used. Either a :class:`ParamType` or a Python type. The later is converted into the former automatically if supported. :param required: controls if this is optional or not. :param default: the default value if omitted. This can also be a callable, in which case it's invoked when the default is needed without any arguments. :param callback: a callback that should be executed after the parameter was matched. This is called as ``fn(ctx, param, value)`` and needs to return the value. Before Click 2.0, the signature was ``(ctx, value)``. :param nargs: the number of arguments to match. If not ``1`` the return value is a tuple instead of single value. The default for nargs is ``1`` (except if the type is a tuple, then it's the arity of the tuple). :param metavar: how the value is represented in the help page. :param expose_value: if this is `True` then the value is passed onwards to the command callback and stored on the context, otherwise it's skipped. :param is_eager: eager values are processed before non eager ones. This should not be set for arguments or it will inverse the order of processing. :param envvar: a string or list of strings that are environment variables that should be checked. """ param_type_name = 'parameter' def __init__(self, param_decls=None, type=None, required=False, default=None, callback=None, nargs=None, metavar=None, expose_value=True, is_eager=False, envvar=None): self.name, self.opts, self.secondary_opts = \ self._parse_decls(param_decls or (), expose_value) self.type = convert_type(type, default) # Default nargs to what the type tells us if we have that # information available. if nargs is None: if self.type.is_composite: nargs = self.type.arity else: nargs = 1 self.required = required self.callback = callback self.nargs = nargs self.multiple = False self.expose_value = expose_value self.default = default self.is_eager = is_eager self.metavar = metavar self.envvar = envvar @property def human_readable_name(self): """Returns the human readable name of this parameter. This is the same as the name for options, but the metavar for arguments. """ return self.name def make_metavar(self): if self.metavar is not None: return self.metavar metavar = self.type.get_metavar(self) if metavar is None: metavar = self.type.name.upper() if self.nargs != 1: metavar += '...' return metavar def get_default(self, ctx): """Given a context variable this calculates the default value.""" # Otherwise go with the regular default. if callable(self.default): rv = self.default() else: rv = self.default return self.type_cast_value(ctx, rv) def add_to_parser(self, parser, ctx): pass def consume_value(self, ctx, opts): value = opts.get(self.name) if value is None: value = ctx.lookup_default(self.name) if value is None: value = self.value_from_envvar(ctx) return value def type_cast_value(self, ctx, value): """Given a value this runs it properly through the type system. This automatically handles things like `nargs` and `multiple` as well as composite types. """ if self.type.is_composite: if self.nargs <= 1: raise TypeError('Attempted to invoke composite type ' 'but nargs has been set to %s. This is ' 'not supported; nargs needs to be set to ' 'a fixed value > 1.' % self.nargs) if self.multiple: return tuple(self.type(x or (), self, ctx) for x in value or ()) return self.type(value or (), self, ctx) def _convert(value, level): if level == 0: return self.type(value, self, ctx) return tuple(_convert(x, level - 1) for x in value or ()) return _convert(value, (self.nargs != 1) + bool(self.multiple)) def process_value(self, ctx, value): """Given a value and context this runs the logic to convert the value as necessary. """ # If the value we were given is None we do nothing. This way # code that calls this can easily figure out if something was # not provided. Otherwise it would be converted into an empty # tuple for multiple invocations which is inconvenient. if value is not None: return self.type_cast_value(ctx, value) def value_is_missing(self, value): if value is None: return True if (self.nargs != 1 or self.multiple) and value == (): return True return False def full_process_value(self, ctx, value): value = self.process_value(ctx, value) if value is None: value = self.get_default(ctx) if self.required and self.value_is_missing(value): raise MissingParameter(ctx=ctx, param=self) return value def resolve_envvar_value(self, ctx): if self.envvar is None: return if isinstance(self.envvar, (tuple, list)): for envvar in self.envvar: rv = os.environ.get(envvar) if rv is not None: return rv else: return os.environ.get(self.envvar) def value_from_envvar(self, ctx): rv = self.resolve_envvar_value(ctx) if rv is not None and self.nargs != 1: rv = self.type.split_envvar_value(rv) return rv def handle_parse_result(self, ctx, opts, args): with augment_usage_errors(ctx, param=self): value = self.consume_value(ctx, opts) try: value = self.full_process_value(ctx, value) except Exception: if not ctx.resilient_parsing: raise value = None if self.callback is not None: try: value = invoke_param_callback( self.callback, ctx, self, value) except Exception: if not ctx.resilient_parsing: raise if self.expose_value: ctx.params[self.name] = value return value, args def get_help_record(self, ctx): pass def get_usage_pieces(self, ctx): return [] class Option(Parameter): """Options are usually optional values on the command line and have some extra features that arguments don't have. All other parameters are passed onwards to the parameter constructor. :param show_default: controls if the default value should be shown on the help page. Normally, defaults are not shown. :param prompt: if set to `True` or a non empty string then the user will be prompted for input if not set. If set to `True` the prompt will be the option name capitalized. :param confirmation_prompt: if set then the value will need to be confirmed if it was prompted for. :param hide_input: if this is `True` then the input on the prompt will be hidden from the user. This is useful for password input. :param is_flag: forces this option to act as a flag. The default is auto detection. :param flag_value: which value should be used for this flag if it's enabled. This is set to a boolean automatically if the option string contains a slash to mark two options. :param multiple: if this is set to `True` then the argument is accepted multiple times and recorded. This is similar to ``nargs`` in how it works but supports arbitrary number of arguments. :param count: this flag makes an option increment an integer. :param allow_from_autoenv: if this is enabled then the value of this parameter will be pulled from an environment variable in case a prefix is defined on the context. :param help: the help string. """ param_type_name = 'option' def __init__(self, param_decls=None, show_default=False, prompt=False, confirmation_prompt=False, hide_input=False, is_flag=None, flag_value=None, multiple=False, count=False, allow_from_autoenv=True, type=None, help=None, **attrs): default_is_missing = attrs.get('default', _missing) is _missing Parameter.__init__(self, param_decls, type=type, **attrs) if prompt is True: prompt_text = self.name.replace('_', ' ').capitalize() elif prompt is False: prompt_text = None else: prompt_text = prompt self.prompt = prompt_text self.confirmation_prompt = confirmation_prompt self.hide_input = hide_input # Flags if is_flag is None: if flag_value is not None: is_flag = True else: is_flag = bool(self.secondary_opts) if is_flag and default_is_missing: self.default = False if flag_value is None: flag_value = not self.default self.is_flag = is_flag self.flag_value = flag_value if self.is_flag and isinstance(self.flag_value, bool) \ and type is None: self.type = BOOL self.is_bool_flag = True else: self.is_bool_flag = False # Counting self.count = count if count: if type is None: self.type = IntRange(min=0) if default_is_missing: self.default = 0 self.multiple = multiple self.allow_from_autoenv = allow_from_autoenv self.help = help self.show_default = show_default # Sanity check for stuff we don't support if __debug__: if self.nargs < 0: raise TypeError('Options cannot have nargs < 0') if self.prompt and self.is_flag and not self.is_bool_flag: raise TypeError('Cannot prompt for flags that are not bools.') if not self.is_bool_flag and self.secondary_opts: raise TypeError('Got secondary option for non boolean flag.') if self.is_bool_flag and self.hide_input \ and self.prompt is not None: raise TypeError('Hidden input does not work with boolean ' 'flag prompts.') if self.count: if self.multiple: raise TypeError('Options cannot be multiple and count ' 'at the same time.') elif self.is_flag: raise TypeError('Options cannot be count and flags at ' 'the same time.') def _parse_decls(self, decls, expose_value): opts = [] secondary_opts = [] name = None possible_names = [] for decl in decls: if isidentifier(decl): if name is not None: raise TypeError('Name defined twice') name = decl else: split_char = decl[:1] == '/' and ';' or '/' if split_char in decl: first, second = decl.split(split_char, 1) first = first.rstrip() possible_names.append(split_opt(first)) opts.append(first) secondary_opts.append(second.lstrip()) else: possible_names.append(split_opt(decl)) opts.append(decl) if name is None and possible_names: possible_names.sort(key=lambda x: len(x[0])) name = possible_names[-1][1].replace('-', '_').lower() if not isidentifier(name): name = None if name is None: if not expose_value: return None, opts, secondary_opts raise TypeError('Could not determine name for option') if not opts and not secondary_opts: raise TypeError('No options defined but a name was passed (%s). ' 'Did you mean to declare an argument instead ' 'of an option?' % name) return name, opts, secondary_opts def add_to_parser(self, parser, ctx): kwargs = { 'dest': self.name, 'nargs': self.nargs, 'obj': self, } if self.multiple: action = 'append' elif self.count: action = 'count' else: action = 'store' if self.is_flag: kwargs.pop('nargs', None) if self.is_bool_flag and self.secondary_opts: parser.add_option(self.opts, action=action + '_const', const=True, **kwargs) parser.add_option(self.secondary_opts, action=action + '_const', const=False, **kwargs) else: parser.add_option(self.opts, action=action + '_const', const=self.flag_value, **kwargs) else: kwargs['action'] = action parser.add_option(self.opts, **kwargs) def get_help_record(self, ctx): any_prefix_is_slash = [] def _write_opts(opts): rv, any_slashes = join_options(opts) if any_slashes: any_prefix_is_slash[:] = [True] if not self.is_flag and not self.count: rv += ' ' + self.make_metavar() return rv rv = [_write_opts(self.opts)] if self.secondary_opts: rv.append(_write_opts(self.secondary_opts)) help = self.help or '' extra = [] if self.default is not None and self.show_default: extra.append('default: %s' % ( ', '.join('%s' % d for d in self.default) if isinstance(self.default, (list, tuple)) else self.default, )) if self.required: extra.append('required') if extra: help = '%s[%s]' % (help and help + ' ' or '', '; '.join(extra)) return ((any_prefix_is_slash and '; ' or ' / ').join(rv), help) def get_default(self, ctx): # If we're a non boolean flag out default is more complex because # we need to look at all flags in the same group to figure out # if we're the the default one in which case we return the flag # value as default. if self.is_flag and not self.is_bool_flag: for param in ctx.command.params: if param.name == self.name and param.default: return param.flag_value return None return Parameter.get_default(self, ctx) def prompt_for_value(self, ctx): """This is an alternative flow that can be activated in the full value processing if a value does not exist. It will prompt the user until a valid value exists and then returns the processed value as result. """ # Calculate the default before prompting anything to be stable. default = self.get_default(ctx) # If this is a prompt for a flag we need to handle this # differently. if self.is_bool_flag: return confirm(self.prompt, default) return prompt(self.prompt, default=default, hide_input=self.hide_input, confirmation_prompt=self.confirmation_prompt, value_proc=lambda x: self.process_value(ctx, x)) def resolve_envvar_value(self, ctx): rv = Parameter.resolve_envvar_value(self, ctx) if rv is not None: return rv if self.allow_from_autoenv and \ ctx.auto_envvar_prefix is not None: envvar = '%s_%s' % (ctx.auto_envvar_prefix, self.name.upper()) return os.environ.get(envvar) def value_from_envvar(self, ctx): rv = self.resolve_envvar_value(ctx) if rv is None: return None value_depth = (self.nargs != 1) + bool(self.multiple) if value_depth > 0 and rv is not None: rv = self.type.split_envvar_value(rv) if self.multiple and self.nargs != 1: rv = batch(rv, self.nargs) return rv def full_process_value(self, ctx, value): if value is None and self.prompt is not None \ and not ctx.resilient_parsing: return self.prompt_for_value(ctx) return Parameter.full_process_value(self, ctx, value) class Argument(Parameter): """Arguments are positional parameters to a command. They generally provide fewer features than options but can have infinite ``nargs`` and are required by default. All parameters are passed onwards to the parameter constructor. """ param_type_name = 'argument' def __init__(self, param_decls, required=None, **attrs): if required is None: if attrs.get('default') is not None: required = False else: required = attrs.get('nargs', 1) > 0 Parameter.__init__(self, param_decls, required=required, **attrs) @property def human_readable_name(self): if self.metavar is not None: return self.metavar return self.name.upper() def make_metavar(self): if self.metavar is not None: return self.metavar var = self.name.upper() if not self.required: var = '[%s]' % var if self.nargs != 1: var += '...' return var def _parse_decls(self, decls, expose_value): if not decls: if not expose_value: return None, [], [] raise TypeError('Could not determine name for argument') if len(decls) == 1: name = arg = decls[0] name = name.replace('-', '_').lower() elif len(decls) == 2: name, arg = decls else: raise TypeError('Arguments take exactly one or two ' 'parameter declarations, got %d' % len(decls)) return name, [arg], [] def get_usage_pieces(self, ctx): return [self.make_metavar()] def add_to_parser(self, parser, ctx): parser.add_argument(dest=self.name, nargs=self.nargs, obj=self) # Circular dependency between decorators and core from .decorators import command, group
gameduell/duell
pylib/click/core.py
Python
bsd-2-clause
68,206
from sympy.core.compatibility import range from sympy import (FiniteSet, S, Symbol, sqrt, symbols, simplify, Eq, cos, And, Tuple, Or, Dict, sympify, binomial, cancel, KroneckerDelta) from sympy.concrete.expr_with_limits import AddWithLimits from sympy.matrices import Matrix from sympy.stats import (DiscreteUniform, Die, Bernoulli, Coin, Binomial, Hypergeometric, Rademacher, P, E, variance, covariance, skewness, sample, density, where, FiniteRV, pspace, cdf, correlation, moment, cmoment, smoment) from sympy.stats.frv_types import DieDistribution from sympy.utilities.pytest import raises, slow from sympy.abc import p, x, i oo = S.Infinity def BayesTest(A, B): assert P(A, B) == P(And(A, B)) / P(B) assert P(A, B) == P(B, A) * P(A) / P(B) def test_discreteuniform(): # Symbolic a, b, c = symbols('a b c') X = DiscreteUniform('X', [a, b, c]) assert E(X) == (a + b + c)/3 assert simplify(variance(X) - ((a**2 + b**2 + c**2)/3 - (a/3 + b/3 + c/3)**2)) == 0 assert P(Eq(X, a)) == P(Eq(X, b)) == P(Eq(X, c)) == S('1/3') Y = DiscreteUniform('Y', range(-5, 5)) # Numeric assert E(Y) == S('-1/2') assert variance(Y) == S('33/4') for x in range(-5, 5): assert P(Eq(Y, x)) == S('1/10') assert P(Y <= x) == S(x + 6)/10 assert P(Y >= x) == S(5 - x)/10 assert dict(density(Die('D', 6)).items()) == \ dict(density(DiscreteUniform('U', range(1, 7))).items()) def test_dice(): # TODO: Make iid method! X, Y, Z = Die('X', 6), Die('Y', 6), Die('Z', 6) a, b = symbols('a b') assert E(X) == 3 + S.Half assert variance(X) == S(35)/12 assert E(X + Y) == 7 assert E(X + X) == 7 assert E(a*X + b) == a*E(X) + b assert variance(X + Y) == variance(X) + variance(Y) == cmoment(X + Y, 2) assert variance(X + X) == 4 * variance(X) == cmoment(X + X, 2) assert cmoment(X, 0) == 1 assert cmoment(4*X, 3) == 64*cmoment(X, 3) assert covariance(X, Y) == S.Zero assert covariance(X, X + Y) == variance(X) assert density(Eq(cos(X*S.Pi), 1))[True] == S.Half assert correlation(X, Y) == 0 assert correlation(X, Y) == correlation(Y, X) assert smoment(X + Y, 3) == skewness(X + Y) assert smoment(X, 0) == 1 assert P(X > 3) == S.Half assert P(2*X > 6) == S.Half assert P(X > Y) == S(5)/12 assert P(Eq(X, Y)) == P(Eq(X, 1)) assert E(X, X > 3) == 5 == moment(X, 1, 0, X > 3) assert E(X, Y > 3) == E(X) == moment(X, 1, 0, Y > 3) assert E(X + Y, Eq(X, Y)) == E(2*X) assert moment(X, 0) == 1 assert moment(5*X, 2) == 25*moment(X, 2) assert P(X > 3, X > 3) == S.One assert P(X > Y, Eq(Y, 6)) == S.Zero assert P(Eq(X + Y, 12)) == S.One/36 assert P(Eq(X + Y, 12), Eq(X, 6)) == S.One/6 assert density(X + Y) == density(Y + Z) != density(X + X) d = density(2*X + Y**Z) assert d[S(22)] == S.One/108 and d[S(4100)] == S.One/216 and S(3130) not in d assert pspace(X).domain.as_boolean() == Or( *[Eq(X.symbol, i) for i in [1, 2, 3, 4, 5, 6]]) assert where(X > 3).set == FiniteSet(4, 5, 6) def test_given(): X = Die('X', 6) assert density(X, X > 5) == {S(6): S(1)} assert where(X > 2, X > 5).as_boolean() == Eq(X.symbol, 6) assert sample(X, X > 5) == 6 def test_domains(): X, Y = Die('x', 6), Die('y', 6) x, y = X.symbol, Y.symbol # Domains d = where(X > Y) assert d.condition == (x > y) d = where(And(X > Y, Y > 3)) assert d.as_boolean() == Or(And(Eq(x, 5), Eq(y, 4)), And(Eq(x, 6), Eq(y, 5)), And(Eq(x, 6), Eq(y, 4))) assert len(d.elements) == 3 assert len(pspace(X + Y).domain.elements) == 36 Z = Die('x', 4) raises(ValueError, lambda: P(X > Z)) # Two domains with same internal symbol assert pspace(X + Y).domain.set == FiniteSet(1, 2, 3, 4, 5, 6)**2 assert where(X > 3).set == FiniteSet(4, 5, 6) assert X.pspace.domain.dict == FiniteSet( *[Dict({X.symbol: i}) for i in range(1, 7)]) assert where(X > Y).dict == FiniteSet(*[Dict({X.symbol: i, Y.symbol: j}) for i in range(1, 7) for j in range(1, 7) if i > j]) def test_dice_bayes(): X, Y, Z = Die('X', 6), Die('Y', 6), Die('Z', 6) BayesTest(X > 3, X + Y < 5) BayesTest(Eq(X - Y, Z), Z > Y) BayesTest(X > 3, X > 2) def test_die_args(): raises(ValueError, lambda: Die('X', -1)) # issue 8105: negative sides. raises(ValueError, lambda: Die('X', 0)) raises(ValueError, lambda: Die('X', 1.5)) # issue 8103: non integer sides. k = Symbol('k') sym_die = Die('X', k) raises(ValueError, lambda: density(sym_die).dict) def test_bernoulli(): p, a, b = symbols('p a b') X = Bernoulli('B', p, a, b) assert E(X) == a*p + b*(-p + 1) assert density(X)[a] == p assert density(X)[b] == 1 - p X = Bernoulli('B', p, 1, 0) assert E(X) == p assert simplify(variance(X)) == p*(1 - p) assert E(a*X + b) == a*E(X) + b assert simplify(variance(a*X + b)) == simplify(a**2 * variance(X)) def test_cdf(): D = Die('D', 6) o = S.One assert cdf( D) == sympify({1: o/6, 2: o/3, 3: o/2, 4: 2*o/3, 5: 5*o/6, 6: o}) def test_coins(): C, D = Coin('C'), Coin('D') H, T = symbols('H, T') assert P(Eq(C, D)) == S.Half assert density(Tuple(C, D)) == {(H, H): S.One/4, (H, T): S.One/4, (T, H): S.One/4, (T, T): S.One/4} assert dict(density(C).items()) == {H: S.Half, T: S.Half} F = Coin('F', S.One/10) assert P(Eq(F, H)) == S(1)/10 d = pspace(C).domain assert d.as_boolean() == Or(Eq(C.symbol, H), Eq(C.symbol, T)) raises(ValueError, lambda: P(C > D)) # Can't intelligently compare H to T def test_binomial_verify_parameters(): raises(ValueError, lambda: Binomial('b', .2, .5)) raises(ValueError, lambda: Binomial('b', 3, 1.5)) def test_binomial_numeric(): nvals = range(5) pvals = [0, S(1)/4, S.Half, S(3)/4, 1] for n in nvals: for p in pvals: X = Binomial('X', n, p) assert E(X) == n*p assert variance(X) == n*p*(1 - p) if n > 0 and 0 < p < 1: assert skewness(X) == (1 - 2*p)/sqrt(n*p*(1 - p)) for k in range(n + 1): assert P(Eq(X, k)) == binomial(n, k)*p**k*(1 - p)**(n - k) @slow def test_binomial_symbolic(): n = 10 # Because we're using for loops, can't do symbolic n p = symbols('p', positive=True) X = Binomial('X', n, p) assert simplify(E(X)) == n*p == simplify(moment(X, 1)) assert simplify(variance(X)) == n*p*(1 - p) == simplify(cmoment(X, 2)) assert cancel((skewness(X) - (1-2*p)/sqrt(n*p*(1-p)))) == 0 # Test ability to change success/failure winnings H, T = symbols('H T') Y = Binomial('Y', n, p, succ=H, fail=T) assert simplify(E(Y) - (n*(H*p + T*(1 - p)))) == 0 def test_hypergeometric_numeric(): for N in range(1, 5): for m in range(0, N + 1): for n in range(1, N + 1): X = Hypergeometric('X', N, m, n) N, m, n = map(sympify, (N, m, n)) assert sum(density(X).values()) == 1 assert E(X) == n * m / N if N > 1: assert variance(X) == n*(m/N)*(N - m)/N*(N - n)/(N - 1) # Only test for skewness when defined if N > 2 and 0 < m < N and n < N: assert skewness(X) == simplify((N - 2*m)*sqrt(N - 1)*(N - 2*n) / (sqrt(n*m*(N - m)*(N - n))*(N - 2))) def test_rademacher(): X = Rademacher('X') assert E(X) == 0 assert variance(X) == 1 assert density(X)[-1] == S.Half assert density(X)[1] == S.Half def test_FiniteRV(): F = FiniteRV('F', {1: S.Half, 2: S.One/4, 3: S.One/4}) assert dict(density(F).items()) == {S(1): S.Half, S(2): S.One/4, S(3): S.One/4} assert P(F >= 2) == S.Half assert pspace(F).domain.as_boolean() == Or( *[Eq(F.symbol, i) for i in [1, 2, 3]]) def test_density_call(): x = Bernoulli('x', p) d = density(x) assert d(0) == 1 - p assert d(S.Zero) == 1 - p assert d(5) == 0 assert 0 in d assert 5 not in d assert d(S(0)) == d[S(0)] def test_DieDistribution(): X = DieDistribution(6) assert X.pdf(S(1)/2) == S.Zero assert X.pdf(x).subs({x: 1}).doit() == S(1)/6 assert X.pdf(x).subs({x: 7}).doit() == 0 assert X.pdf(x).subs({x: -1}).doit() == 0 assert X.pdf(x).subs({x: S(1)/3}).doit() == 0 raises(TypeError, lambda: X.pdf(x).subs({x: Matrix([0, 0])})) raises(ValueError, lambda: X.pdf(x**2 - 1))
Shaswat27/sympy
sympy/stats/tests/test_finite_rv.py
Python
bsd-3-clause
8,667
# -*- encoding: utf-8 -*- ############################################################################## # # Odoo, Open Source Management Solution # This module copyright (C) 2014 Savoir-faire Linux # (<http://www.savoirfairelinux.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp import models, fields class hr_academic(models.Model): _name = 'hr.academic' _inherit = 'hr.curriculum' diploma = fields.Char(string='Diploma', translate=True) study_field = fields.Char(string='Field of study', translate=True,) activities = fields.Text(string='Activities and associations', translate=True)
Endika/hr
hr_experience/models/hr_academic.py
Python
agpl-3.0
1,388
# 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. # pylint: disable=missing-docstring from __future__ import print_function import mxnet as mx import numpy as np try: import cPickle as pickle except ModuleNotFoundError: import pickle def extract_feature(sym, args, auxs, data_iter, N, xpu=mx.cpu()): input_buffs = [mx.nd.empty(shape, ctx=xpu) for k, shape in data_iter.provide_data] input_names = [k for k, shape in data_iter.provide_data] args = dict(args, **dict(zip(input_names, input_buffs))) exe = sym.bind(xpu, args=args, aux_states=auxs) outputs = [[] for _ in exe.outputs] output_buffs = None data_iter.hard_reset() for batch in data_iter: for data, buff in zip(batch.data, input_buffs): data.copyto(buff) exe.forward(is_train=False) if output_buffs is None: output_buffs = [mx.nd.empty(i.shape, ctx=mx.cpu()) for i in exe.outputs] else: for out, buff in zip(outputs, output_buffs): out.append(buff.asnumpy()) for out, buff in zip(exe.outputs, output_buffs): out.copyto(buff) for out, buff in zip(outputs, output_buffs): out.append(buff.asnumpy()) outputs = [np.concatenate(i, axis=0)[:N] for i in outputs] return dict(zip(sym.list_outputs(), outputs)) class MXModel(object): def __init__(self, xpu=mx.cpu(), *args, **kwargs): self.xpu = xpu self.loss = None self.args = {} self.args_grad = {} self.args_mult = {} self.auxs = {} self.setup(*args, **kwargs) def save(self, fname): args_save = {key: v.asnumpy() for key, v in self.args.items()} with open(fname, 'wb') as fout: pickle.dump(args_save, fout) def load(self, fname): with open(fname, 'rb') as fin: args_save = pickle.load(fin) for key, v in args_save.items(): if key in self.args: self.args[key][:] = v def setup(self, *args, **kwargs): raise NotImplementedError("must override this")
jiajiechen/mxnet
example/autoencoder/model.py
Python
apache-2.0
2,838
#!/usr/bin/env python # ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- """Unit tests for aggregator module.""" import unittest2 as unittest from nupic.data import aggregator class AggregatorTest(unittest.TestCase): """Unit tests for misc. aggregator functions.""" def testFixAggregationDict(self): # Simplest case. result = aggregator._aggr_weighted_mean((1.0, 1.0), (1, 1)) self.assertAlmostEqual(result, 1.0, places=7) # Simple non-uniform case. result = aggregator._aggr_weighted_mean((1.0, 2.0), (1, 2)) self.assertAlmostEqual(result, 5.0/3.0, places=7) # Make sure it handles integer values as integers. result = aggregator._aggr_weighted_mean((1, 2), (1, 2)) self.assertAlmostEqual(result, 1, places=7) # More-than-two case. result = aggregator._aggr_weighted_mean((1.0, 2.0, 3.0), (1, 2, 3)) self.assertAlmostEqual(result, 14.0/6.0, places=7) # Handle zeros. result = aggregator._aggr_weighted_mean((1.0, 0.0, 3.0), (1, 2, 3)) self.assertAlmostEqual(result, 10.0/6.0, places=7) # Handle negative numbers. result = aggregator._aggr_weighted_mean((1.0, -2.0, 3.0), (1, 2, 3)) self.assertAlmostEqual(result, 1.0, places=7) if __name__ == '__main__': unittest.main()
0x0all/nupic
tests/unit/py2/nupic/data/aggregator_test.py
Python
gpl-3.0
2,186
# (c) 2016, Matt Davis <mdavis@ansible.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 import time from datetime import datetime, timedelta from ansible.errors import AnsibleError from ansible.plugins.action import ActionBase from ansible.module_utils._text import to_native try: from __main__ import display except ImportError: from ansible.utils.display import Display display = Display() class TimedOutException(Exception): pass class ActionModule(ActionBase): TRANSFERS_FILES = False DEFAULT_REBOOT_TIMEOUT = 600 DEFAULT_CONNECT_TIMEOUT = 5 DEFAULT_PRE_REBOOT_DELAY = 2 DEFAULT_POST_REBOOT_DELAY = 0 DEFAULT_TEST_COMMAND = 'whoami' DEFAULT_REBOOT_MESSAGE = 'Reboot initiated by Ansible.' def get_system_uptime(self): uptime_command = "(Get-WmiObject -ClassName Win32_OperatingSystem).LastBootUpTime" (rc, stdout, stderr) = self._connection.exec_command(uptime_command) if rc != 0: raise Exception("win_reboot: failed to get host uptime info, rc: %d, stdout: %s, stderr: %s" % (rc, stdout, stderr)) return stdout def do_until_success_or_timeout(self, what, timeout, what_desc, fail_sleep=1): max_end_time = datetime.utcnow() + timedelta(seconds=timeout) exc = "" while datetime.utcnow() < max_end_time: try: what() if what_desc: display.debug("win_reboot: %s success" % what_desc) return except Exception as e: exc = e if what_desc: display.debug("win_reboot: %s fail (expected), retrying in %d seconds..." % (what_desc, fail_sleep)) time.sleep(fail_sleep) raise TimedOutException("timed out waiting for %s: %s" % (what_desc, exc)) def run(self, tmp=None, task_vars=None): self._supports_check_mode = True self._supports_async = True if self._play_context.check_mode: return dict(changed=True, elapsed=0, rebooted=True) if task_vars is None: task_vars = dict() result = super(ActionModule, self).run(tmp, task_vars) if result.get('skipped', False) or result.get('failed', False): return result # Handle timeout parameters and its alias deprecated_args = { 'shutdown_timeout': '2.5', 'shutdown_timeout_sec': '2.5', } for arg, version in deprecated_args.items(): if self._task.args.get(arg) is not None: display.warning("Since Ansible %s, %s is no longer used with win_reboot" % (arg, version)) if self._task.args.get('connect_timeout') is not None: connect_timeout = int(self._task.args.get('connect_timeout', self.DEFAULT_CONNECT_TIMEOUT)) else: connect_timeout = int(self._task.args.get('connect_timeout_sec', self.DEFAULT_CONNECT_TIMEOUT)) if self._task.args.get('reboot_timeout') is not None: reboot_timeout = int(self._task.args.get('reboot_timeout', self.DEFAULT_REBOOT_TIMEOUT)) else: reboot_timeout = int(self._task.args.get('reboot_timeout_sec', self.DEFAULT_REBOOT_TIMEOUT)) if self._task.args.get('pre_reboot_delay') is not None: pre_reboot_delay = int(self._task.args.get('pre_reboot_delay', self.DEFAULT_PRE_REBOOT_DELAY)) else: pre_reboot_delay = int(self._task.args.get('pre_reboot_delay_sec', self.DEFAULT_PRE_REBOOT_DELAY)) if self._task.args.get('post_reboot_delay') is not None: post_reboot_delay = int(self._task.args.get('post_reboot_delay', self.DEFAULT_POST_REBOOT_DELAY)) else: post_reboot_delay = int(self._task.args.get('post_reboot_delay_sec', self.DEFAULT_POST_REBOOT_DELAY)) test_command = str(self._task.args.get('test_command', self.DEFAULT_TEST_COMMAND)) msg = str(self._task.args.get('msg', self.DEFAULT_REBOOT_MESSAGE)) # Get current uptime try: before_uptime = self.get_system_uptime() except Exception as e: result['failed'] = True result['reboot'] = False result['msg'] = to_native(e) return result # Initiate reboot display.vvv("rebooting server") (rc, stdout, stderr) = self._connection.exec_command('shutdown /r /t %d /c "%s"' % (pre_reboot_delay, msg)) # Test for "A system shutdown has already been scheduled. (1190)" and handle it gracefully if rc == 1190: display.warning('A scheduled reboot was pre-empted by Ansible.') # Try to abort (this may fail if it was already aborted) (rc, stdout1, stderr1) = self._connection.exec_command('shutdown /a') # Initiate reboot again (rc, stdout2, stderr2) = self._connection.exec_command('shutdown /r /t %d' % pre_reboot_delay) stdout += stdout1 + stdout2 stderr += stderr1 + stderr2 if rc != 0: result['failed'] = True result['rebooted'] = False result['msg'] = "Shutdown command failed, error text was %s" % stderr return result start = datetime.now() # Get the original connection_timeout option var so it can be reset after connection_timeout_orig = None try: connection_timeout_orig = self._connection.get_option('connection_timeout') except AnsibleError: display.debug("win_reboot: connection_timeout connection option has not been set") try: # keep on checking system uptime with short connection responses def check_uptime(): display.vvv("attempting to get system uptime") # override connection timeout from defaults to custom value try: self._connection.set_options(direct={"connection_timeout": connect_timeout}) self._connection._reset() except AttributeError: display.warning("Connection plugin does not allow the connection timeout to be overridden") # try and get uptime try: current_uptime = self.get_system_uptime() except Exception as e: raise e if current_uptime == before_uptime: raise Exception("uptime has not changed") self.do_until_success_or_timeout(check_uptime, reboot_timeout, what_desc="reboot uptime check success") # reset the connection to clear the custom connection timeout try: self._connection.set_options(direct={"connection_timeout": connection_timeout_orig}) self._connection._reset() except (AnsibleError, AttributeError): display.debug("Failed to reset connection_timeout back to default") # finally run test command to ensure everything is working def run_test_command(): display.vvv("attempting post-reboot test command '%s'" % test_command) (rc, stdout, stderr) = self._connection.exec_command(test_command) if rc != 0: raise Exception('test command failed') # FUTURE: add a stability check (system must remain up for N seconds) to deal with self-multi-reboot updates self.do_until_success_or_timeout(run_test_command, reboot_timeout, what_desc="post-reboot test command success") result['rebooted'] = True result['changed'] = True except TimedOutException as toex: result['failed'] = True result['rebooted'] = True result['msg'] = to_native(toex) if post_reboot_delay != 0: display.vvv("win_reboot: waiting an additional %d seconds" % post_reboot_delay) time.sleep(post_reboot_delay) elapsed = datetime.now() - start result['elapsed'] = elapsed.seconds return result
photoninger/ansible
lib/ansible/plugins/action/win_reboot.py
Python
gpl-3.0
8,292
# Copyright (c) 2011 Zadara Storage Inc. # Copyright (c) 2011 OpenStack Foundation # Copyright 2011 University of Southern California # 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. """ Unit Tests for volume types extra specs code """ from cinder import context from cinder import db from cinder import test class VolumeTypeExtraSpecsTestCase(test.TestCase): def setUp(self): super(VolumeTypeExtraSpecsTestCase, self).setUp() self.context = context.get_admin_context() self.vol_type1 = dict(name="TEST: Regular volume test") self.vol_type1_specs = dict(vol_extra1="value1", vol_extra2="value2", vol_extra3=3) self.vol_type1['extra_specs'] = self.vol_type1_specs ref = db.volume_type_create(self.context, self.vol_type1) self.addCleanup(db.volume_type_destroy, context.get_admin_context(), self.vol_type1['id']) self.volume_type1_id = ref.id for k, v in self.vol_type1_specs.iteritems(): self.vol_type1_specs[k] = str(v) self.vol_type2_noextra = dict(name="TEST: Volume type without extra") ref = db.volume_type_create(self.context, self.vol_type2_noextra) self.addCleanup(db.volume_type_destroy, context.get_admin_context(), self.vol_type2_noextra['id']) self.vol_type2_id = ref.id def test_volume_type_specs_get(self): expected_specs = self.vol_type1_specs.copy() actual_specs = db.volume_type_extra_specs_get( context.get_admin_context(), self.volume_type1_id) self.assertEqual(expected_specs, actual_specs) def test_volume_type_extra_specs_delete(self): expected_specs = self.vol_type1_specs.copy() del expected_specs['vol_extra2'] db.volume_type_extra_specs_delete(context.get_admin_context(), self.volume_type1_id, 'vol_extra2') actual_specs = db.volume_type_extra_specs_get( context.get_admin_context(), self.volume_type1_id) self.assertEqual(expected_specs, actual_specs) def test_volume_type_extra_specs_update(self): expected_specs = self.vol_type1_specs.copy() expected_specs['vol_extra3'] = "4" db.volume_type_extra_specs_update_or_create( context.get_admin_context(), self.volume_type1_id, dict(vol_extra3=4)) actual_specs = db.volume_type_extra_specs_get( context.get_admin_context(), self.volume_type1_id) self.assertEqual(expected_specs, actual_specs) def test_volume_type_extra_specs_create(self): expected_specs = self.vol_type1_specs.copy() expected_specs['vol_extra4'] = 'value4' expected_specs['vol_extra5'] = 'value5' db.volume_type_extra_specs_update_or_create( context.get_admin_context(), self.volume_type1_id, dict(vol_extra4="value4", vol_extra5="value5")) actual_specs = db.volume_type_extra_specs_get( context.get_admin_context(), self.volume_type1_id) self.assertEqual(expected_specs, actual_specs) def test_volume_type_get_with_extra_specs(self): volume_type = db.volume_type_get( context.get_admin_context(), self.volume_type1_id) self.assertEqual(volume_type['extra_specs'], self.vol_type1_specs) volume_type = db.volume_type_get( context.get_admin_context(), self.vol_type2_id) self.assertEqual(volume_type['extra_specs'], {}) def test_volume_type_get_by_name_with_extra_specs(self): volume_type = db.volume_type_get_by_name( context.get_admin_context(), self.vol_type1['name']) self.assertEqual(volume_type['extra_specs'], self.vol_type1_specs) volume_type = db.volume_type_get_by_name( context.get_admin_context(), self.vol_type2_noextra['name']) self.assertEqual(volume_type['extra_specs'], {}) def test_volume_type_get_all(self): expected_specs = self.vol_type1_specs.copy() types = db.volume_type_get_all(context.get_admin_context()) self.assertEqual( types[self.vol_type1['name']]['extra_specs'], expected_specs) self.assertEqual( types[self.vol_type2_noextra['name']]['extra_specs'], {})
rakeshmi/cinder
cinder/tests/unit/test_volume_types_extra_specs.py
Python
apache-2.0
5,074
# -*- encoding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Copyright (c) 2011 Cubic ERP - Teradata SAC. (https://cubicerp.com). { "name": "Bolivia - Accounting", "version": "2.0", "description": """ Bolivian accounting chart and tax localization. Plan contable boliviano e impuestos de acuerdo a disposiciones vigentes """, "author": "Cubic ERP", "website": "https://cubicERP.com", 'category': 'Localization', "depends": ["account"], "data": [ "l10n_bo_chart.xml", "account_tax.xml", "account_chart_template.yml", ], "installable": True, }
vileopratama/vitech
src/addons/l10n_bo/__openerp__.py
Python
mit
656
# -*- coding: utf-8 -*- """ The MIT License (MIT) Copyright (c) 2015-2016 Rapptz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from discord.errors import DiscordException __all__ = [ 'CommandError', 'MissingRequiredArgument', 'BadArgument', 'NoPrivateMessage', 'CheckFailure', 'CommandNotFound', 'DisabledCommand', 'CommandInvokeError', 'TooManyArguments', 'UserInputError', 'CommandOnCooldown' ] class CommandError(DiscordException): """The base exception type for all command related errors. This inherits from :exc:`discord.DiscordException`. This exception and exceptions derived from it are handled in a special way as they are caught and passed into a special event from :class:`Bot`\, :func:`on_command_error`. """ def __init__(self, message=None, *args): if message is not None: # clean-up @everyone and @here mentions m = message.replace('@everyone', '@\u200beveryone').replace('@here', '@\u200bhere') super().__init__(m, *args) else: super().__init__(*args) class UserInputError(CommandError): """The base exception type for errors that involve errors regarding user input. This inherits from :exc:`CommandError`. """ pass class CommandNotFound(CommandError): """Exception raised when a command is attempted to be invoked but no command under that name is found. This is not raised for invalid subcommands, rather just the initial main command that is attempted to be invoked. """ pass class MissingRequiredArgument(UserInputError): """Exception raised when parsing a command and a parameter that is required is not encountered. """ pass class TooManyArguments(UserInputError): """Exception raised when the command was passed too many arguments and its :attr:`Command.ignore_extra` attribute was not set to ``True``. """ pass class BadArgument(UserInputError): """Exception raised when a parsing or conversion failure is encountered on an argument to pass into a command. """ pass class NoPrivateMessage(CommandError): """Exception raised when an operation does not work in private message contexts. """ pass class CheckFailure(CommandError): """Exception raised when the predicates in :attr:`Command.checks` have failed.""" pass class DisabledCommand(CommandError): """Exception raised when the command being invoked is disabled.""" pass class CommandInvokeError(CommandError): """Exception raised when the command being invoked raised an exception. Attributes ----------- original The original exception that was raised. You can also get this via the ``__cause__`` attribute. """ def __init__(self, e): self.original = e super().__init__('Command raised an exception: {0.__class__.__name__}: {0}'.format(e)) class CommandOnCooldown(CommandError): """Exception raised when the command being invoked is on cooldown. Attributes ----------- cooldown: Cooldown A class with attributes ``rate``, ``per``, and ``type`` similar to the :func:`cooldown` decorator. retry_after: float The amount of seconds to wait before you can retry again. """ def __init__(self, cooldown, retry_after): self.cooldown = cooldown self.retry_after = retry_after super().__init__('You are on cooldown. Try again in {:.2f}s'.format(retry_after))
LordDamionDevil/Lony
lib/discord/ext/commands/errors.py
Python
gpl-3.0
4,513
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'DjangoApplication1.views.home', name='home'), # url(r'^DjangoApplication1/', include('DjangoApplication1.fob.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), url(r'^Oar/$', 'Oar.views.index'), url(r'^/$', 'oar.views.main'), url(r'^loop_nobom/$', 'Oar.views.loop_nobom'), url(r'^loop/$', 'Oar.views.loop'), url(r'^loop2/$', 'Oar.views.loop2'), )
jkorell/PTVS
Python/Tests/TestData/DjangoProject/urls.py
Python
apache-2.0
813
import imp import os import io import sys from mock import patch from gp_unittest import GpTestCase class GpSshTestCase(GpTestCase): def setUp(self): # because gpssh does not have a .py extension, we have to use imp to import it # if we had a gpssh.py, this is equivalent to: # import gpssh # self.subject = gpssh gpssh_file = os.path.abspath(os.path.dirname(__file__) + "/../../../gpssh") self.subject = imp.load_source('gpssh', gpssh_file) self.old_sys_argv = sys.argv sys.argv = [] def tearDown(self): sys.argv = self.old_sys_argv @patch('sys.exit') def test_when_run_without_args_prints_help_text(self, sys_exit_mock): sys_exit_mock.side_effect = Exception("on purpose") # GOOD_MOCK_EXAMPLE of stdout with patch('sys.stdout', new=io.BytesIO()) as mock_stdout: with self.assertRaisesRegexp(Exception, "on purpose"): self.subject.main() self.assertIn('gpssh -- ssh access to multiple hosts at once', mock_stdout.getvalue()) @patch('sys.exit') def test_happy_ssh_to_localhost_succeeds(self, sys_mock): sys.argv = ['', '-h', 'localhost', 'uptime'] self.subject.main() sys_mock.assert_called_with(0)
edespino/gpdb
gpMgmt/bin/gppylib/test/unit/test_unit_gpssh.py
Python
apache-2.0
1,292
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import itertools import operator import uuid from functools import partial from inspect import getmembers from io import FileIO from six import iteritems, string_types, text_type from jinja2.exceptions import UndefinedError from ansible.errors import AnsibleParserError from ansible.parsing import DataLoader from ansible.playbook.attribute import Attribute, FieldAttribute from ansible.template import Templar from ansible.utils.boolean import boolean from ansible.utils.debug import debug from ansible.utils.vars import combine_vars, isidentifier from ansible.template import template class Base: # connection/transport _connection = FieldAttribute(isa='string') _port = FieldAttribute(isa='int') _remote_user = FieldAttribute(isa='string') # variables _vars = FieldAttribute(isa='dict', default=dict(), priority=100) # flags and misc. settings _environment = FieldAttribute(isa='list') _no_log = FieldAttribute(isa='bool') # param names which have been deprecated/removed DEPRECATED_ATTRIBUTES = [ 'sudo', 'sudo_user', 'sudo_pass', 'sudo_exe', 'sudo_flags', 'su', 'su_user', 'su_pass', 'su_exe', 'su_flags', ] def __init__(self): # initialize the data loader and variable manager, which will be provided # later when the object is actually loaded self._loader = None self._variable_manager = None # every object gets a random uuid: self._uuid = uuid.uuid4() # and initialize the base attributes self._initialize_base_attributes() try: from __main__ import display self._display = display except ImportError: from ansible.utils.display import Display self._display = Display() # The following three functions are used to programatically define data # descriptors (aka properties) for the Attributes of all of the playbook # objects (tasks, blocks, plays, etc). # # The function signature is a little strange because of how we define # them. We use partial to give each method the name of the Attribute that # it is for. Since partial prefills the positional arguments at the # beginning of the function we end up with the first positional argument # being allocated to the name instead of to the class instance (self) as # normal. To deal with that we make the property name field the first # positional argument and self the second arg. # # Because these methods are defined inside of the class, they get bound to # the instance when the object is created. After we run partial on them # and put the result back into the class as a property, they get bound # a second time. This leads to self being placed in the arguments twice. # To work around that, we mark the functions as @staticmethod so that the # first binding to the instance doesn't happen. @staticmethod def _generic_g(prop_name, self): method = "_get_attr_%s" % prop_name if hasattr(self, method): return getattr(self, method)() value = self._attributes[prop_name] if value is None and hasattr(self, '_get_parent_attribute'): value = self._get_parent_attribute(prop_name) return value @staticmethod def _generic_s(prop_name, self, value): self._attributes[prop_name] = value @staticmethod def _generic_d(prop_name, self): del self._attributes[prop_name] def _get_base_attributes(self): ''' Returns the list of attributes for this class (or any subclass thereof). If the attribute name starts with an underscore, it is removed ''' base_attributes = dict() for (name, value) in getmembers(self.__class__): if isinstance(value, Attribute): if name.startswith('_'): name = name[1:] base_attributes[name] = value return base_attributes def _initialize_base_attributes(self): # each class knows attributes set upon it, see Task.py for example self._attributes = dict() for (name, value) in self._get_base_attributes().items(): getter = partial(self._generic_g, name) setter = partial(self._generic_s, name) deleter = partial(self._generic_d, name) # Place the property into the class so that cls.name is the # property functions. setattr(Base, name, property(getter, setter, deleter)) # Place the value into the instance so that the property can # process and hold that value/ setattr(self, name, value.default) def preprocess_data(self, ds): ''' infrequently used method to do some pre-processing of legacy terms ''' for base_class in self.__class__.mro(): method = getattr(self, "_preprocess_data_%s" % base_class.__name__.lower(), None) if method: return method(ds) return ds def load_data(self, ds, variable_manager=None, loader=None): ''' walk the input datastructure and assign any values ''' assert ds is not None # cache the datastructure internally setattr(self, '_ds', ds) # the variable manager class is used to manage and merge variables # down to a single dictionary for reference in templating, etc. self._variable_manager = variable_manager # the data loader class is used to parse data from strings and files if loader is not None: self._loader = loader else: self._loader = DataLoader() # call the preprocess_data() function to massage the data into # something we can more easily parse, and then call the validation # function on it to ensure there are no incorrect key values ds = self.preprocess_data(ds) self._validate_attributes(ds) # Walk all attributes in the class. We sort them based on their priority # so that certain fields can be loaded before others, if they are dependent. # FIXME: we currently don't do anything with private attributes but # may later decide to filter them out of 'ds' here. base_attributes = self._get_base_attributes() for name, attr in sorted(base_attributes.items(), key=operator.itemgetter(1)): # copy the value over unless a _load_field method is defined if name in ds: method = getattr(self, '_load_%s' % name, None) if method: self._attributes[name] = method(name, ds[name]) else: self._attributes[name] = ds[name] # run early, non-critical validation self.validate() # return the constructed object return self def get_ds(self): try: return getattr(self, '_ds') except AttributeError: return None def get_loader(self): return self._loader def get_variable_manager(self): return self._variable_manager def _validate_attributes(self, ds): ''' Ensures that there are no keys in the datastructure which do not map to attributes for this object. ''' valid_attrs = frozenset(name for name in self._get_base_attributes()) for key in ds: if key not in valid_attrs: raise AnsibleParserError("'%s' is not a valid attribute for a %s" % (key, self.__class__.__name__), obj=ds) def validate(self, all_vars=dict()): ''' validation that is done at parse time, not load time ''' # walk all fields in the object for (name, attribute) in iteritems(self._get_base_attributes()): # run validator only if present method = getattr(self, '_validate_%s' % name, None) if method: method(attribute, name, getattr(self, name)) else: # and make sure the attribute is of the type it should be value = getattr(self, name) if value is not None: if attribute.isa == 'string' and isinstance(value, (list, dict)): raise AnsibleParserError("The field '%s' is supposed to be a string type, however the incoming data structure is a %s" % (name, type(value)), obj=self.get_ds()) def copy(self): ''' Create a copy of this object and return it. ''' new_me = self.__class__() for name in self._get_base_attributes(): setattr(new_me, name, getattr(self, name)) new_me._loader = self._loader new_me._variable_manager = self._variable_manager # if the ds value was set on the object, copy it to the new copy too if hasattr(self, '_ds'): new_me._ds = self._ds return new_me def post_validate(self, templar): ''' we can't tell that everything is of the right type until we have all the variables. Run basic types (from isa) as well as any _post_validate_<foo> functions. ''' basedir = None if self._loader is not None: basedir = self._loader.get_basedir() # save the omit value for later checking omit_value = templar._available_variables.get('omit') for (name, attribute) in iteritems(self._get_base_attributes()): if getattr(self, name) is None: if not attribute.required: continue else: raise AnsibleParserError("the field '%s' is required but was not set" % name) elif not attribute.always_post_validate and self.__class__.__name__ not in ('Task', 'Handler', 'PlayContext'): # Intermediate objects like Play() won't have their fields validated by # default, as their values are often inherited by other objects and validated # later, so we don't want them to fail out early continue try: # Run the post-validator if present. These methods are responsible for # using the given templar to template the values, if required. method = getattr(self, '_post_validate_%s' % name, None) if method: value = method(attribute, getattr(self, name), templar) else: # if the attribute contains a variable, template it now value = templar.template(getattr(self, name)) # if this evaluated to the omit value, set the value back to # the default specified in the FieldAttribute and move on if omit_value is not None and value == omit_value: value = attribute.default continue # and make sure the attribute is of the type it should be if value is not None: if attribute.isa == 'string': value = text_type(value) elif attribute.isa == 'int': value = int(value) elif attribute.isa == 'float': value = float(value) elif attribute.isa == 'bool': value = boolean(value) elif attribute.isa == 'percent': # special value, which may be an integer or float # with an optional '%' at the end if isinstance(value, string_types) and '%' in value: value = value.replace('%', '') value = float(value) elif attribute.isa == 'list': if value is None: value = [] elif not isinstance(value, list): value = [ value ] if attribute.listof is not None: for item in value: if not isinstance(item, attribute.listof): raise AnsibleParserError("the field '%s' should be a list of %s, but the item '%s' is a %s" % (name, attribute.listof, item, type(item)), obj=self.get_ds()) elif attribute.required and attribute.listof == string_types: if item is None or item.strip() == "": raise AnsibleParserError("the field '%s' is required, and cannot have empty values" % (name,), obj=self.get_ds()) elif attribute.isa == 'set': if value is None: value = set() else: if not isinstance(value, (list, set)): value = [ value ] if not isinstance(value, set): value = set(value) elif attribute.isa == 'dict': if value is None: value = dict() elif not isinstance(value, dict): raise TypeError("%s is not a dictionary" % value) # and assign the massaged value back to the attribute field setattr(self, name, value) except (TypeError, ValueError) as e: raise AnsibleParserError("the field '%s' has an invalid value (%s), and could not be converted to an %s. Error was: %s" % (name, value, attribute.isa, e), obj=self.get_ds()) except UndefinedError as e: if templar._fail_on_undefined_errors and name != 'name': raise AnsibleParserError("the field '%s' has an invalid value, which appears to include a variable that is undefined. The error was: %s" % (name,e), obj=self.get_ds()) def serialize(self): ''' Serializes the object derived from the base object into a dictionary of values. This only serializes the field attributes for the object, so this may need to be overridden for any classes which wish to add additional items not stored as field attributes. ''' repr = dict() for name in self._get_base_attributes(): repr[name] = getattr(self, name) # serialize the uuid field repr['uuid'] = getattr(self, '_uuid') return repr def deserialize(self, data): ''' Given a dictionary of values, load up the field attributes for this object. As with serialize(), if there are any non-field attribute data members, this method will need to be overridden and extended. ''' assert isinstance(data, dict) for (name, attribute) in iteritems(self._get_base_attributes()): if name in data: setattr(self, name, data[name]) else: setattr(self, name, attribute.default) # restore the UUID field setattr(self, '_uuid', data.get('uuid')) def _load_vars(self, attr, ds): ''' Vars in a play can be specified either as a dictionary directly, or as a list of dictionaries. If the later, this method will turn the list into a single dictionary. ''' def _validate_variable_keys(ds): for key in ds: if not isidentifier(key): raise TypeError("%s is not a valid variable name" % key) try: if isinstance(ds, dict): _validate_variable_keys(ds) return ds elif isinstance(ds, list): all_vars = dict() for item in ds: if not isinstance(item, dict): raise ValueError _validate_variable_keys(item) all_vars = combine_vars(all_vars, item) return all_vars elif ds is None: return {} else: raise ValueError except ValueError: raise AnsibleParserError("Vars in a %s must be specified as a dictionary, or a list of dictionaries" % self.__class__.__name__, obj=ds) except TypeError as e: raise AnsibleParserError("Invalid variable name in vars specified for %s: %s" % (self.__class__.__name__, e), obj=ds) def _extend_value(self, value, new_value): ''' Will extend the value given with new_value (and will turn both into lists if they are not so already). The values are run through a set to remove duplicate values. ''' if not isinstance(value, list): value = [ value ] if not isinstance(new_value, list): new_value = [ new_value ] #return list(set(value + new_value)) return [i for i,_ in itertools.groupby(value + new_value)] def __getstate__(self): return self.serialize() def __setstate__(self, data): self.__init__() self.deserialize(data)
pheanex/ansible
lib/ansible/playbook/base.py
Python
gpl-3.0
18,228
#!/usr/bin/env python from tempfile import TemporaryFile, SpooledTemporaryFile import os, sys, re, socket, time, pickle, csv, uuid, subprocess, argparse, decimal, select, platform class LLDB: def __init__(self): self.debugger = lldb.SBDebugger.Create() self.command_interpreter = self.debugger.GetCommandInterpreter() self.target = self.debugger.CreateTargetWithFileAndArch(None, None) self.listener = lldb.SBListener("event_listener") self.error = lldb.SBError() def __del__(self): lldb.SBDebugger.Destroy(self.debugger) def _parseStackTrace(self, gibberish): return gibberish def _run_commands(self, commands): tmp_text = '' return_obj = lldb.SBCommandReturnObject() for command in commands: self.command_interpreter.HandleCommand(command, return_obj) if return_obj.Succeeded(): if command == 'process status': tmp_text += '\n########################################################\n## Process Status:\n##\n' tmp_text += return_obj.GetOutput() elif command == 'bt': tmp_text += '\n########################################################\n## Backtrace:\n##\n' tmp_text += return_obj.GetOutput() return tmp_text def getStackTrace(self, pid): event = lldb.SBEvent() lldb_results = '' state = 0 attach_info = lldb.SBAttachInfo(int(pid)) process = self.target.Attach(attach_info, self.error) process.GetBroadcaster().AddListener(self.listener, lldb.SBProcess.eBroadcastBitStateChanged) done = False while not done: if self.listener.WaitForEvent(lldb.UINT32_MAX, event): state = lldb.SBProcess.GetStateFromEvent(event) if state == lldb.eStateExited: done = True elif state == lldb.eStateStopped: lldb_results = self._run_commands(['process status', 'bt', 'cont']) done = True elif state == lldb.eStateRunning: self._run_commands(['process interrupt']) if state == lldb.eStateCrashed or state == lldb.eStateInvalid or state == lldb.eStateExited: return 'Binary exited before sample could be taken' time.sleep(0.03) # Due to some strange race condition we have to wait until eState is running # before we can pass the 'detach, quit' command. Why we can not do this all in # one go... bug? done = False while not done: if self.listener.WaitForEvent(lldb.UINT32_MAX, event): state = lldb.SBProcess.GetStateFromEvent(event) if state == lldb.eStateRunning: self._run_commands(['detach', 'quit']) done = True if state == lldb.eStateCrashed or state == lldb.eStateInvalid or state == lldb.eStateExited: return 'Binary exited before sample could be taken' time.sleep(0.03) return self._parseStackTrace(lldb_results) class GDB: def _parseStackTrace(self, gibberish): not_gibberish = re.findall(r'\(gdb\) (#.*)\(gdb\)', gibberish, re.DOTALL) if len(not_gibberish) != 0: return not_gibberish[0] else: return 'Stack Trace failed:', gibberish def _waitForResponse(self, wait=True): while wait: self.gdb_stdout.seek(self.last_position) for line in self.gdb_stdout: if line == '(gdb) ': self.last_position = self.gdb_stdout.tell() return True time.sleep(0.05) time.sleep(0.05) return True def getStackTrace(self, pid): gdb_commands = [ 'attach ' + pid + '\n', 'set verbose off\n', 'thread\n', 'apply\n', 'all\n', 'bt\n', 'quit\n', 'y\n' ] self.gdb_stdout = SpooledTemporaryFile() self.last_position = 0 gdb_process = subprocess.Popen([which('gdb'), '-nx'], stdin=subprocess.PIPE, stdout=self.gdb_stdout, stderr=self.gdb_stdout) while gdb_process.poll() == None: for command in gdb_commands: if command == gdb_commands[-1]: gdb_commands = [] elif self._waitForResponse(): # I have seen GDB exit out from under us try: gdb_process.stdin.write(command) except: pass self.gdb_stdout.seek(0) stack_trace = self._parseStackTrace(self.gdb_stdout.read()) self.gdb_stdout.close() return stack_trace class Server: def __init__(self, arguments): self.arguments = arguments self.arguments.cwd = os.getcwd() # Test to see if we are starting as a server if self.arguments.pbs == True: if os.getenv('PBS_NODEFILE') != None: # Initialize an agent, strictly for holding our stdout logs. Give it the UUID of 'server' self.agent = Agent(self.arguments, 'server') if self.arguments.recover: self.logfile = WriteCSV(self.arguments.outfile[0], False) else: self.logfile = WriteCSV(self.arguments.outfile[0], True) self.client_connections = [] self.startServer() else: print 'I could not find your PBS_NODEFILE. Is PBS loaded?' sys.exit(1) # If we are not a server, start the single client else: self.startClient() def startServer(self): # Setup the TCP socket self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server_socket.bind((socket.gethostname(), 0)) self.server_socket.listen(5) (self.host, self.port) = self.server_socket.getsockname() # We will store all connections (sockets objects) made to the server in a list self.client_connections.append(self.server_socket) # Launch the actual binary we want to track self._launchJob() # Now launch all pbs agents self._launchClients() # This is a try so we can handle a keyboard ctrl-c try: # Continue to listen and accept active connections from agents # until all agents report a STOP command. AGENTS_ACTIVE = True while AGENTS_ACTIVE: read_sockets, write_sockets, error_sockets = select.select(self.client_connections,[],[]) for sock in read_sockets: if sock == self.server_socket: # Accept an incomming connection self.client_connections.append(self.server_socket.accept()[0]) else: # Deal with the data being sent to the server by its agents self.handleAgent() # Check to see if _all_ agents are telling the server to stop agent_count = len(self.agent.agent_data.keys()) current_count = 0 for agent in self.agent.agent_data.keys(): if self.agent.agent_data[agent]['STOP']: current_count += 1 # if All Agents have reported a STOP command, begin to exit if current_count == agent_count: AGENTS_ACTIVE = False # Gotta get out of the for loop somehow... break # Sleep a bit before reading additional data time.sleep(self.arguments.repeat_rate[-1]) # Close the server socket self.server_socket.close() # Close the logfile as the server is about to exit self.logfile.close() # Cancel server operations if ctrl-c was pressed except KeyboardInterrupt: print 'Canceled by user. Wrote log:', self.arguments.outfile[0] sys.exit(0) # Normal exiting procedures print '\n\nAll agents have stopped. Log file saved to:', self.arguments.outfile[0] sys.exit(0) def startClient(self): Client(self.arguments) def _launchClients(self): # Read the environment PBS_NODEFILE self._PBS_NODEFILE = open(os.getenv('PBS_NODEFILE'), 'r') nodes = set(self._PBS_NODEFILE.read().split()) # Print some useful information about our setup print 'Memory Logger running on Host:', self.host, 'Port:', self.port, '\nNodes:', ', '.join(nodes), '\nSample rate (including stdout):', self.arguments.repeat_rate[-1], 's (use --repeat-rate to adjust)\nRemote agents delaying', self.arguments.pbs_delay[-1], 'second/s before tracking. (use --pbs-delay to adjust)\n' # Build our command list based on the PBS_NODEFILE command = [] for node in nodes: command.append([ 'ssh', node, 'bash --login -c "source /etc/profile && ' \ + 'sleep ' + str(self.arguments.pbs_delay[-1]) + ' && ' \ + os.path.abspath(__file__) \ + ' --call-back-host ' \ + self.host + ' ' + str(self.port) \ + '"']) # remote into each node and execute another copy of memory_logger.py # with a call back argument to recieve further instructions for pbs_node in command: subprocess.Popen(pbs_node, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Launch the binary we intend to track def _launchJob(self): subprocess.Popen(self.arguments.run[-1].split(), stdout=self.agent.log, stderr=self.agent.log) # A connection has been made from client to server # Capture that data, and determin what to do with it def handleAgent(self): # Loop through all client connections, and receive data if any for agent_socket in self.client_connections: # Completely ignore the server_socket object if agent_socket == self.server_socket: continue # Assign an AgentConnector for the task of handling data between client and server reporting_agent = AgentConnector(self.arguments, agent_socket) # OK... get data from a client and begin new_data = reporting_agent.readData() if new_data != None: # There should be only one dictionary key (were reading data from just one client at a time) agent_uuid = new_data.keys()[0] # Update our dictionary of an agents data self.agent.agent_data[agent_uuid] = new_data[agent_uuid] # Modify incoming Agents timestamp to match Server's time (because every node is a little bit off) if self.arguments.recover: self.agent.agent_data[agent_uuid]['TIMESTAMP'] = GetTime().now - self.agent.delta else: self.agent.agent_data[agent_uuid]['TIMESTAMP'] = GetTime().now # update total usage for all known reporting agents total_usage = 0 for one_agent in self.agent.agent_data.keys(): total_usage += self.agent.agent_data[one_agent]['MEMORY'] self.agent.agent_data[agent_uuid]['TOTAL'] = int(total_usage) # Get any stdout thats happened thus far and apply it to what ever agent just sent us data self.agent.agent_data[agent_uuid]['STDOUT'] = self.agent._getStdout() # Write to our logfile self.logfile.write(self.agent.agent_data[agent_uuid]) # Check for any agents sending a stop command. If we find one, # set some zeroing values, and close that agent's socket. if self.agent.agent_data[agent_uuid]['STOP']: self.agent.agent_data[agent_uuid]['MEMORY'] = 0 agent_socket.close() if agent_socket != self.server_socket: self.client_connections.remove(agent_socket) # Go ahead and set our server agent to STOP as well. # The server will continue recording samples from agents self.agent.agent_data['server']['STOP'] = True # If an Agent has made a request for instructions, handle it here update_client = False if new_data[agent_uuid]['REQUEST'] != None: for request in new_data[agent_uuid]['REQUEST'].iteritems(): if new_data[agent_uuid]['REQUEST'][request[0]] == '': update_client = True # We only support sending any arguments supplied to ther server, back to the agent for request_type in dir(self.arguments): if request[0] == str(request_type): self.agent.agent_data[agent_uuid]['REQUEST'][request[0]] = getattr(self.arguments, request[0]) # If an Agent needed additional instructions, go ahead and re-send those instructions if update_client: reporting_agent.sendData(self.agent.agent_data[agent_uuid]) class Client: def __init__(self, arguments): self.arguments = arguments # Initialize an Agent with a UUID based on our hostname self.my_agent = Agent(arguments, str(uuid.uuid3(uuid.NAMESPACE_DNS, socket.gethostname()))) # Initialize an AgentConnector self.remote_server = AgentConnector(self.arguments) # If client will talk to a server (PBS) if self.arguments.call_back_host: # We know by initializing an agent, agent_data contains the necessary message asking for further instructions self.my_agent.agent_data[self.my_agent.my_uuid] = self.remote_server.sendData(self.my_agent.agent_data) # Apply new instructions received from server (this basically updates our arguments) for request in self.my_agent.agent_data[self.my_agent.my_uuid]['REQUEST'].iteritems(): for request_type in dir(self.arguments): if request[0] == str(request_type): setattr(self.arguments, request[0], request[1]) # Requests have been satisfied, set to None self.my_agent.agent_data[self.my_agent.my_uuid]['REQUEST'] = None # Change to the same directory as the server was when initiated (needed for PBS stuff) os.chdir(self.arguments.cwd) # Client will not be talking to a server, save data to a file instead else: # Deal with --recover if self.arguments.recover: # Do not overwrite the file self.logfile = WriteCSV(self.arguments.outfile[0], False) else: # Overwrite the file self.logfile = WriteCSV(self.arguments.outfile[0], True) # Lets begin! self.startProcess() # This function handles the starting and stoping of the sampler process. # We loop until an agent returns a stop command. def startProcess(self): AGENTS_ACTIVE = True # If we know we are the only client, go ahead and start the process we want to track. if self.arguments.call_back_host == None: subprocess.Popen(self.arguments.run[-1].split(), stdout=self.my_agent.log, stderr=self.my_agent.log) # Delay just a bit to keep from recording a possible zero memory usage as the binary starts up time.sleep(self.arguments.sample_delay[0]) # This is a try so we can handle a keyboard ctrl-c try: # Continue to process data until an Agent reports a STOP command while AGENTS_ACTIVE: # Take a sample current_data = self.my_agent.takeSample() # Handle the data supplied by the Agent. self._handleData(current_data) # If an Agent reported a STOP command, go ahead and begin the shutdown phase if current_data[current_data.keys()[0]]['STOP']: AGENTS_ACTIVE = False # Sleep just a bit between samples, as to not saturate the machine time.sleep(self.arguments.repeat_rate[-1]) # An agent reported a stop command... so let everyone know where the log was saved, and exit! if self.arguments.call_back_host == None: print 'Binary has exited. Wrote log:', self.arguments.outfile[0] # Cancel server operations if ctrl-c was pressed except KeyboardInterrupt: self.logfile.close() print 'Canceled by user. Wrote log:', self.arguments.outfile[0] sys.exit(0) # Everything went smooth. sys.exit(0) # Figure out what to do with the sampled data def _handleData(self, data): # Sending the sampled data to a server if self.arguments.call_back_host: self.remote_server.sendData(data) # Saving the sampled data to a file else: # Compute the TOTAL memory usage to be how much our one agent reported # Because were the only client doing any work data[self.my_agent.my_uuid]['TOTAL'] = data[self.my_agent.my_uuid]['MEMORY'] self.logfile.write(data[self.my_agent.my_uuid]) # If the agent has been told to stop, close the database file if self.my_agent.agent_data[self.my_agent.my_uuid]['STOP'] == True: self.logfile.close() class AgentConnector: """ Functions used to communicate to and from Client and Server. Both Client and Server classes use this object. readData() sendData('message', socket_connection=None) if sendData's socket_connection is None, it will create a new connection to the server based on supplied arguments """ def __init__(self, arguments, connection=None): self.arguments = arguments self.connection = connection self.CREATED_CONNECTION = False # If the connection is None, meaning this object was instanced by a client, # we must create a connection to the server first if self.connection == None and self.arguments.call_back_host != None: self.CREATED_CONNECTION = True self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.connection.settimeout(15) self.connection.connect((self.arguments.call_back_host[0], int(self.arguments.call_back_host[1]))) # read all data sent by an agent def readData(self): # Get how much data there is to receive # The first eight bytes is our data length data_width = int(self.connection.recv(8)) tmp_received = '' # We need to receive precisely the ammount of data the # client is trying to send us. while len(tmp_received) < data_width: if data_width - len(tmp_received) > 1024: tmp_received += self.connection.recv(1024) else: tmp_received += self.connection.recv(data_width - (len(tmp_received))) # unpickle the received message return self._unpickleMessage(tmp_received) # send data to an agent def sendData(self, message): # pickle the data up, and send the message self.connection.sendall(self._pickleMessage(message)) # If we had to create the socket (connection was none), and this client/agent is requesting # instructions, go ahead and read the data that _better be there_ sent to us by the server. if self.CREATED_CONNECTION and message[message.keys()[0]]['REQUEST'] != None: return self.readData() # The following two functions pickle up the data for easy socket transport def _pickleMessage(self, message): t = TemporaryFile() pickle.dump(message, t) t.seek(0) str_msg = t.read() str_len = len(str_msg) message = "%-8d" % (str_len,) + str_msg return message def _unpickleMessage(self, message): t = TemporaryFile() t.write(message) t.seek(0) try: return pickle.load(t) except KeyError: print 'Socket data was not pickled data: ', message except: raise class WriteCSV: def __init__(self, logfile, overwrite): if overwrite: self.file_object = open(logfile, 'w', 1) else: self.file_object = open(logfile, 'a', 1) csv.field_size_limit(sys.maxsize) self.log_file = csv.writer(self.file_object, delimiter=',', quotechar='|', escapechar='\\', quoting=csv.QUOTE_MINIMAL) # Close the logfile def close(self): self.file_object.close() # Write a CSV row def write(self, data): formatted_string = self._formatString(data) self.log_file.writerow(formatted_string) # Format the CSV output def _formatString(self, data): # We will be saving this data in CSV format. Before we do, lets format it a bit here format_order = ['TIMESTAMP', 'TOTAL', 'STDOUT', 'STACK', 'HOSTNAME', 'MEMORY'] formatted_text = [] for item in format_order: # We have to handle python's way of formatting floats to strings specially if item == 'TIMESTAMP': formatted_text.append('%.6f' % data[item]) else: formatted_text.append(data[item]) return formatted_text class Agent: """ Each agent object contains its own sampled log data. The Agent class is responsible for collecting and storing data. machine_id is used to identify the agent. machine_id is supplied by the client class. This allows for multiple agents if desired """ def __init__(self, arguments, machine_id): self.arguments = arguments self.my_uuid = machine_id self.track_process = '' # This log object is for stdout purposes self.log = TemporaryFile() self.log_position = 0 # Discover if --recover is being used. If so, we need to obtain the # timestamp of the last entry in the outfile log... a little bulky # to do... and not a very good place to do it. if self.arguments.recover: if os.path.exists(self.arguments.outfile[-1]): memory_list = [] history_file = open(self.arguments.outfile[-1], 'r') csv.field_size_limit(sys.maxsize) reader = csv.reader(history_file, delimiter=',', quotechar='|', escapechar='\\', quoting=csv.QUOTE_MINIMAL) # Get last item in list. Unfortunately, no way to do this until # we have read the entire file...? Lucky for us, most memory log # files are in the single digit megabytes for row in reader: memory_list.append(row) history_file.close() last_entry = float(memory_list[-1][0]) + self.arguments.repeat_rate[-1] self.delta = (GetTime().now - last_entry) else: print 'Recovery options detected, but I could not find your previous memory log file.' sys.exit(1) else: self.delta = 0 # Create the dictionary to which all sampled data will be stored # NOTE: REQUEST dictionary items are instructions (arguments) we will # ask the server to provide (if we are running with --pbs) # Simply add them here. We _can not_ make the arguments match the # server exactly, this would cause every agent launched to perform # like a server... bad stuff # Example: We added repeat_rate (see dictionary below). Now every # agent would update their repeat_rate according to what the user # supplied as an argument (--repeat_rate 0.02) self.agent_data = { self.my_uuid : { 'HOSTNAME' : socket.gethostname(), 'STDOUT' : '', 'STACK' : '', 'MEMORY' : 0, 'TIMESTAMP' : GetTime().now - self.delta, 'REQUEST' : { 'run' : '', 'pstack' : '', 'repeat_rate' : '', 'cwd' : ''}, 'STOP' : False, 'TOTAL' : 0, 'DEBUG_LOG' : '' } } # NOTE: This is the only function that should be called in this class def takeSample(self): if self.arguments.pstack: self.agent_data[self.my_uuid]['STACK'] = self._getStack() # Always do the following self.agent_data[self.my_uuid]['MEMORY'] = self._getMemory() self.agent_data[self.my_uuid]['STDOUT'] = self._getStdout() if self.arguments.recover: self.agent_data[self.my_uuid]['TIMESTAMP'] = GetTime().now - self.delta else: self.agent_data[self.my_uuid]['TIMESTAMP'] = GetTime().now # Return the data to whom ever asked for it return self.agent_data def _getStdout(self): self.log.seek(self.log_position) output = self.log.read() self.log_position = self.log.tell() sys.stdout.write(output) return output def _getMemory(self): tmp_pids = self._getPIDs() memory_usage = 0 if tmp_pids != {}: for single_pid in tmp_pids.iteritems(): memory_usage += int(single_pid[1][0]) if memory_usage == 0: # Memory usage hit zero? Then assume the binary being tracked has exited. So lets begin doing the same. self.agent_data[self.my_uuid]['DEBUG_LOG'] = 'I found the total memory usage of all my processes hit 0. Stoping' self.agent_data[self.my_uuid]['STOP'] = True return 0 return int(memory_usage) # No binay even detected? Lets assume it exited, so we should begin doing the same. self.agent_data[self.my_uuid]['STOP'] = True self.agent_data[self.my_uuid]['DEBUG_LOG'] = 'I found no processes running. Stopping' return 0 def _getStack(self): if self._darwin() == True: stack_trace = LLDB() else: stack_trace = GDB() tmp_pids = self._getPIDs() if tmp_pids != {}: last_pid = sorted([x for x in tmp_pids.keys()])[-1] return stack_trace.getStackTrace(str(last_pid)) else: return '' def _getPIDs(self): pid_list = {} # Determin the binary to sample and store it. Doing the findCommand is a little expensive. if self.track_process == '': self.track_process = self._findCommand(''.join(self.arguments.run)) # A quick way to safely check for the avilability of needed tools self._verifyCommand(['ps']) # If we are tracking a binary if self.arguments.run: command = [which('ps'), '-e', '-o', 'pid,rss,user,args'] tmp_proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) all_pids = tmp_proc.communicate()[0].split('\n') # Figure out what we are allowed to track (strip away mpiexec, processes not owned by us, etc) for single_pid in all_pids: if single_pid.find(self.track_process) != -1 and \ single_pid.find(__file__) == -1 and \ single_pid.find('mpirun') == -1 and \ single_pid.find(os.getenv('USER')) != -1 and \ single_pid.find('mpiexec') == -1: pid_list[int(single_pid.split()[0])] = [] pid_list[int(single_pid.split()[0])].extend([single_pid.split()[1], single_pid.split()[3]]) return pid_list def _verifyCommand(self, command_list): for command in command_list: if which(command) == None: print 'Command not found:', command sys.exit(1) # determine if we are running on a darwin kernel def _darwin(self): if platform.platform(0, 1).split('-')[:-1][0].find('Darwin') != -1: return True # Determine the command we are going to track # A few things are happening here; first we strip off any MPI commands # we then loop through the remaining items until we find a matching path # exp: mpiexec -n 12 ../../../moose_test-opt -i simple_diffusion.i -r 6 # would first strip off mpiexec, check for the presence of -n in our # current directory, then 12, then ../../../moose_test-opt <- found. It would # stop and return the base name (moose_test-opt). def _findCommand(self, command): if command.find('mpiexec') == 0 or command.find('mpirun') == 0: for binary in command.split(): if os.path.exists(binary): return os.path.split(binary)[1] elif os.path.exists(command.split()[0]): return os.path.split(command.split()[0])[1] class GetTime: """A simple formatted time object. """ def __init__(self, posix_time=None): import datetime if posix_time == None: self.posix_time = datetime.datetime.now() else: self.posix_time = datetime.datetime.fromtimestamp(posix_time) self.now = float(datetime.datetime.now().strftime('%s.%f')) self.microsecond = self.posix_time.microsecond self.second = self.posix_time.second self.minute = self.posix_time.strftime('%M') self.hour = self.posix_time.strftime('%H') self.day = self.posix_time.strftime('%d') self.month = self.posix_time.strftime('%m') self.year = self.posix_time.year self.dayname = self.posix_time.strftime('%a') self.monthname = self.posix_time.strftime('%b') class MemoryPlotter: def __init__(self, arguments): self.arguments = arguments self.buildGraph() def buildPlots(self): plot_dictionary = {} for log in self.arguments.plot: memory_list = [] if os.path.exists(log): log_file = open(log, 'r') csv.field_size_limit(sys.maxsize) reader = csv.reader(log_file, delimiter=',', quotechar='|', escapechar='\\', quoting=csv.QUOTE_MINIMAL) for row in reader: memory_list.append(row) log_file.close() plot_dictionary[log.split('/')[-1:][0]] = memory_list else: print 'log not found:', log sys.exit(1) return plot_dictionary def buildGraph(self): try: import matplotlib.pyplot as plt except ImportError: print 'Error importing matplotlib. Matplotlib not available on this system?' sys.exit(1) plot_dictionary = self.buildPlots() fig = plt.figure() plot_list = [] tmp_plot = [] tmp_legend = [] self.stdout_msgs = {} self.pstack_msgs = {} self.multiples = 1 self.memory_label = 'Memory in Bytes' # Try and calculate memory sizes, so we can move annotations around a bit more accurately largest_memory = [] for plot_name, value_list in plot_dictionary.iteritems(): for records in value_list: largest_memory.append(int(records[1])) largest_memory.sort() # Determine the scale of the graph suffixes = ["Terabytes", "Gigabytes", "Megabytes", "Kilobytes", "Bytes"] multiplier = 1 << 40; index = 0 while largest_memory[-1] < multiplier and multiplier >= 1: multiplier = multiplier >> 10 index = index + 1 self.multiples = multiplier self.memory_label = "Memory in " + suffixes[index-1] # Loop through each log file for plot_name, value_list in plot_dictionary.iteritems(): plot_list.append(fig.add_subplot(111)) tmp_memory = [] tmp_time = [] tmp_stdout_x = [] tmp_stdout_y = [] tmp_pstack_x = [] tmp_pstack_y = [] stdout_msg = [] pstack_msg = [] # Get the start time, and make this 0 try: tmp_zero = decimal.Decimal(value_list[0][0]) except: print 'Could not parse log file:', plot_name, 'is this a valid memory_logger file?' sys.exit(1) # Populate the graph for records in value_list: tmp_memory.append(decimal.Decimal(records[1]) / self.multiples) tmp_time.append(str(decimal.Decimal(records[0]) - tmp_zero)) if len(records[2]) > 0 and self.arguments.stdout: tmp_stdout_x.append(tmp_time[-1]) tmp_stdout_y.append(tmp_memory[-1]) stdout_msg.append(records[2]) if len(records[3]) > 0 and self.arguments.pstack: tmp_pstack_x.append(tmp_time[-1]) tmp_pstack_y.append(tmp_memory[-1]) pstack_msg.append(records[3]) # Do the actual plotting: f, = plot_list[-1].plot(tmp_time, tmp_memory) tmp_plot.append(f) tmp_legend.append(plot_name) plot_list[-1].grid(True) plot_list[-1].set_ylabel(self.memory_label) plot_list[-1].set_xlabel('Time in Seconds') # Plot annotations if self.arguments.stdout: stdout_line, = plot_list[-1].plot(tmp_stdout_x, tmp_stdout_y, 'x', picker=10, color=f.get_color()) next_index = str(len(plot_list)) stdout_line.set_gid('stdout' + next_index) self.stdout_msgs[next_index] = stdout_msg self.buildAnnotation(plot_list[-1], tmp_stdout_x, tmp_stdout_y, stdout_msg, f.get_color()) if self.arguments.pstack: pstack_line, = plot_list[-1].plot(tmp_pstack_x, tmp_pstack_y, 'o', picker=10, color=f.get_color()) next_index = str(len(plot_list)) pstack_line.set_gid('pstack' + next_index) self.pstack_msgs[next_index] = pstack_msg # Make points clickable fig.canvas.mpl_connect('pick_event', self) # Create legend plt.legend(tmp_plot, tmp_legend, loc = 2) plt.show() def __call__(self, event): color_codes = {'RESET':'\033[0m', 'r':'\033[31m','g':'\033[32m','c':'\033[36m','y':'\033[33m', 'b':'\033[34m', 'm':'\033[35m', 'k':'\033[0m', 'w':'\033[0m' } line = event.artist ind = event.ind name = line.get_gid()[:-1] index = line.get_gid()[-1] if self.arguments.stdout and name == 'stdout': if self.arguments.no_color != False: print color_codes[line.get_color()] print "stdout -----------------------------------------------------\n" for id in ind: print self.stdout_msgs[index][id] if self.arguments.no_color != False: print color_codes['RESET'] if self.arguments.pstack and name == 'pstack': if self.arguments.no_color != False: print color_codes[line.get_color()] print "pstack -----------------------------------------------------\n" for id in ind: print self.pstack_msgs[index][id] if self.arguments.no_color != False: print color_codes['RESET'] def buildAnnotation(self,fig,x,y,msg,c): for i in range(len(x)): fig.annotate(str(msg[i].split('\n')[0][:self.arguments.trim_text[-1]]), xy=(x[i], y[i]), rotation=self.arguments.rotate_text[-1], xytext=(decimal.Decimal(x[i]) + decimal.Decimal(self.arguments.move_text[0]), decimal.Decimal(y[i]) + decimal.Decimal(self.arguments.move_text[1])), color=c, horizontalalignment='center', verticalalignment='bottom', arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=0.5", color=c ) ) class ReadLog: """Read a memory_logger log file, and display the results to stdout in an easy to read form. """ def __init__(self, arguments): self.arguments = arguments history_file = open(self.arguments.read[-1], 'r') reader = csv.reader(history_file, delimiter=',', quotechar='|', escapechar='\\', quoting=csv.QUOTE_MINIMAL) self.memory_list = [] for row in reader: self.memory_list.append(row) history_file.close() self.sorted_list = [] self.mem_list = [] self.use_nodes = False self.printHistory() def printHistory(self): RESET = '\033[0m' BOLD = '\033[1m' BLACK = '\033[30m' RED = '\033[31m' GREEN = '\033[32m' CYAN = '\033[36m' YELLOW = '\033[33m' last_memory = 0.0 (terminal_width, terminal_height) = self.getTerminalSize() for timestamp in self.memory_list: to = GetTime(float(timestamp[0])) total_memory = int(timestamp[1]) log = timestamp[2].split('\n') pstack = timestamp[3].split('\n') node_name = str(timestamp[4]) node_memory = int(timestamp[5]) self.mem_list.append(total_memory) self.sorted_list.append([str(to.day) + ' ' + str(to.monthname) + ' ' + str(to.hour) + ':' + str(to.minute) + ':' + '{:02.0f}'.format(to.second) + '.' + '{:06.0f}'.format(to.microsecond), total_memory, log, pstack, node_name, node_memory]) largest_memory = decimal.Decimal(max(self.mem_list)) if len(set([x[4] for x in self.sorted_list])) > 1: self.use_nodes = True print 'Date Stamp' + ' '*int(17) + 'Memory Usage | Percent of MAX memory used: ( ' + str('{:0,.0f}'.format(largest_memory)) + ' K )' for item in self.sorted_list: tmp_str = '' if decimal.Decimal(item[1]) == largest_memory: tmp_str = self.formatText(largest_memory, item[0], item[1], item[5], item[2], item[3], item[4], RESET, terminal_width) elif item[1] > last_memory: tmp_str = self.formatText(largest_memory, item[0], item[1], item[5], item[2], item[3], item[4], RED, terminal_width) elif item[1] == last_memory: tmp_str = self.formatText(largest_memory, item[0], item[1], item[5], item[2], item[3], item[4], CYAN, terminal_width) else: tmp_str = self.formatText(largest_memory, item[0], item[1], item[5], item[2], item[3], item[4], GREEN, terminal_width) last_memory = item[1] sys.stdout.write(tmp_str) print 'Date Stamp' + ' '*int(17) + 'Memory Usage | Percent of MAX memory used: ( ' + str('{:0,.0f}'.format(largest_memory)) + ' K )' def formatText(self, largest_memory, date, total_memory, node_memory, log, pstack, reporting_host, color_code, terminal_width): RESET = '\033[0m' if decimal.Decimal(total_memory) == largest_memory: percent = '100' elif (decimal.Decimal(total_memory) / largest_memory) == 0: percent = '0' else: percent = str(decimal.Decimal(total_memory) / largest_memory)[2:4] + '.' + str(decimal.Decimal(total_memory) / largest_memory)[4:6] header = len(date) + 18 footer = len(percent) + 6 additional_correction = 0 max_length = decimal.Decimal(terminal_width - header) / largest_memory total_position = total_memory * decimal.Decimal(max_length) node_position = node_memory * decimal.Decimal(max_length) tmp_log = '' if self.arguments.stdout: for single_log in log: if single_log != '': tmp_log += ' '*(header - len(' stdout |')) + ' stdout | ' + single_log + '\n' if self.arguments.pstack: for single_pstack in pstack: if single_pstack != '': tmp_log += ' '*(header - len(' pstack |')) + ' pstack | ' + single_pstack + '\n' if self.arguments.separate and self.use_nodes != False: message = '< ' + RESET + reporting_host + ' - ' + '{:10,.0f}'.format(node_memory) + ' K' + color_code + ' >' additional_correction = len(RESET) + len(color_code) elif self.use_nodes: message = '< >' else: node_position = 0 message = '' return date + '{:15,.0f}'.format(total_memory) + ' K | ' + color_code + '-'*int(node_position) + message + '-'*(int(total_position) - (int(node_position) + ((len(message) - additional_correction) + footer))) + RESET + '| ' + percent + '%\n' + tmp_log def getTerminalSize(self): """Quicky to get terminal window size""" env = os.environ def ioctl_GWINSZ(fd): try: import fcntl, termios, struct, os cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234')) except: return None return cr cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2) if not cr: try: fd = os.open(os.ctermid(), os.O_RDONLY) cr = ioctl_GWINSZ(fd) os.close(fd) except: pass if not cr: try: cr = (env['LINES'], env['COLUMNS']) except: cr = (25, 80) return int(cr[1]), int(cr[0]) # A simple which function to return path to program def which(program): def is_exe(fpath): return os.path.exists(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file print 'I could not find the following binary:', program sys.exit(1) def verifyArgs(args): option_count = 0 if args.read: option_count += 1 if args.run: option_count += 1 if args.plot: option_count += 1 if option_count != 1 and args.pbs != True: if args.call_back_host == None: print 'You must use one of the following: run, read, or plot' sys.exit(1) args.cwd = os.getcwd() # Work with --recover (a MOOSE application specific option) args.recover = False if args.run: if args.run[0].find('--recover') != -1: args.recover = True if args.outfile == None and args.run: # Attempt to build the output file based on input file if re.findall(r'-i (\w+)', args.run[0]) != []: args.outfile = [os.getcwd() + '/' + re.findall(r'-i (\w+)', args.run[0])[0] + '_memory.log'] else: args.outfile = [os.getcwd() + '/' + args.run[0].replace('..', '').replace('/', '').replace(' ', '_') + '.log'] if args.pstack: if platform.platform(0, 1).split('-')[:-1][0].find('Darwin') != -1: try: import lldb except ImportError: print 'Unable to import lldb. The lldb API is now supplied by \nXcode but not automatically set in your PYTHONPATH. \nPlease search the internet for how to do this if you \nwish to use --pstack on Mac OS X.\n\nNote: If you installed Xcode to the default location of \n/Applications, you should only have to perform the following:\n\n\texport PYTHONPATH=/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python:$PYTHONPATH\n' sys.exit(1) else: results = which('gdb') return args def parseArguments(args=None): parser = argparse.ArgumentParser(description='Track and Display memory usage') rungroup = parser.add_argument_group('Tracking', 'The following options control how the memory logger tracks memory usage') rungroup.add_argument('--run', nargs=1, metavar='command', help='Run specified command. You must encapsulate the command in quotes\n ') rungroup.add_argument('--pbs', dest='pbs', metavar='', action='store_const', const=True, default=False, help='Instruct memory logger to tally all launches on all nodes\n ') rungroup.add_argument('--pbs-delay', dest='pbs_delay', metavar='float', nargs=1, type=float, default=[1.0], help='For larger jobs, you may need to increase the delay as to when the memory_logger will launch the tracking agents\n ') rungroup.add_argument('--sample-delay', dest='sample_delay', metavar='float', nargs=1, type=float, default=[0.25], help='The time to delay before taking the first sample (when not using pbs)') rungroup.add_argument('--repeat-rate', nargs=1, metavar='float', type=float, default=[0.25], help='Indicate the sleep delay in float seconds to check memory usage (default 0.25 seconds)\n ') rungroup.add_argument('--outfile', nargs=1, metavar='file', help='Save log to specified file. (Defaults based on run command)\n ') readgroup = parser.add_argument_group('Read / Display', 'Options to manipulate or read log files created by the memory_logger') readgroup.add_argument('--read', nargs=1, metavar='file', help='Read a specified memory log file to stdout\n ') readgroup.add_argument('--separate', dest='separate', action='store_const', const=True, default=False, help='Display individual node memory usage (read mode only)\n ') readgroup.add_argument('--plot', nargs="+", metavar='file', help='Display a graphical representation of memory usage (Requires Matplotlib). Specify a single file or a list of files to plot\n ') commongroup = parser.add_argument_group('Common Options', 'The following options can be used when displaying the results') commongroup.add_argument('--pstack', dest='pstack', action='store_const', const=True, default=False, help='Display/Record stack trace information (if available)\n ') commongroup.add_argument('--stdout', dest='stdout', action='store_const', const=True, default=False, help='Display stdout information\n ') plotgroup = parser.add_argument_group('Plot Options', 'Additional options when using --plot') plotgroup.add_argument('--rotate-text', nargs=1, metavar='int', type=int, default=[30], help='Rotate stdout/pstack text by this ammount (default 30)\n ') plotgroup.add_argument('--move-text', nargs=2, metavar='int', default=['0', '0'], help='Move text X and Y by this ammount (default 0 0)\n ') plotgroup.add_argument('--trim-text', nargs=1, metavar='int', type=int, default=[15], help='Display this many characters in stdout/pstack (default 15)\n ') plotgroup.add_argument('--no-color', dest='no_color', metavar='', action='store_const', const=False, help='When printing output to stdout do not use color codes\n ') internalgroup = parser.add_argument_group('Internal PBS Options', 'The following options are used to control how memory_logger as a tracking agent connects back to the caller. These are set automatically when using PBS and can be ignored.') internalgroup.add_argument('--call-back-host', nargs=2, help='Server hostname and port that launched memory_logger\n ') return verifyArgs(parser.parse_args(args)) if __name__ == '__main__': args = parseArguments() if args.read: ReadLog(args) sys.exit(0) if args.plot: MemoryPlotter(args) sys.exit(0) Server(args)
mellis13/moose
scripts/memory_logger.py
Python
lgpl-2.1
43,940
#!/usr/bin/env python import vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # this script tests vtkImageReslice with different interpolation modes, # with the wrap-pad feature turned on and with a rotation # Image pipeline reader = vtk.vtkImageReader() reader.ReleaseDataFlagOff() reader.SetDataByteOrderToLittleEndian() reader.SetDataExtent(0,63,0,63,1,93) reader.SetDataSpacing(3.2,3.2,1.5) reader.SetFilePrefix("" + str(VTK_DATA_ROOT) + "/Data/headsq/quarter") reader.SetDataMask(0x7fff) transform = vtk.vtkTransform() # rotate about the center of the image transform.Translate(+100.8,+100.8,+69.0) transform.RotateWXYZ(10,1,1,0) transform.Translate(-100.8,-100.8,-69.0) bspline3 = vtk.vtkImageBSplineInterpolator() bspline3.SetSplineDegree(3) bspline9 = vtk.vtkImageBSplineInterpolator() bspline9.SetSplineDegree(9) coeffs1 = vtk.vtkImageBSplineCoefficients() coeffs1.SetInputConnection(reader.GetOutputPort()) coeffs1.SetSplineDegree(3) coeffs2 = vtk.vtkImageBSplineCoefficients() coeffs2.SetInputConnection(reader.GetOutputPort()) coeffs2.SetSplineDegree(9) reslice1 = vtk.vtkImageReslice() reslice1.SetInputConnection(coeffs1.GetOutputPort()) reslice1.SetResliceTransform(transform) reslice1.SetInterpolator(bspline3) reslice1.SetOutputSpacing(2.0,2.0,1.5) reslice1.SetOutputOrigin(-32,-32,40) reslice1.SetOutputExtent(0,127,0,127,0,0) reslice2 = vtk.vtkImageReslice() reslice2.SetInputConnection(coeffs1.GetOutputPort()) reslice2.SetInterpolator(bspline3) reslice2.SetOutputSpacing(2.0,2.0,1.5) reslice2.SetOutputOrigin(-32,-32,40) reslice2.SetOutputExtent(0,127,0,127,0,0) reslice3 = vtk.vtkImageReslice() reslice3.SetInputConnection(coeffs2.GetOutputPort()) reslice3.SetResliceTransform(transform) reslice3.SetInterpolator(bspline9) reslice3.SetOutputSpacing(2.0,2.0,1.5) reslice3.SetOutputOrigin(-32,-32,40) reslice3.SetOutputExtent(0,127,0,127,0,0) reslice4 = vtk.vtkImageReslice() reslice4.SetInputConnection(coeffs2.GetOutputPort()) reslice4.SetInterpolator(bspline9) reslice4.SetOutputSpacing(2.0,2.0,1.5) reslice4.SetOutputOrigin(-32,-32,40) reslice4.SetOutputExtent(0,127,0,127,0,0) mapper1 = vtk.vtkImageMapper() mapper1.SetInputConnection(reslice1.GetOutputPort()) mapper1.SetColorWindow(2000) mapper1.SetColorLevel(1000) mapper1.SetZSlice(0) mapper2 = vtk.vtkImageMapper() mapper2.SetInputConnection(reslice2.GetOutputPort()) mapper2.SetColorWindow(2000) mapper2.SetColorLevel(1000) mapper2.SetZSlice(0) mapper3 = vtk.vtkImageMapper() mapper3.SetInputConnection(reslice3.GetOutputPort()) mapper3.SetColorWindow(2000) mapper3.SetColorLevel(1000) mapper3.SetZSlice(0) mapper4 = vtk.vtkImageMapper() mapper4.SetInputConnection(reslice4.GetOutputPort()) mapper4.SetColorWindow(2000) mapper4.SetColorLevel(1000) mapper4.SetZSlice(0) actor1 = vtk.vtkActor2D() actor1.SetMapper(mapper1) actor2 = vtk.vtkActor2D() actor2.SetMapper(mapper2) actor3 = vtk.vtkActor2D() actor3.SetMapper(mapper3) actor4 = vtk.vtkActor2D() actor4.SetMapper(mapper4) imager1 = vtk.vtkRenderer() imager1.AddActor2D(actor1) imager1.SetViewport(0.5,0.0,1.0,0.5) imager2 = vtk.vtkRenderer() imager2.AddActor2D(actor2) imager2.SetViewport(0.0,0.0,0.5,0.5) imager3 = vtk.vtkRenderer() imager3.AddActor2D(actor3) imager3.SetViewport(0.5,0.5,1.0,1.0) imager4 = vtk.vtkRenderer() imager4.AddActor2D(actor4) imager4.SetViewport(0.0,0.5,0.5,1.0) imgWin = vtk.vtkRenderWindow() imgWin.AddRenderer(imager1) imgWin.AddRenderer(imager2) imgWin.AddRenderer(imager3) imgWin.AddRenderer(imager4) imgWin.SetSize(256,256) imgWin.Render() # --- end of script --
HopeFOAM/HopeFOAM
ThirdParty-0.1/ParaView-5.0.1/VTK/Imaging/Core/Testing/Python/ResliceBSpline.py
Python
gpl-3.0
3,591
from __future__ import absolute_import from __future__ import print_function from .ChessFile import ChessFile, LoadingError from pychess.Utils.GameModel import GameModel from pychess.Utils.const import WHITE, BLACK, WON_RESIGN, WAITING_TO_START, BLACKWON, WHITEWON, DRAW from pychess.Utils.logic import getStatus from pychess.Utils.lutils.leval import evaluateComplete __label__ = _("Chess Position") __ending__ = "epd" __append__ = True def save (file, model, position=None): """Saves game to file in fen format""" color = model.boards[-1].color fen = model.boards[-1].asFen().split(" ") # First four parts of fen are the same in epd file.write(u" ".join(fen[:4])) ############################################################################ # Repetition count # ############################################################################ rc = model.boards[-1].board.repetitionCount() ############################################################################ # Centipawn evaluation # ############################################################################ if model.status == WHITEWON: if color == WHITE: ce = 32766 else: ce = -32766 elif model.status == BLACKWON: if color == WHITE: ce = -32766 else: ce = 32766 elif model.status == DRAW: ce = 0 else: ce = evaluateComplete(model.boards[-1].board, model.boards[-1].color) ############################################################################ # Opcodes # ############################################################################ opcodes = ( ("fmvn", fen[5]), # In fen full move number is the 6th field ("hmvc", fen[4]), # In fen halfmove clock is the 5th field # Email and name of reciever and sender. We don't know the email. ("tcri", "?@?.? %s" % repr(model.players[color]).replace(";","")), ("tcsi", "?@?.? %s" % repr(model.players[1-color]).replace(";","")), ("ce", ce), ("rc", rc), ) for key, value in opcodes: file.write(u" %s %s;" % (key, value)) ############################################################################ # Resign opcode # ############################################################################ if model.status in (WHITEWON, BLACKWON) and model.reason == WON_RESIGN: file.write(u" resign;") print(u"", file=file) file.close() def load (file): return EpdFile ([line for line in map(str.strip, file) if line]) class EpdFile (ChessFile): def loadToModel (self, gameno, position, model=None): if not model: model = GameModel() fieldlist = self.games[gameno].split(" ") if len(fieldlist) == 4: fen = self.games[gameno] opcodestr = "" elif len(fieldlist) > 4: fen = " ".join(fieldlist[:4]) opcodestr = " ".join(fieldlist[4:]) else: raise LoadingError("EPD string can not have less than 4 field") opcodes = {} for opcode in map(str.strip, opcodestr.split(";")): space = opcode.find(" ") if space == -1: opcodes[opcode] = True else: opcodes[opcode[:space]] = opcode[space+1:] if "hmvc" in opcodes: fen += " " + opcodes["hmvc"] else: fen += " 0" if "fmvn" in opcodes: fen += " " + opcodes["fmvn"] else: fen += " 1" model.boards = [model.variant.board(setup=fen)] model.variations = [model.boards] model.status = WAITING_TO_START # rc is kinda broken #if "rc" in opcodes: # model.boards[0].board.rc = int(opcodes["rc"]) if "resign" in opcodes: if fieldlist[1] == "w": model.status = BLACKWON else: model.status = WHITEWON model.reason = WON_RESIGN if model.status == WAITING_TO_START: status, reason = getStatus(model.boards[-1]) if status in (BLACKWON, WHITEWON, DRAW): model.status, model.reason = status, reason return model def get_player_names (self, gameno): data = self.games[gameno] names = {} for key in "tcri", "tcsi": keyindex = data.find(key) if keyindex == -1: names[key] = _("Unknown") else: sem = data.find(";", keyindex) if sem == -1: opcode = data[keyindex+len(key)+1:] else: opcode = data[keyindex+len(key)+1:sem] email, name = opcode.split(" ", 1) names[key] = name color = data.split(" ")[1] == "b" and BLACK or WHITE if color == WHITE: return (names["tcri"], names["tcsi"]) else: return (names["tcsi"], names["tcri"])
Karlon/pychess
lib/pychess/Savers/epd.py
Python
gpl-3.0
5,385
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals import logging import os import sys try: from magic import from_file as magic_from_file except ImportError: magic_from_file = None from six.moves import SimpleHTTPServer as srvmod from six.moves import socketserver class ComplexHTTPRequestHandler(srvmod.SimpleHTTPRequestHandler): SUFFIXES = ['', '.html', '/index.html'] def do_GET(self): # Try to detect file by applying various suffixes for suffix in self.SUFFIXES: if not hasattr(self, 'original_path'): self.original_path = self.path self.path = self.original_path + suffix path = self.translate_path(self.path) if os.path.exists(path): srvmod.SimpleHTTPRequestHandler.do_GET(self) logging.info("Found `%s`." % self.path) break logging.info("Tried to find `%s`, but it doesn't exist.", self.path) else: # Fallback if there were no matches logging.warning("Unable to find `%s` or variations.", self.original_path) def guess_type(self, path): """Guess at the mime type for the specified file. """ mimetype = srvmod.SimpleHTTPRequestHandler.guess_type(self, path) # If the default guess is too generic, try the python-magic library if mimetype == 'application/octet-stream' and magic_from_file: mimetype = magic_from_file(path, mime=True) return mimetype if __name__ == '__main__': PORT = len(sys.argv) in (2, 3) and int(sys.argv[1]) or 8000 SERVER = len(sys.argv) == 3 and sys.argv[2] or "" socketserver.TCPServer.allow_reuse_address = True try: httpd = socketserver.TCPServer( (SERVER, PORT), ComplexHTTPRequestHandler) except OSError as e: logging.error("Could not listen on port %s, server %s.", PORT, SERVER) sys.exit(getattr(e, 'exitcode', 1)) logging.info("Serving at port %s, server %s.", PORT, SERVER) try: httpd.serve_forever() except KeyboardInterrupt as e: logging.info("Shutting down server.") httpd.socket.close()
jimperio/pelican
pelican/server.py
Python
agpl-3.0
2,272
""" MixedModuleStore allows for aggregation between multiple modulestores. In this way, courses can be served up both - say - XMLModuleStore or MongoModuleStore """ import logging from contextlib import contextmanager import itertools import functools from contracts import contract, new_contract from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey, AssetKey from opaque_keys.edx.locator import LibraryLocator from opaque_keys.edx.locations import SlashSeparatedCourseKey from xmodule.assetstore import AssetMetadata from . import ModuleStoreWriteBase from . import ModuleStoreEnum from .exceptions import ItemNotFoundError, DuplicateCourseError from .draft_and_published import ModuleStoreDraftAndPublished from .split_migrator import SplitMigrator new_contract('CourseKey', CourseKey) new_contract('AssetKey', AssetKey) new_contract('AssetMetadata', AssetMetadata) new_contract('LibraryLocator', LibraryLocator) new_contract('long', long) log = logging.getLogger(__name__) def strip_key(func): """ A decorator for stripping version and branch information from return values that are, or contain, UsageKeys or CourseKeys. Additionally, the decorated function is called with an optional 'field_decorator' parameter that can be used to strip any location(-containing) fields, which are not directly returned by the function. The behavior can be controlled by passing 'remove_version' and 'remove_branch' booleans to the decorated function's kwargs. """ @functools.wraps(func) def inner(*args, **kwargs): """ Supported kwargs: remove_version - If True, calls 'version_agnostic' on all return values, including those in lists and dicts. remove_branch - If True, calls 'for_branch(None)' on all return values, including those in lists and dicts. Note: The 'field_decorator' parameter passed to the decorated function is a function that honors the values of these kwargs. """ # remove version and branch, by default rem_vers = kwargs.pop('remove_version', True) rem_branch = kwargs.pop('remove_branch', True) # helper function for stripping individual values def strip_key_func(val): """ Strips the version and branch information according to the settings of rem_vers and rem_branch. Recursively calls this function if the given value has a 'location' attribute. """ retval = val if rem_vers and hasattr(retval, 'version_agnostic'): retval = retval.version_agnostic() if rem_branch and hasattr(retval, 'for_branch'): retval = retval.for_branch(None) if hasattr(retval, 'location'): retval.location = strip_key_func(retval.location) return retval # function for stripping both, collection of, and individual, values def strip_key_collection(field_value): """ Calls strip_key_func for each element in the given value. """ if rem_vers or rem_branch: if isinstance(field_value, list): field_value = [strip_key_func(fv) for fv in field_value] elif isinstance(field_value, dict): for key, val in field_value.iteritems(): field_value[key] = strip_key_func(val) else: field_value = strip_key_func(field_value) return field_value # call the decorated function retval = func(field_decorator=strip_key_collection, *args, **kwargs) # strip the return value return strip_key_collection(retval) return inner class MixedModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase): """ ModuleStore knows how to route requests to the right persistence ms """ def __init__( self, contentstore, mappings, stores, i18n_service=None, fs_service=None, user_service=None, create_modulestore_instance=None, signal_handler=None, **kwargs ): """ Initialize a MixedModuleStore. Here we look into our passed in kwargs which should be a collection of other modulestore configuration information """ super(MixedModuleStore, self).__init__(contentstore, **kwargs) if create_modulestore_instance is None: raise ValueError('MixedModuleStore constructor must be passed a create_modulestore_instance function') self.modulestores = [] self.mappings = {} for course_id, store_name in mappings.iteritems(): try: self.mappings[CourseKey.from_string(course_id)] = store_name except InvalidKeyError: try: self.mappings[SlashSeparatedCourseKey.from_deprecated_string(course_id)] = store_name except InvalidKeyError: log.exception("Invalid MixedModuleStore configuration. Unable to parse course_id %r", course_id) continue for store_settings in stores: key = store_settings['NAME'] is_xml = 'XMLModuleStore' in store_settings['ENGINE'] if is_xml: # restrict xml to only load courses in mapping store_settings['OPTIONS']['course_ids'] = [ course_key.to_deprecated_string() for course_key, store_key in self.mappings.iteritems() if store_key == key ] store = create_modulestore_instance( store_settings['ENGINE'], self.contentstore, store_settings.get('DOC_STORE_CONFIG', {}), store_settings.get('OPTIONS', {}), i18n_service=i18n_service, fs_service=fs_service, user_service=user_service, signal_handler=signal_handler, ) # replace all named pointers to the store into actual pointers for course_key, store_name in self.mappings.iteritems(): if store_name == key: self.mappings[course_key] = store self.modulestores.append(store) def _clean_locator_for_mapping(self, locator): """ In order for mapping to work, the locator must be minimal--no version, no branch-- as we never store one version or one branch in one ms and another in another ms. :param locator: the CourseKey """ if hasattr(locator, 'version_agnostic'): locator = locator.version_agnostic() if hasattr(locator, 'branch'): locator = locator.replace(branch=None) return locator def _get_modulestore_for_courselike(self, locator=None): """ For a given locator, look in the mapping table and see if it has been pinned to a particular modulestore If locator is None, returns the first (ordered) store as the default """ if locator is not None: locator = self._clean_locator_for_mapping(locator) mapping = self.mappings.get(locator, None) if mapping is not None: return mapping else: if isinstance(locator, LibraryLocator): has_locator = lambda store: hasattr(store, 'has_library') and store.has_library(locator) else: has_locator = lambda store: store.has_course(locator) for store in self.modulestores: if has_locator(store): self.mappings[locator] = store return store # return the default store return self.default_modulestore def _get_modulestore_by_type(self, modulestore_type): """ This method should only really be used by tests and migration scripts when necessary. Returns the module store as requested by type. The type can be a value from ModuleStoreEnum.Type. """ for store in self.modulestores: if store.get_modulestore_type() == modulestore_type: return store return None def fill_in_run(self, course_key): """ Some course_keys are used without runs. This function calls the corresponding fill_in_run function on the appropriate modulestore. """ store = self._get_modulestore_for_courselike(course_key) if not hasattr(store, 'fill_in_run'): return course_key return store.fill_in_run(course_key) def has_item(self, usage_key, **kwargs): """ Does the course include the xblock who's id is reference? """ store = self._get_modulestore_for_courselike(usage_key.course_key) return store.has_item(usage_key, **kwargs) @strip_key def get_item(self, usage_key, depth=0, **kwargs): """ see parent doc """ store = self._get_modulestore_for_courselike(usage_key.course_key) return store.get_item(usage_key, depth, **kwargs) @strip_key def get_items(self, course_key, **kwargs): """ Returns: list of XModuleDescriptor instances for the matching items within the course with the given course_key NOTE: don't use this to look for courses as the course_key is required. Use get_courses. Args: course_key (CourseKey): the course identifier kwargs: settings (dict): fields to look for which have settings scope. Follows same syntax and rules as kwargs below content (dict): fields to look for which have content scope. Follows same syntax and rules as kwargs below. qualifiers (dict): what to look for within the course. Common qualifiers are ``category`` or any field name. if the target field is a list, then it searches for the given value in the list not list equivalence. Substring matching pass a regex object. For some modulestores, ``name`` is another commonly provided key (Location based stores) For some modulestores, you can search by ``edited_by``, ``edited_on`` providing either a datetime for == (probably useless) or a function accepting one arg to do inequality """ if not isinstance(course_key, CourseKey): raise Exception("Must pass in a course_key when calling get_items()") store = self._get_modulestore_for_courselike(course_key) return store.get_items(course_key, **kwargs) @strip_key def get_courses(self, **kwargs): ''' Returns a list containing the top level XModuleDescriptors of the courses in this modulestore. ''' courses = {} for store in self.modulestores: # filter out ones which were fetched from earlier stores but locations may not be == for course in store.get_courses(**kwargs): course_id = self._clean_locator_for_mapping(course.id) if course_id not in courses: # course is indeed unique. save it in result courses[course_id] = course return courses.values() @strip_key def get_libraries(self, **kwargs): """ Returns a list containing the top level XBlock of the libraries (LibraryRoot) in this modulestore. """ libraries = {} for store in self.modulestores: if not hasattr(store, 'get_libraries'): continue # filter out ones which were fetched from earlier stores but locations may not be == for library in store.get_libraries(**kwargs): library_id = self._clean_locator_for_mapping(library.location) if library_id not in libraries: # library is indeed unique. save it in result libraries[library_id] = library return libraries.values() def make_course_key(self, org, course, run): """ Return a valid :class:`~opaque_keys.edx.keys.CourseKey` for this modulestore that matches the supplied `org`, `course`, and `run`. This key may represent a course that doesn't exist in this modulestore. """ # If there is a mapping that match this org/course/run, use that for course_id, store in self.mappings.iteritems(): candidate_key = store.make_course_key(org, course, run) if candidate_key == course_id: return candidate_key # Otherwise, return the key created by the default store return self.default_modulestore.make_course_key(org, course, run) @strip_key def get_course(self, course_key, depth=0, **kwargs): """ returns the course module associated with the course_id. If no such course exists, it returns None :param course_key: must be a CourseKey """ assert isinstance(course_key, CourseKey) store = self._get_modulestore_for_courselike(course_key) try: return store.get_course(course_key, depth=depth, **kwargs) except ItemNotFoundError: return None @strip_key @contract(library_key='LibraryLocator') def get_library(self, library_key, depth=0, **kwargs): """ returns the library block associated with the given key. If no such library exists, it returns None :param library_key: must be a LibraryLocator """ try: store = self._verify_modulestore_support(library_key, 'get_library') return store.get_library(library_key, depth=depth, **kwargs) except NotImplementedError: log.exception("Modulestore configured for %s does not have get_library method", library_key) return None except ItemNotFoundError: return None @strip_key def has_course(self, course_id, ignore_case=False, **kwargs): """ returns the course_id of the course if it was found, else None Note: we return the course_id instead of a boolean here since the found course may have a different id than the given course_id when ignore_case is True. Args: * course_id (CourseKey) * ignore_case (bool): If True, do a case insensitive search. If False, do a case sensitive search """ assert isinstance(course_id, CourseKey) store = self._get_modulestore_for_courselike(course_id) return store.has_course(course_id, ignore_case, **kwargs) def delete_course(self, course_key, user_id): """ See xmodule.modulestore.__init__.ModuleStoreWrite.delete_course """ assert isinstance(course_key, CourseKey) store = self._get_modulestore_for_courselike(course_key) return store.delete_course(course_key, user_id) @contract(asset_metadata='AssetMetadata', user_id='int|long', import_only=bool) def save_asset_metadata(self, asset_metadata, user_id, import_only=False): """ Saves the asset metadata for a particular course's asset. Args: asset_metadata (AssetMetadata): data about the course asset data user_id (int|long): user ID saving the asset metadata import_only (bool): True if importing without editing, False if editing Returns: True if info save was successful, else False """ store = self._get_modulestore_for_courselike(asset_metadata.asset_id.course_key) return store.save_asset_metadata(asset_metadata, user_id, import_only) @contract(asset_metadata_list='list(AssetMetadata)', user_id='int|long', import_only=bool) def save_asset_metadata_list(self, asset_metadata_list, user_id, import_only=False): """ Saves the asset metadata for each asset in a list of asset metadata. Optimizes the saving of many assets. Args: asset_metadata_list (list(AssetMetadata)): list of data about several course assets user_id (int|long): user ID saving the asset metadata import_only (bool): True if importing without editing, False if editing Returns: True if info save was successful, else False """ if len(asset_metadata_list) == 0: return True store = self._get_modulestore_for_courselike(asset_metadata_list[0].asset_id.course_key) return store.save_asset_metadata_list(asset_metadata_list, user_id, import_only) @strip_key @contract(asset_key='AssetKey') def find_asset_metadata(self, asset_key, **kwargs): """ Find the metadata for a particular course asset. Args: asset_key (AssetKey): locator containing original asset filename Returns: asset metadata (AssetMetadata) -or- None if not found """ store = self._get_modulestore_for_courselike(asset_key.course_key) return store.find_asset_metadata(asset_key, **kwargs) @strip_key @contract(course_key='CourseKey', asset_type='None | basestring', start=int, maxresults=int, sort='tuple|None') def get_all_asset_metadata(self, course_key, asset_type, start=0, maxresults=-1, sort=None, **kwargs): """ Returns a list of static assets for a course. By default all assets are returned, but start and maxresults can be provided to limit the query. Args: course_key (CourseKey): course identifier asset_type (str): type of asset, such as 'asset', 'video', etc. If None, return assets of all types. start (int): optional - start at this asset number maxresults (int): optional - return at most this many, -1 means no limit sort (array): optional - None means no sort (sort_by (str), sort_order (str)) sort_by - one of 'uploadDate' or 'displayname' sort_order - one of 'ascending' or 'descending' Returns: List of AssetMetadata objects. """ store = self._get_modulestore_for_courselike(course_key) return store.get_all_asset_metadata(course_key, asset_type, start, maxresults, sort, **kwargs) @contract(asset_key='AssetKey', user_id='int|long') def delete_asset_metadata(self, asset_key, user_id): """ Deletes a single asset's metadata. Arguments: asset_id (AssetKey): locator containing original asset filename user_id (int_long): user deleting the metadata Returns: Number of asset metadata entries deleted (0 or 1) """ store = self._get_modulestore_for_courselike(asset_key.course_key) return store.delete_asset_metadata(asset_key, user_id) @contract(source_course_key='CourseKey', dest_course_key='CourseKey', user_id='int|long') def copy_all_asset_metadata(self, source_course_key, dest_course_key, user_id): """ Copy all the course assets from source_course_key to dest_course_key. Arguments: source_course_key (CourseKey): identifier of course to copy from dest_course_key (CourseKey): identifier of course to copy to user_id (int|long): user copying the asset metadata """ source_store = self._get_modulestore_for_courselike(source_course_key) dest_store = self._get_modulestore_for_courselike(dest_course_key) if source_store != dest_store: with self.bulk_operations(dest_course_key): # Get all the asset metadata in the source course. all_assets = source_store.get_all_asset_metadata(source_course_key, 'asset') # Store it all in the dest course. for asset in all_assets: new_asset_key = dest_course_key.make_asset_key('asset', asset.asset_id.path) copied_asset = AssetMetadata(new_asset_key) copied_asset.from_storable(asset.to_storable()) dest_store.save_asset_metadata(copied_asset, user_id) else: # Courses in the same modulestore can be handled by the modulestore itself. source_store.copy_all_asset_metadata(source_course_key, dest_course_key, user_id) @contract(asset_key='AssetKey', attr=str, user_id='int|long') def set_asset_metadata_attr(self, asset_key, attr, value, user_id): """ Add/set the given attr on the asset at the given location. Value can be any type which pymongo accepts. Arguments: asset_key (AssetKey): asset identifier attr (str): which attribute to set value: the value to set it to (any type pymongo accepts such as datetime, number, string) user_id: (int|long): user setting the attribute Raises: NotFoundError if no such item exists AttributeError is attr is one of the build in attrs. """ store = self._get_modulestore_for_courselike(asset_key.course_key) return store.set_asset_metadata_attrs(asset_key, {attr: value}, user_id) @contract(asset_key='AssetKey', attr_dict=dict, user_id='int|long') def set_asset_metadata_attrs(self, asset_key, attr_dict, user_id): """ Add/set the given dict of attrs on the asset at the given location. Value can be any type which pymongo accepts. Arguments: asset_key (AssetKey): asset identifier attr_dict (dict): attribute/value pairs to set user_id: (int|long): user setting the attributes Raises: NotFoundError if no such item exists AttributeError is attr is one of the build in attrs. """ store = self._get_modulestore_for_courselike(asset_key.course_key) return store.set_asset_metadata_attrs(asset_key, attr_dict, user_id) @strip_key def get_parent_location(self, location, **kwargs): """ returns the parent locations for a given location """ store = self._get_modulestore_for_courselike(location.course_key) return store.get_parent_location(location, **kwargs) def get_block_original_usage(self, usage_key): """ If a block was inherited into another structure using copy_from_template, this will return the original block usage locator from which the copy was inherited. """ try: store = self._verify_modulestore_support(usage_key.course_key, 'get_block_original_usage') return store.get_block_original_usage(usage_key) except NotImplementedError: return None, None def get_modulestore_type(self, course_id): """ Returns a type which identifies which modulestore is servicing the given course_id. The return can be one of: "xml" (for XML based courses), "mongo" for old-style MongoDB backed courses, "split" for new-style split MongoDB backed courses. """ return self._get_modulestore_for_courselike(course_id).get_modulestore_type() @strip_key def get_orphans(self, course_key, **kwargs): """ Get all of the xblocks in the given course which have no parents and are not of types which are usually orphaned. NOTE: may include xblocks which still have references via xblocks which don't use children to point to their dependents. """ store = self._get_modulestore_for_courselike(course_key) return store.get_orphans(course_key, **kwargs) def get_errored_courses(self): """ Return a dictionary of course_dir -> [(msg, exception_str)], for each course_dir where course loading failed. """ errs = {} for store in self.modulestores: errs.update(store.get_errored_courses()) return errs @strip_key def create_course(self, org, course, run, user_id, **kwargs): """ Creates and returns the course. Args: org (str): the organization that owns the course course (str): the name of the course run (str): the name of the run user_id: id of the user creating the course fields (dict): Fields to set on the course at initialization kwargs: Any optional arguments understood by a subset of modulestores to customize instantiation Returns: a CourseDescriptor """ # first make sure an existing course doesn't already exist in the mapping course_key = self.make_course_key(org, course, run) if course_key in self.mappings: raise DuplicateCourseError(course_key, course_key) # create the course store = self._verify_modulestore_support(None, 'create_course') course = store.create_course(org, course, run, user_id, **kwargs) # add new course to the mapping self.mappings[course_key] = store return course @strip_key def create_library(self, org, library, user_id, fields, **kwargs): """ Creates and returns a new library. Args: org (str): the organization that owns the course library (str): the code/number/name of the library user_id: id of the user creating the course fields (dict): Fields to set on the course at initialization - e.g. display_name kwargs: Any optional arguments understood by a subset of modulestores to customize instantiation Returns: a LibraryRoot """ # first make sure an existing course/lib doesn't already exist in the mapping lib_key = LibraryLocator(org=org, library=library) if lib_key in self.mappings: raise DuplicateCourseError(lib_key, lib_key) # create the library store = self._verify_modulestore_support(None, 'create_library') library = store.create_library(org, library, user_id, fields, **kwargs) # add new library to the mapping self.mappings[lib_key] = store return library @strip_key def clone_course(self, source_course_id, dest_course_id, user_id, fields=None, **kwargs): """ See the superclass for the general documentation. If cloning w/in a store, delegates to that store's clone_course which, in order to be self- sufficient, should handle the asset copying (call the same method as this one does) If cloning between stores, * copy the assets * migrate the courseware """ source_modulestore = self._get_modulestore_for_courselike(source_course_id) # for a temporary period of time, we may want to hardcode dest_modulestore as split if there's a split # to have only course re-runs go to split. This code, however, uses the config'd priority dest_modulestore = self._get_modulestore_for_courselike(dest_course_id) if source_modulestore == dest_modulestore: return source_modulestore.clone_course(source_course_id, dest_course_id, user_id, fields, **kwargs) if dest_modulestore.get_modulestore_type() == ModuleStoreEnum.Type.split: split_migrator = SplitMigrator(dest_modulestore, source_modulestore) split_migrator.migrate_mongo_course(source_course_id, user_id, dest_course_id.org, dest_course_id.course, dest_course_id.run, fields, **kwargs) # the super handles assets and any other necessities super(MixedModuleStore, self).clone_course(source_course_id, dest_course_id, user_id, fields, **kwargs) else: raise NotImplementedError("No code for cloning from {} to {}".format( source_modulestore, dest_modulestore )) @strip_key def create_item(self, user_id, course_key, block_type, block_id=None, fields=None, **kwargs): """ Creates and saves a new item in a course. Returns the newly created item. Args: user_id: ID of the user creating and saving the xmodule course_key: A :class:`~opaque_keys.edx.CourseKey` identifying which course to create this item in block_type: The typo of block to create block_id: a unique identifier for the new item. If not supplied, a new identifier will be generated fields (dict): A dictionary specifying initial values for some or all fields in the newly created block """ modulestore = self._verify_modulestore_support(course_key, 'create_item') return modulestore.create_item(user_id, course_key, block_type, block_id=block_id, fields=fields, **kwargs) @strip_key def create_child(self, user_id, parent_usage_key, block_type, block_id=None, fields=None, **kwargs): """ Creates and saves a new xblock that is a child of the specified block Returns the newly created item. Args: user_id: ID of the user creating and saving the xmodule parent_usage_key: a :class:`~opaque_key.edx.UsageKey` identifying the block that this item should be parented under block_type: The typo of block to create block_id: a unique identifier for the new item. If not supplied, a new identifier will be generated fields (dict): A dictionary specifying initial values for some or all fields in the newly created block """ modulestore = self._verify_modulestore_support(parent_usage_key.course_key, 'create_child') return modulestore.create_child(user_id, parent_usage_key, block_type, block_id=block_id, fields=fields, **kwargs) @strip_key def import_xblock(self, user_id, course_key, block_type, block_id, fields=None, runtime=None, **kwargs): """ See :py:meth `ModuleStoreDraftAndPublished.import_xblock` Defer to the course's modulestore if it supports this method """ store = self._verify_modulestore_support(course_key, 'import_xblock') return store.import_xblock(user_id, course_key, block_type, block_id, fields, runtime) @strip_key def copy_from_template(self, source_keys, dest_key, user_id, **kwargs): """ See :py:meth `SplitMongoModuleStore.copy_from_template` """ store = self._verify_modulestore_support(dest_key.course_key, 'copy_from_template') return store.copy_from_template(source_keys, dest_key, user_id) @strip_key def update_item(self, xblock, user_id, allow_not_found=False, **kwargs): """ Update the xblock persisted to be the same as the given for all types of fields (content, children, and metadata) attribute the change to the given user. """ store = self._verify_modulestore_support(xblock.location.course_key, 'update_item') return store.update_item(xblock, user_id, allow_not_found, **kwargs) @strip_key def delete_item(self, location, user_id, **kwargs): """ Delete the given item from persistence. kwargs allow modulestore specific parameters. """ store = self._verify_modulestore_support(location.course_key, 'delete_item') return store.delete_item(location, user_id=user_id, **kwargs) def revert_to_published(self, location, user_id): """ Reverts an item to its last published version (recursively traversing all of its descendants). If no published version exists, an InvalidVersionError is thrown. If a published version exists but there is no draft version of this item or any of its descendants, this method is a no-op. :raises InvalidVersionError: if no published version exists for the location specified """ store = self._verify_modulestore_support(location.course_key, 'revert_to_published') return store.revert_to_published(location, user_id) def close_all_connections(self): """ Close all db connections """ for modulestore in self.modulestores: modulestore.close_connections() def _drop_database(self): """ A destructive operation to drop all databases and close all db connections. Intended to be used by test code for cleanup. """ for modulestore in self.modulestores: # drop database if the store supports it (read-only stores do not) if hasattr(modulestore, '_drop_database'): modulestore._drop_database() # pylint: disable=protected-access @strip_key def create_xblock(self, runtime, course_key, block_type, block_id=None, fields=None, **kwargs): """ Create the new xmodule but don't save it. Returns the new module. Args: runtime: :py:class `xblock.runtime` from another xblock in the same course. Providing this significantly speeds up processing (inheritance and subsequent persistence) course_key: :py:class `opaque_keys.CourseKey` block_type: :py:class `string`: the string identifying the xblock type block_id: the string uniquely identifying the block within the given course fields: :py:class `dict` field_name, value pairs for initializing the xblock fields. Values should be the pythonic types not the json serialized ones. """ store = self._verify_modulestore_support(course_key, 'create_xblock') return store.create_xblock(runtime, course_key, block_type, block_id, fields or {}, **kwargs) @strip_key def get_courses_for_wiki(self, wiki_slug, **kwargs): """ Return the list of courses which use this wiki_slug :param wiki_slug: the course wiki root slug :return: list of course keys """ courses = [] for modulestore in self.modulestores: courses.extend(modulestore.get_courses_for_wiki(wiki_slug, **kwargs)) return courses def heartbeat(self): """ Delegate to each modulestore and package the results for the caller. """ # could be done in parallel threads if needed return dict( itertools.chain.from_iterable( store.heartbeat().iteritems() for store in self.modulestores ) ) def has_published_version(self, xblock): """ Returns whether this xblock is draft, public, or private. Returns: PublishState.draft - content is in the process of being edited, but still has a previous version deployed to LMS PublishState.public - content is locked and deployed to LMS PublishState.private - content is editable and not deployed to LMS """ course_id = xblock.scope_ids.usage_id.course_key store = self._get_modulestore_for_courselike(course_id) return store.has_published_version(xblock) @strip_key def publish(self, location, user_id, **kwargs): """ Save a current draft to the underlying modulestore Returns the newly published item. """ store = self._verify_modulestore_support(location.course_key, 'publish') return store.publish(location, user_id, **kwargs) @strip_key def unpublish(self, location, user_id, **kwargs): """ Save a current draft to the underlying modulestore Returns the newly unpublished item. """ store = self._verify_modulestore_support(location.course_key, 'unpublish') return store.unpublish(location, user_id, **kwargs) def convert_to_draft(self, location, user_id): """ Create a copy of the source and mark its revision as draft. Note: This method is to support the Mongo Modulestore and may be deprecated. :param location: the location of the source (its revision must be None) """ store = self._verify_modulestore_support(location.course_key, 'convert_to_draft') return store.convert_to_draft(location, user_id) def has_changes(self, xblock): """ Checks if the given block has unpublished changes :param xblock: the block to check :return: True if the draft and published versions differ """ store = self._verify_modulestore_support(xblock.location.course_key, 'has_changes') return store.has_changes(xblock) def check_supports(self, course_key, method): """ Verifies that the modulestore for a particular course supports a feature. Returns True/false based on this. """ try: self._verify_modulestore_support(course_key, method) return True except NotImplementedError: return False def _verify_modulestore_support(self, course_key, method): """ Finds and returns the store that contains the course for the given location, and verifying that the store supports the given method. Raises NotImplementedError if the found store does not support the given method. """ store = self._get_modulestore_for_courselike(course_key) if hasattr(store, method): return store else: raise NotImplementedError(u"Cannot call {} on store {}".format(method, store)) @property def default_modulestore(self): """ Return the default modulestore """ thread_local_default_store = getattr(self.thread_cache, 'default_store', None) if thread_local_default_store: # return the thread-local cache, if found return thread_local_default_store else: # else return the default store return self.modulestores[0] @contextmanager def default_store(self, store_type): """ A context manager for temporarily changing the default store in the Mixed modulestore to the given store type """ # find the store corresponding to the given type store = next((store for store in self.modulestores if store.get_modulestore_type() == store_type), None) if not store: raise Exception(u"Cannot find store of type {}".format(store_type)) prev_thread_local_store = getattr(self.thread_cache, 'default_store', None) try: self.thread_cache.default_store = store yield finally: self.thread_cache.default_store = prev_thread_local_store @contextmanager def branch_setting(self, branch_setting, course_id=None): """ A context manager for temporarily setting the branch value for the given course' store to the given branch_setting. If course_id is None, the default store is used. """ store = self._verify_modulestore_support(course_id, 'branch_setting') with store.branch_setting(branch_setting, course_id): yield @contextmanager def bulk_operations(self, course_id, emit_signals=True): """ A context manager for notifying the store of bulk operations. If course_id is None, the default store is used. """ store = self._get_modulestore_for_courselike(course_id) with store.bulk_operations(course_id, emit_signals): yield def ensure_indexes(self): """ Ensure that all appropriate indexes are created that are needed by this modulestore, or raise an exception if unable to. This method is intended for use by tests and administrative commands, and not to be run during server startup. """ for store in self.modulestores: store.ensure_indexes()
beni55/edx-platform
common/lib/xmodule/xmodule/modulestore/mixed.py
Python
agpl-3.0
40,382
import base64 import cPickle as pickle from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings from django.utils.hashcompat import md5_constructor class SessionManager(models.Manager): def encode(self, session_dict): """ Returns the given session dictionary pickled and encoded as a string. """ pickled = pickle.dumps(session_dict) pickled_md5 = md5_constructor(pickled + settings.SECRET_KEY).hexdigest() return base64.encodestring(pickled + pickled_md5) def save(self, session_key, session_dict, expire_date): s = self.model(session_key, self.encode(session_dict), expire_date) if session_dict: s.save() else: s.delete() # Clear sessions with no data. return s class Session(models.Model): """ Django provides full support for anonymous sessions. The session framework lets you store and retrieve arbitrary data on a per-site-visitor basis. It stores data on the server side and abstracts the sending and receiving of cookies. Cookies contain a session ID -- not the data itself. The Django sessions framework is entirely cookie-based. It does not fall back to putting session IDs in URLs. This is an intentional design decision. Not only does that behavior make URLs ugly, it makes your site vulnerable to session-ID theft via the "Referer" header. For complete documentation on using Sessions in your code, consult the sessions documentation that is shipped with Django (also available on the Django website). """ session_key = models.CharField(_('session key'), max_length=40, primary_key=True) session_data = models.TextField(_('session data')) expire_date = models.DateTimeField(_('expire date')) objects = SessionManager() class Meta: db_table = 'django_session' verbose_name = _('session') verbose_name_plural = _('sessions') def get_decoded(self): encoded_data = base64.decodestring(self.session_data) pickled, tamper_check = encoded_data[:-32], encoded_data[-32:] if md5_constructor(pickled + settings.SECRET_KEY).hexdigest() != tamper_check: from django.core.exceptions import SuspiciousOperation raise SuspiciousOperation("User tampered with session cookie.") try: return pickle.loads(pickled) # Unpickling can cause a variety of exceptions. If something happens, # just return an empty dictionary (an empty session). except: return {}
nycholas/ask-undrgz
src/ask-undrgz/django/contrib/sessions/models.py
Python
bsd-3-clause
2,675
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2016 Michael Gruener <michael.gruener@chaosmoon.net> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: cloudflare_dns author: "Michael Gruener (@mgruener)" requirements: - "python >= 2.6" version_added: "2.1" short_description: manage Cloudflare DNS records description: - "Manages dns records via the Cloudflare API, see the docs: U(https://api.cloudflare.com/)" options: account_api_token: description: - > Account API token. You can obtain your API key from the bottom of the Cloudflare 'My Account' page, found here: U(https://dash.cloudflare.com/) required: true account_email: description: - "Account email." required: true algorithm: description: - Algorithm number. Required for C(type=DS) and C(type=SSHFP) when C(state=present). type: int version_added: 2.7 cert_usage: description: - Certificate usage number. Required for C(type=TLSA) when C(state=present). choices: [ 0, 1, 2, 3 ] type: int version_added: 2.7 hash_type: description: - Hash type number. Required for C(type=DS), C(type=SSHFP) and C(type=TLSA) when C(state=present). choices: [ 1, 2 ] type: int version_added: 2.7 key_tag: description: - DNSSEC key tag. Needed for C(type=DS) when C(state=present). type: int version_added: 2.7 port: description: Service port. Required for C(type=SRV) and C(type=TLSA). priority: description: Record priority. Required for C(type=MX) and C(type=SRV) default: "1" proto: description: - Service protocol. Required for C(type=SRV) and C(type=TLSA). - Common values are tcp and udp. - Before Ansible 2.6 only tcp and udp were available. proxied: description: Proxy through cloudflare network or just use DNS type: bool default: 'no' version_added: "2.3" record: description: - Record to add. Required if C(state=present). Default is C(@) (e.g. the zone name) default: "@" aliases: [ "name" ] selector: description: - Selector number. Required for C(type=TLSA) when C(state=present). choices: [ 0, 1 ] type: int version_added: 2.7 service: description: Record service. Required for C(type=SRV) solo: description: - Whether the record should be the only one for that record type and record name. Only use with C(state=present) - This will delete all other records with the same record name and type. state: description: - Whether the record(s) should exist or not choices: [ 'present', 'absent' ] default: present timeout: description: - Timeout for Cloudflare API calls default: 30 ttl: description: - The TTL to give the new record. Must be between 120 and 2,147,483,647 seconds, or 1 for automatic. default: 1 (automatic) type: description: - The type of DNS record to create. Required if C(state=present) - C(type=DS), C(type=SSHFP) and C(type=TLSA) added in Ansible 2.7. choices: [ 'A', 'AAAA', 'CNAME', 'TXT', 'SRV', 'MX', 'NS', 'DS', 'SPF', 'SSHFP', 'TLSA' ] value: description: - The record value. Required for C(state=present) aliases: [ "content" ] weight: description: Service weight. Required for C(type=SRV) default: "1" zone: description: - The name of the Zone to work with (e.g. "example.com"). The Zone must already exist. required: true aliases: ["domain"] ''' EXAMPLES = ''' # create a test.my.com A record to point to 127.0.0.1 - cloudflare_dns: zone: my.com record: test type: A value: 127.0.0.1 account_email: test@example.com account_api_token: dummyapitoken register: record # create a my.com CNAME record to example.com - cloudflare_dns: zone: my.com type: CNAME value: example.com state: present account_email: test@example.com account_api_token: dummyapitoken # change it's ttl - cloudflare_dns: zone: my.com type: CNAME value: example.com ttl: 600 state: present account_email: test@example.com account_api_token: dummyapitoken # and delete the record - cloudflare_dns: zone: my.com type: CNAME value: example.com state: absent account_email: test@example.com account_api_token: dummyapitoken # create a my.com CNAME record to example.com and proxy through cloudflare's network - cloudflare_dns: zone: my.com type: CNAME value: example.com state: present proxied: yes account_email: test@example.com account_api_token: dummyapitoken # create TXT record "test.my.com" with value "unique value" # delete all other TXT records named "test.my.com" - cloudflare_dns: domain: my.com record: test type: TXT value: unique value state: present solo: true account_email: test@example.com account_api_token: dummyapitoken # create a SRV record _foo._tcp.my.com - cloudflare_dns: domain: my.com service: foo proto: tcp port: 3500 priority: 10 weight: 20 type: SRV value: fooserver.my.com # create a SSHFP record login.example.com - cloudflare_dns: zone: example.com record: login type: SSHFP algorithm: 4 hash_type: 2 value: 9dc1d6742696d2f51ca1f1a78b3d16a840f7d111eb9454239e70db31363f33e1 # create a TLSA record _25._tcp.mail.example.com - cloudflare_dns: zone: example.com record: mail port: 25 proto: tcp type: TLSA cert_usage: 3 selector: 1 hash_type: 1 value: 6b76d034492b493e15a7376fccd08e63befdad0edab8e442562f532338364bf3 # Create a DS record for subdomain.example.com - cloudflare_dns: zone: example.com record: subdomain type: DS key_tag: 5464 algorithm: 8 hash_type: 2 value: B4EB5AC4467D2DFB3BAF9FB9961DC1B6FED54A58CDFAA3E465081EC86F89BFAB ''' RETURN = ''' record: description: dictionary containing the record data returned: success, except on record deletion type: complex contains: content: description: the record content (details depend on record type) returned: success type: string sample: 192.0.2.91 created_on: description: the record creation date returned: success type: string sample: 2016-03-25T19:09:42.516553Z data: description: additional record data returned: success, if type is SRV, DS, SSHFP or TLSA type: dictionary sample: { name: "jabber", port: 8080, priority: 10, proto: "_tcp", service: "_xmpp", target: "jabberhost.sample.com", weight: 5, } id: description: the record id returned: success type: string sample: f9efb0549e96abcb750de63b38c9576e locked: description: No documentation available returned: success type: boolean sample: False meta: description: No documentation available returned: success type: dictionary sample: { auto_added: false } modified_on: description: record modification date returned: success type: string sample: 2016-03-25T19:09:42.516553Z name: description: the record name as FQDN (including _service and _proto for SRV) returned: success type: string sample: www.sample.com priority: description: priority of the MX record returned: success, if type is MX type: int sample: 10 proxiable: description: whether this record can be proxied through cloudflare returned: success type: boolean sample: False proxied: description: whether the record is proxied through cloudflare returned: success type: boolean sample: False ttl: description: the time-to-live for the record returned: success type: int sample: 300 type: description: the record type returned: success type: string sample: A zone_id: description: the id of the zone containing the record returned: success type: string sample: abcede0bf9f0066f94029d2e6b73856a zone_name: description: the name of the zone containing the record returned: success type: string sample: sample.com ''' import json from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.six.moves.urllib.parse import urlencode from ansible.module_utils._text import to_native, to_text from ansible.module_utils.urls import fetch_url def lowercase_string(param): if not isinstance(param, str): return param return param.lower() class CloudflareAPI(object): cf_api_endpoint = 'https://api.cloudflare.com/client/v4' changed = False def __init__(self, module): self.module = module self.account_api_token = module.params['account_api_token'] self.account_email = module.params['account_email'] self.algorithm = module.params['algorithm'] self.cert_usage = module.params['cert_usage'] self.hash_type = module.params['hash_type'] self.key_tag = module.params['key_tag'] self.port = module.params['port'] self.priority = module.params['priority'] self.proto = lowercase_string(module.params['proto']) self.proxied = module.params['proxied'] self.selector = module.params['selector'] self.record = lowercase_string(module.params['record']) self.service = lowercase_string(module.params['service']) self.is_solo = module.params['solo'] self.state = module.params['state'] self.timeout = module.params['timeout'] self.ttl = module.params['ttl'] self.type = module.params['type'] self.value = module.params['value'] self.weight = module.params['weight'] self.zone = lowercase_string(module.params['zone']) if self.record == '@': self.record = self.zone if (self.type in ['CNAME', 'NS', 'MX', 'SRV']) and (self.value is not None): self.value = self.value.rstrip('.').lower() if (self.type == 'AAAA') and (self.value is not None): self.value = self.value.lower() if (self.type == 'SRV'): if (self.proto is not None) and (not self.proto.startswith('_')): self.proto = '_' + self.proto if (self.service is not None) and (not self.service.startswith('_')): self.service = '_' + self.service if (self.type == 'TLSA'): if (self.proto is not None) and (not self.proto.startswith('_')): self.proto = '_' + self.proto if (self.port is not None): self.port = '_' + str(self.port) if not self.record.endswith(self.zone): self.record = self.record + '.' + self.zone if (self.type == 'DS'): if self.record == self.zone: self.module.fail_json(msg="DS records only apply to subdomains.") def _cf_simple_api_call(self, api_call, method='GET', payload=None): headers = {'X-Auth-Email': self.account_email, 'X-Auth-Key': self.account_api_token, 'Content-Type': 'application/json'} data = None if payload: try: data = json.dumps(payload) except Exception as e: self.module.fail_json(msg="Failed to encode payload as JSON: %s " % to_native(e)) resp, info = fetch_url(self.module, self.cf_api_endpoint + api_call, headers=headers, data=data, method=method, timeout=self.timeout) if info['status'] not in [200, 304, 400, 401, 403, 429, 405, 415]: self.module.fail_json(msg="Failed API call {0}; got unexpected HTTP code {1}".format(api_call, info['status'])) error_msg = '' if info['status'] == 401: # Unauthorized error_msg = "API user does not have permission; Status: {0}; Method: {1}: Call: {2}".format(info['status'], method, api_call) elif info['status'] == 403: # Forbidden error_msg = "API request not authenticated; Status: {0}; Method: {1}: Call: {2}".format(info['status'], method, api_call) elif info['status'] == 429: # Too many requests error_msg = "API client is rate limited; Status: {0}; Method: {1}: Call: {2}".format(info['status'], method, api_call) elif info['status'] == 405: # Method not allowed error_msg = "API incorrect HTTP method provided; Status: {0}; Method: {1}: Call: {2}".format(info['status'], method, api_call) elif info['status'] == 415: # Unsupported Media Type error_msg = "API request is not valid JSON; Status: {0}; Method: {1}: Call: {2}".format(info['status'], method, api_call) elif info['status'] == 400: # Bad Request error_msg = "API bad request; Status: {0}; Method: {1}: Call: {2}".format(info['status'], method, api_call) result = None try: content = resp.read() except AttributeError: if info['body']: content = info['body'] else: error_msg += "; The API response was empty" if content: try: result = json.loads(to_text(content, errors='surrogate_or_strict')) except (getattr(json, 'JSONDecodeError', ValueError)) as e: error_msg += "; Failed to parse API response with error {0}: {1}".format(to_native(e), content) # Without a valid/parsed JSON response no more error processing can be done if result is None: self.module.fail_json(msg=error_msg) if not result['success']: error_msg += "; Error details: " for error in result['errors']: error_msg += "code: {0}, error: {1}; ".format(error['code'], error['message']) if 'error_chain' in error: for chain_error in error['error_chain']: error_msg += "code: {0}, error: {1}; ".format(chain_error['code'], chain_error['message']) self.module.fail_json(msg=error_msg) return result, info['status'] def _cf_api_call(self, api_call, method='GET', payload=None): result, status = self._cf_simple_api_call(api_call, method, payload) data = result['result'] if 'result_info' in result: pagination = result['result_info'] if pagination['total_pages'] > 1: next_page = int(pagination['page']) + 1 parameters = ['page={0}'.format(next_page)] # strip "page" parameter from call parameters (if there are any) if '?' in api_call: raw_api_call, query = api_call.split('?', 1) parameters += [param for param in query.split('&') if not param.startswith('page')] else: raw_api_call = api_call while next_page <= pagination['total_pages']: raw_api_call += '?' + '&'.join(parameters) result, status = self._cf_simple_api_call(raw_api_call, method, payload) data += result['result'] next_page += 1 return data, status def _get_zone_id(self, zone=None): if not zone: zone = self.zone zones = self.get_zones(zone) if len(zones) > 1: self.module.fail_json(msg="More than one zone matches {0}".format(zone)) if len(zones) < 1: self.module.fail_json(msg="No zone found with name {0}".format(zone)) return zones[0]['id'] def get_zones(self, name=None): if not name: name = self.zone param = '' if name: param = '?' + urlencode({'name': name}) zones, status = self._cf_api_call('/zones' + param) return zones def get_dns_records(self, zone_name=None, type=None, record=None, value=''): if not zone_name: zone_name = self.zone if not type: type = self.type if not record: record = self.record # necessary because None as value means to override user # set module value if (not value) and (value is not None): value = self.value zone_id = self._get_zone_id() api_call = '/zones/{0}/dns_records'.format(zone_id) query = {} if type: query['type'] = type if record: query['name'] = record if value: query['content'] = value if query: api_call += '?' + urlencode(query) records, status = self._cf_api_call(api_call) return records def delete_dns_records(self, **kwargs): params = {} for param in ['port', 'proto', 'service', 'solo', 'type', 'record', 'value', 'weight', 'zone', 'algorithm', 'cert_usage', 'hash_type', 'selector', 'key_tag']: if param in kwargs: params[param] = kwargs[param] else: params[param] = getattr(self, param) records = [] content = params['value'] search_record = params['record'] if params['type'] == 'SRV': if not (params['value'] is None or params['value'] == ''): content = str(params['weight']) + '\t' + str(params['port']) + '\t' + params['value'] search_record = params['service'] + '.' + params['proto'] + '.' + params['record'] elif params['type'] == 'DS': if not (params['value'] is None or params['value'] == ''): content = str(params['key_tag']) + '\t' + str(params['algorithm']) + '\t' + str(params['hash_type']) + '\t' + params['value'] elif params['type'] == 'SSHFP': if not (params['value'] is None or params['value'] == ''): content = str(params['algorithm']) + '\t' + str(params['hash_type']) + '\t' + params['value'] elif params['type'] == 'TLSA': if not (params['value'] is None or params['value'] == ''): content = str(params['cert_usage']) + '\t' + str(params['selector']) + '\t' + str(params['hash_type']) + '\t' + params['value'] search_record = params['port'] + '.' + params['proto'] + '.' + params['record'] if params['solo']: search_value = None else: search_value = content records = self.get_dns_records(params['zone'], params['type'], search_record, search_value) for rr in records: if params['solo']: if not ((rr['type'] == params['type']) and (rr['name'] == search_record) and (rr['content'] == content)): self.changed = True if not self.module.check_mode: result, info = self._cf_api_call('/zones/{0}/dns_records/{1}'.format(rr['zone_id'], rr['id']), 'DELETE') else: self.changed = True if not self.module.check_mode: result, info = self._cf_api_call('/zones/{0}/dns_records/{1}'.format(rr['zone_id'], rr['id']), 'DELETE') return self.changed def ensure_dns_record(self, **kwargs): params = {} for param in ['port', 'priority', 'proto', 'proxied', 'service', 'ttl', 'type', 'record', 'value', 'weight', 'zone', 'algorithm', 'cert_usage', 'hash_type', 'selector', 'key_tag']: if param in kwargs: params[param] = kwargs[param] else: params[param] = getattr(self, param) search_value = params['value'] search_record = params['record'] new_record = None if (params['type'] is None) or (params['record'] is None): self.module.fail_json(msg="You must provide a type and a record to create a new record") if (params['type'] in ['A', 'AAAA', 'CNAME', 'TXT', 'MX', 'NS', 'SPF']): if not params['value']: self.module.fail_json(msg="You must provide a non-empty value to create this record type") # there can only be one CNAME per record # ignoring the value when searching for existing # CNAME records allows us to update the value if it # changes if params['type'] == 'CNAME': search_value = None new_record = { "type": params['type'], "name": params['record'], "content": params['value'], "ttl": params['ttl'] } if (params['type'] in ['A', 'AAAA', 'CNAME']): new_record["proxied"] = params["proxied"] if params['type'] == 'MX': for attr in [params['priority'], params['value']]: if (attr is None) or (attr == ''): self.module.fail_json(msg="You must provide priority and a value to create this record type") new_record = { "type": params['type'], "name": params['record'], "content": params['value'], "priority": params['priority'], "ttl": params['ttl'] } if params['type'] == 'SRV': for attr in [params['port'], params['priority'], params['proto'], params['service'], params['weight'], params['value']]: if (attr is None) or (attr == ''): self.module.fail_json(msg="You must provide port, priority, proto, service, weight and a value to create this record type") srv_data = { "target": params['value'], "port": params['port'], "weight": params['weight'], "priority": params['priority'], "name": params['record'][:-len('.' + params['zone'])], "proto": params['proto'], "service": params['service'] } new_record = {"type": params['type'], "ttl": params['ttl'], 'data': srv_data} search_value = str(params['weight']) + '\t' + str(params['port']) + '\t' + params['value'] search_record = params['service'] + '.' + params['proto'] + '.' + params['record'] if params['type'] == 'DS': for attr in [params['key_tag'], params['algorithm'], params['hash_type'], params['value']]: if (attr is None) or (attr == ''): self.module.fail_json(msg="You must provide key_tag, algorithm, hash_type and a value to create this record type") ds_data = { "key_tag": params['key_tag'], "algorithm": params['algorithm'], "digest_type": params['hash_type'], "digest": params['value'], } new_record = { "type": params['type'], "name": params['record'], 'data': ds_data, "ttl": params['ttl'], } search_value = str(params['key_tag']) + '\t' + str(params['algorithm']) + '\t' + str(params['hash_type']) + '\t' + params['value'] if params['type'] == 'SSHFP': for attr in [params['algorithm'], params['hash_type'], params['value']]: if (attr is None) or (attr == ''): self.module.fail_json(msg="You must provide algorithm, hash_type and a value to create this record type") sshfp_data = { "fingerprint": params['value'], "type": params['hash_type'], "algorithm": params['algorithm'], } new_record = { "type": params['type'], "name": params['record'], 'data': sshfp_data, "ttl": params['ttl'], } search_value = str(params['algorithm']) + '\t' + str(params['hash_type']) + '\t' + params['value'] if params['type'] == 'TLSA': for attr in [params['port'], params['proto'], params['cert_usage'], params['selector'], params['hash_type'], params['value']]: if (attr is None) or (attr == ''): self.module.fail_json(msg="You must provide port, proto, cert_usage, selector, hash_type and a value to create this record type") search_record = params['port'] + '.' + params['proto'] + '.' + params['record'] tlsa_data = { "usage": params['cert_usage'], "selector": params['selector'], "matching_type": params['hash_type'], "certificate": params['value'], } new_record = { "type": params['type'], "name": search_record, 'data': tlsa_data, "ttl": params['ttl'], } search_value = str(params['cert_usage']) + '\t' + str(params['selector']) + '\t' + str(params['hash_type']) + '\t' + params['value'] zone_id = self._get_zone_id(params['zone']) records = self.get_dns_records(params['zone'], params['type'], search_record, search_value) # in theory this should be impossible as cloudflare does not allow # the creation of duplicate records but lets cover it anyways if len(records) > 1: self.module.fail_json(msg="More than one record already exists for the given attributes. That should be impossible, please open an issue!") # record already exists, check if it must be updated if len(records) == 1: cur_record = records[0] do_update = False if (params['ttl'] is not None) and (cur_record['ttl'] != params['ttl']): do_update = True if (params['priority'] is not None) and ('priority' in cur_record) and (cur_record['priority'] != params['priority']): do_update = True if ('proxied' in new_record) and ('proxied' in cur_record) and (cur_record['proxied'] != params['proxied']): do_update = True if ('data' in new_record) and ('data' in cur_record): if (cur_record['data'] != new_record['data']): do_update = True if (params['type'] == 'CNAME') and (cur_record['content'] != new_record['content']): do_update = True if do_update: if self.module.check_mode: result = new_record else: result, info = self._cf_api_call('/zones/{0}/dns_records/{1}'.format(zone_id, records[0]['id']), 'PUT', new_record) self.changed = True return result, self.changed else: return records, self.changed if self.module.check_mode: result = new_record else: result, info = self._cf_api_call('/zones/{0}/dns_records'.format(zone_id), 'POST', new_record) self.changed = True return result, self.changed def main(): module = AnsibleModule( argument_spec=dict( account_api_token=dict(required=True, no_log=True, type='str'), account_email=dict(required=True, type='str'), algorithm=dict(required=False, default=None, type='int'), cert_usage=dict(required=False, default=None, choices=[0, 1, 2, 3], type='int'), hash_type=dict(required=False, default=None, choices=[1, 2], type='int'), key_tag=dict(required=False, default=None, type='int'), port=dict(required=False, default=None, type='int'), priority=dict(required=False, default=1, type='int'), proto=dict(required=False, default=None, type='str'), proxied=dict(required=False, default=False, type='bool'), record=dict(required=False, default='@', aliases=['name'], type='str'), selector=dict(required=False, default=None, choices=[0, 1], type='int'), service=dict(required=False, default=None, type='str'), solo=dict(required=False, default=None, type='bool'), state=dict(required=False, default='present', choices=['present', 'absent'], type='str'), timeout=dict(required=False, default=30, type='int'), ttl=dict(required=False, default=1, type='int'), type=dict(required=False, default=None, choices=['A', 'AAAA', 'CNAME', 'TXT', 'SRV', 'MX', 'NS', 'DS', 'SPF', 'SSHFP', 'TLSA'], type='str'), value=dict(required=False, default=None, aliases=['content'], type='str'), weight=dict(required=False, default=1, type='int'), zone=dict(required=True, default=None, aliases=['domain'], type='str'), ), supports_check_mode=True, required_if=([ ('state', 'present', ['record', 'type', 'value']), ('state', 'absent', ['record']), ('type', 'SRV', ['proto', 'service']), ('type', 'TLSA', ['proto', 'port']), ] ), ) if module.params['type'] == 'SRV': if not ((module.params['weight'] is not None and module.params['port'] is not None and not (module.params['value'] is None or module.params['value'] == '')) or (module.params['weight'] is None and module.params['port'] is None and (module.params['value'] is None or module.params['value'] == ''))): module.fail_json(msg="For SRV records the params weight, port and value all need to be defined, or not at all.") if module.params['type'] == 'SSHFP': if not ((module.params['algorithm'] is not None and module.params['hash_type'] is not None and not (module.params['value'] is None or module.params['value'] == '')) or (module.params['algorithm'] is None and module.params['hash_type'] is None and (module.params['value'] is None or module.params['value'] == ''))): module.fail_json(msg="For SSHFP records the params algorithm, hash_type and value all need to be defined, or not at all.") if module.params['type'] == 'TLSA': if not ((module.params['cert_usage'] is not None and module.params['selector'] is not None and module.params['hash_type'] is not None and not (module.params['value'] is None or module.params['value'] == '')) or (module.params['cert_usage'] is None and module.params['selector'] is None and module.params['hash_type'] is None and (module.params['value'] is None or module.params['value'] == ''))): module.fail_json(msg="For TLSA records the params cert_usage, selector, hash_type and value all need to be defined, or not at all.") if module.params['type'] == 'DS': if not ((module.params['key_tag'] is not None and module.params['algorithm'] is not None and module.params['hash_type'] is not None and not (module.params['value'] is None or module.params['value'] == '')) or (module.params['key_tag'] is None and module.params['algorithm'] is None and module.params['hash_type'] is None and (module.params['value'] is None or module.params['value'] == ''))): module.fail_json(msg="For DS records the params key_tag, algorithm, hash_type and value all need to be defined, or not at all.") changed = False cf_api = CloudflareAPI(module) # sanity checks if cf_api.is_solo and cf_api.state == 'absent': module.fail_json(msg="solo=true can only be used with state=present") # perform add, delete or update (only the TTL can be updated) of one or # more records if cf_api.state == 'present': # delete all records matching record name + type if cf_api.is_solo: changed = cf_api.delete_dns_records(solo=cf_api.is_solo) result, changed = cf_api.ensure_dns_record() if isinstance(result, list): module.exit_json(changed=changed, result={'record': result[0]}) else: module.exit_json(changed=changed, result={'record': result}) else: # force solo to False, just to be sure changed = cf_api.delete_dns_records(solo=False) module.exit_json(changed=changed) if __name__ == '__main__': main()
maartenq/ansible
lib/ansible/modules/net_tools/cloudflare_dns.py
Python
gpl-3.0
33,473
# 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. # ============================================================================== """Deprecation tests.""" # pylint: disable=unused-import from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.platform import test from tensorflow.python.platform import tf_logging as logging from tensorflow.python.util import deprecation class DeprecationTest(test.TestCase): @test.mock.patch.object(logging, "warning", autospec=True) def test_silence(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." @deprecation.deprecated(date, instructions) def _fn(): pass _fn() self.assertEqual(1, mock_warning.call_count) with deprecation.silence(): _fn() self.assertEqual(1, mock_warning.call_count) _fn() self.assertEqual(2, mock_warning.call_count) def _assert_subset(self, expected_subset, actual_set): self.assertTrue( actual_set.issuperset(expected_subset), msg="%s is not a superset of %s." % (actual_set, expected_subset)) def test_deprecated_illegal_args(self): instructions = "This is how you update..." with self.assertRaisesRegexp(ValueError, "YYYY-MM-DD"): deprecation.deprecated("", instructions) with self.assertRaisesRegexp(ValueError, "YYYY-MM-DD"): deprecation.deprecated("07-04-2016", instructions) date = "2016-07-04" with self.assertRaisesRegexp(ValueError, "instructions"): deprecation.deprecated(date, None) with self.assertRaisesRegexp(ValueError, "instructions"): deprecation.deprecated(date, "") @test.mock.patch.object(logging, "warning", autospec=True) def test_no_date(self, mock_warning): date = None instructions = "This is how you update..." @deprecation.deprecated(date, instructions) def _fn(arg0, arg1): """fn doc. Args: arg0: Arg 0. arg1: Arg 1. Returns: Sum of args. """ return arg0 + arg1 self.assertEqual( "fn doc. (deprecated)" "\n" "\nTHIS FUNCTION IS DEPRECATED. It will be removed in a future version." "\nInstructions for updating:\n%s" "\n" "\nArgs:" "\n arg0: Arg 0." "\n arg1: Arg 1." "\n" "\nReturns:" "\n Sum of args." % instructions, _fn.__doc__) # Assert calling new fn issues log warning. self.assertEqual(3, _fn(1, 2)) self.assertEqual(1, mock_warning.call_count) (args, _) = mock_warning.call_args self.assertRegexpMatches( args[0], r"deprecated and will be removed") self._assert_subset(set(["in a future version", instructions]), set(args[1:])) @test.mock.patch.object(logging, "warning", autospec=True) def test_static_fn_with_doc(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." @deprecation.deprecated(date, instructions) def _fn(arg0, arg1): """fn doc. Args: arg0: Arg 0. arg1: Arg 1. Returns: Sum of args. """ return arg0 + arg1 # Assert function docs are properly updated. self.assertEqual("_fn", _fn.__name__) self.assertEqual( "fn doc. (deprecated)" "\n" "\nTHIS FUNCTION IS DEPRECATED. It will be removed after %s." "\nInstructions for updating:\n%s" "\n" "\nArgs:" "\n arg0: Arg 0." "\n arg1: Arg 1." "\n" "\nReturns:" "\n Sum of args." % (date, instructions), _fn.__doc__) # Assert calling new fn issues log warning. self.assertEqual(3, _fn(1, 2)) self.assertEqual(1, mock_warning.call_count) (args, _) = mock_warning.call_args self.assertRegexpMatches(args[0], r"deprecated and will be removed") self._assert_subset(set(["after " + date, instructions]), set(args[1:])) @test.mock.patch.object(logging, "warning", autospec=True) def test_static_fn_with_one_line_doc(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." @deprecation.deprecated(date, instructions) def _fn(arg0, arg1): """fn doc.""" return arg0 + arg1 # Assert function docs are properly updated. self.assertEqual("_fn", _fn.__name__) self.assertEqual( "fn doc. (deprecated)" "\n" "\nTHIS FUNCTION IS DEPRECATED. It will be removed after %s." "\nInstructions for updating:\n%s" % (date, instructions), _fn.__doc__) # Assert calling new fn issues log warning. self.assertEqual(3, _fn(1, 2)) self.assertEqual(1, mock_warning.call_count) (args, _) = mock_warning.call_args self.assertRegexpMatches(args[0], r"deprecated and will be removed") self._assert_subset(set(["after " + date, instructions]), set(args[1:])) @test.mock.patch.object(logging, "warning", autospec=True) def test_static_fn_no_doc(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." @deprecation.deprecated(date, instructions) def _fn(arg0, arg1): return arg0 + arg1 # Assert function docs are properly updated. self.assertEqual("_fn", _fn.__name__) self.assertEqual( "DEPRECATED FUNCTION" "\n" "\nTHIS FUNCTION IS DEPRECATED. It will be removed after %s." "\nInstructions for updating:" "\n%s" % (date, instructions), _fn.__doc__) # Assert calling new fn issues log warning. self.assertEqual(3, _fn(1, 2)) self.assertEqual(1, mock_warning.call_count) (args, _) = mock_warning.call_args self.assertRegexpMatches(args[0], r"deprecated and will be removed") self._assert_subset(set(["after " + date, instructions]), set(args[1:])) @test.mock.patch.object(logging, "warning", autospec=True) def test_instance_fn_with_doc(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." class _Object(object): def __init(self): pass @deprecation.deprecated(date, instructions) def _fn(self, arg0, arg1): """fn doc. Args: arg0: Arg 0. arg1: Arg 1. Returns: Sum of args. """ return arg0 + arg1 # Assert function docs are properly updated. self.assertEqual( "fn doc. (deprecated)" "\n" "\nTHIS FUNCTION IS DEPRECATED. It will be removed after %s." "\nInstructions for updating:\n%s" "\n" "\nArgs:" "\n arg0: Arg 0." "\n arg1: Arg 1." "\n" "\nReturns:" "\n Sum of args." % (date, instructions), getattr(_Object, "_fn").__doc__) # Assert calling new fn issues log warning. self.assertEqual(3, _Object()._fn(1, 2)) self.assertEqual(1, mock_warning.call_count) (args, _) = mock_warning.call_args self.assertRegexpMatches(args[0], r"deprecated and will be removed") self._assert_subset(set(["after " + date, instructions]), set(args[1:])) @test.mock.patch.object(logging, "warning", autospec=True) def test_instance_fn_with_one_line_doc(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." class _Object(object): def __init(self): pass @deprecation.deprecated(date, instructions) def _fn(self, arg0, arg1): """fn doc.""" return arg0 + arg1 # Assert function docs are properly updated. self.assertEqual( "fn doc. (deprecated)" "\n" "\nTHIS FUNCTION IS DEPRECATED. It will be removed after %s." "\nInstructions for updating:\n%s" % (date, instructions), getattr(_Object, "_fn").__doc__) # Assert calling new fn issues log warning. self.assertEqual(3, _Object()._fn(1, 2)) self.assertEqual(1, mock_warning.call_count) (args, _) = mock_warning.call_args self.assertRegexpMatches(args[0], r"deprecated and will be removed") self._assert_subset(set(["after " + date, instructions]), set(args[1:])) @test.mock.patch.object(logging, "warning", autospec=True) def test_instance_fn_no_doc(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." class _Object(object): def __init(self): pass @deprecation.deprecated(date, instructions) def _fn(self, arg0, arg1): return arg0 + arg1 # Assert function docs are properly updated. self.assertEqual( "DEPRECATED FUNCTION" "\n" "\nTHIS FUNCTION IS DEPRECATED. It will be removed after %s." "\nInstructions for updating:" "\n%s" % (date, instructions), getattr(_Object, "_fn").__doc__) # Assert calling new fn issues log warning. self.assertEqual(3, _Object()._fn(1, 2)) self.assertEqual(1, mock_warning.call_count) (args, _) = mock_warning.call_args self.assertRegexpMatches(args[0], r"deprecated and will be removed") self._assert_subset(set(["after " + date, instructions]), set(args[1:])) def test_prop_wrong_order(self): with self.assertRaisesRegexp( ValueError, "make sure @property appears before @deprecated in your source code"): # pylint: disable=unused-variable class _Object(object): def __init(self): pass @deprecation.deprecated("2016-07-04", "Instructions.") @property def _prop(self): return "prop_wrong_order" @test.mock.patch.object(logging, "warning", autospec=True) def test_prop_with_doc(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." class _Object(object): def __init(self): pass @property @deprecation.deprecated(date, instructions) def _prop(self): """prop doc. Returns: String. """ return "prop_with_doc" # Assert function docs are properly updated. self.assertEqual( "prop doc. (deprecated)" "\n" "\nTHIS FUNCTION IS DEPRECATED. It will be removed after %s." "\nInstructions for updating:" "\n%s" "\n" "\nReturns:" "\n String." % (date, instructions), getattr(_Object, "_prop").__doc__) # Assert calling new fn issues log warning. self.assertEqual("prop_with_doc", _Object()._prop) self.assertEqual(1, mock_warning.call_count) (args, _) = mock_warning.call_args self.assertRegexpMatches(args[0], r"deprecated and will be removed") self._assert_subset(set(["after " + date, instructions]), set(args[1:])) @test.mock.patch.object(logging, "warning", autospec=True) def test_prop_no_doc(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." class _Object(object): def __init(self): pass @property @deprecation.deprecated(date, instructions) def _prop(self): return "prop_no_doc" # Assert function docs are properly updated. self.assertEqual( "DEPRECATED FUNCTION" "\n" "\nTHIS FUNCTION IS DEPRECATED. It will be removed after %s." "\nInstructions for updating:" "\n%s" % (date, instructions), getattr(_Object, "_prop").__doc__) # Assert calling new fn issues log warning. self.assertEqual("prop_no_doc", _Object()._prop) self.assertEqual(1, mock_warning.call_count) (args, _) = mock_warning.call_args self.assertRegexpMatches(args[0], r"deprecated and will be removed") self._assert_subset(set(["after " + date, instructions]), set(args[1:])) class DeprecatedArgsTest(test.TestCase): def _assert_subset(self, expected_subset, actual_set): self.assertTrue( actual_set.issuperset(expected_subset), msg="%s is not a superset of %s." % (actual_set, expected_subset)) def test_deprecated_illegal_args(self): instructions = "This is how you update..." date = "2016-07-04" with self.assertRaisesRegexp(ValueError, "YYYY-MM-DD"): deprecation.deprecated_args("", instructions, "deprecated") with self.assertRaisesRegexp(ValueError, "YYYY-MM-DD"): deprecation.deprecated_args("07-04-2016", instructions, "deprecated") with self.assertRaisesRegexp(ValueError, "instructions"): deprecation.deprecated_args(date, None, "deprecated") with self.assertRaisesRegexp(ValueError, "instructions"): deprecation.deprecated_args(date, "", "deprecated") with self.assertRaisesRegexp(ValueError, "argument"): deprecation.deprecated_args(date, instructions) def test_deprecated_missing_args(self): date = "2016-07-04" instructions = "This is how you update..." def _fn(arg0, arg1, deprecated=None): return arg0 + arg1 if deprecated else arg1 + arg0 # Assert calls without the deprecated argument log nothing. with self.assertRaisesRegexp(ValueError, "not present.*\\['missing'\\]"): deprecation.deprecated_args(date, instructions, "missing")(_fn) @test.mock.patch.object(logging, "warning", autospec=True) def test_static_fn_with_doc(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." @deprecation.deprecated_args(date, instructions, "deprecated") def _fn(arg0, arg1, deprecated=True): """fn doc. Args: arg0: Arg 0. arg1: Arg 1. deprecated: Deprecated! Returns: Sum of args. """ return arg0 + arg1 if deprecated else arg1 + arg0 # Assert function docs are properly updated. self.assertEqual("_fn", _fn.__name__) self.assertEqual( "fn doc. (deprecated arguments)" "\n" "\nSOME ARGUMENTS ARE DEPRECATED. They will be removed after %s." "\nInstructions for updating:\n%s" "\n" "\nArgs:" "\n arg0: Arg 0." "\n arg1: Arg 1." "\n deprecated: Deprecated!" "\n" "\nReturns:" "\n Sum of args." % (date, instructions), _fn.__doc__) # Assert calls without the deprecated argument log nothing. self.assertEqual(3, _fn(1, 2)) self.assertEqual(0, mock_warning.call_count) # Assert calls with the deprecated argument log a warning. self.assertEqual(3, _fn(1, 2, True)) self.assertEqual(1, mock_warning.call_count) (args, _) = mock_warning.call_args self.assertRegexpMatches(args[0], r"deprecated and will be removed") self._assert_subset(set(["after " + date, instructions]), set(args[1:])) @test.mock.patch.object(logging, "warning", autospec=True) def test_static_fn_with_one_line_doc(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." @deprecation.deprecated_args(date, instructions, "deprecated") def _fn(arg0, arg1, deprecated=True): """fn doc.""" return arg0 + arg1 if deprecated else arg1 + arg0 # Assert function docs are properly updated. self.assertEqual("_fn", _fn.__name__) self.assertEqual( "fn doc. (deprecated arguments)" "\n" "\nSOME ARGUMENTS ARE DEPRECATED. They will be removed after %s." "\nInstructions for updating:\n%s" % (date, instructions), _fn.__doc__) # Assert calls without the deprecated argument log nothing. self.assertEqual(3, _fn(1, 2)) self.assertEqual(0, mock_warning.call_count) # Assert calls with the deprecated argument log a warning. self.assertEqual(3, _fn(1, 2, True)) self.assertEqual(1, mock_warning.call_count) (args, _) = mock_warning.call_args self.assertRegexpMatches(args[0], r"deprecated and will be removed") self._assert_subset(set(["after " + date, instructions]), set(args[1:])) @test.mock.patch.object(logging, "warning", autospec=True) def test_static_fn_no_doc(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." @deprecation.deprecated_args(date, instructions, "deprecated") def _fn(arg0, arg1, deprecated=True): return arg0 + arg1 if deprecated else arg1 + arg0 # Assert function docs are properly updated. self.assertEqual("_fn", _fn.__name__) self.assertEqual( "DEPRECATED FUNCTION ARGUMENTS" "\n" "\nSOME ARGUMENTS ARE DEPRECATED. They will be removed after %s." "\nInstructions for updating:" "\n%s" % (date, instructions), _fn.__doc__) # Assert calls without the deprecated argument log nothing. self.assertEqual(3, _fn(1, 2)) self.assertEqual(0, mock_warning.call_count) # Assert calls with the deprecated argument log a warning. self.assertEqual(3, _fn(1, 2, True)) self.assertEqual(1, mock_warning.call_count) (args, _) = mock_warning.call_args self.assertRegexpMatches(args[0], r"deprecated and will be removed") self._assert_subset(set(["after " + date, instructions]), set(args[1:])) @test.mock.patch.object(logging, "warning", autospec=True) def test_varargs(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." @deprecation.deprecated_args(date, instructions, "deprecated") def _fn(arg0, arg1, *deprecated): return arg0 + arg1 if deprecated else arg1 + arg0 # Assert calls without the deprecated argument log nothing. self.assertEqual(3, _fn(1, 2)) self.assertEqual(0, mock_warning.call_count) # Assert calls with the deprecated argument log a warning. self.assertEqual(3, _fn(1, 2, True, False)) self.assertEqual(1, mock_warning.call_count) (args, _) = mock_warning.call_args self.assertRegexpMatches(args[0], r"deprecated and will be removed") self._assert_subset(set(["after " + date, instructions]), set(args[1:])) @test.mock.patch.object(logging, "warning", autospec=True) def test_kwargs(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." @deprecation.deprecated_args(date, instructions, "deprecated") def _fn(arg0, arg1, **deprecated): return arg0 + arg1 if deprecated else arg1 + arg0 # Assert calls without the deprecated argument log nothing. self.assertEqual(3, _fn(1, 2)) self.assertEqual(0, mock_warning.call_count) # Assert calls with the deprecated argument log a warning. self.assertEqual(3, _fn(1, 2, a=True, b=False)) self.assertEqual(1, mock_warning.call_count) (args, _) = mock_warning.call_args self.assertRegexpMatches(args[0], r"deprecated and will be removed") self._assert_subset(set(["after " + date, instructions]), set(args[1:])) @test.mock.patch.object(logging, "warning", autospec=True) def test_positional_and_named(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." @deprecation.deprecated_args(date, instructions, "d1", "d2") def _fn(arg0, d1=None, arg1=2, d2=None): return arg0 + arg1 if d1 else arg1 + arg0 if d2 else arg0 * arg1 # Assert calls without the deprecated arguments log nothing. self.assertEqual(2, _fn(1, arg1=2)) self.assertEqual(0, mock_warning.call_count) # Assert calls with the deprecated arguments log warnings. self.assertEqual(2, _fn(1, None, 2, d2=False)) self.assertEqual(2, mock_warning.call_count) (args1, _) = mock_warning.call_args_list[0] self.assertRegexpMatches(args1[0], r"deprecated and will be removed") self._assert_subset(set(["after " + date, instructions, "d1"]), set(args1[1:])) (args2, _) = mock_warning.call_args_list[1] self.assertRegexpMatches(args2[0], r"deprecated and will be removed") self._assert_subset(set(["after " + date, instructions, "d2"]), set(args2[1:])) @test.mock.patch.object(logging, "warning", autospec=True) def test_positional_and_named_with_ok_vals(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." @deprecation.deprecated_args(date, instructions, ("d1", None), ("d2", "my_ok_val")) def _fn(arg0, d1=None, arg1=2, d2=None): return arg0 + arg1 if d1 else arg1 + arg0 if d2 else arg0 * arg1 # Assert calls without the deprecated arguments log nothing. self.assertEqual(2, _fn(1, arg1=2)) self.assertEqual(0, mock_warning.call_count) # Assert calls with the deprecated arguments log warnings. self.assertEqual(2, _fn(1, False, 2, d2=False)) self.assertEqual(2, mock_warning.call_count) (args1, _) = mock_warning.call_args_list[0] self.assertRegexpMatches(args1[0], r"deprecated and will be removed") self._assert_subset(set(["after " + date, instructions, "d1"]), set(args1[1:])) (args2, _) = mock_warning.call_args_list[1] self.assertRegexpMatches(args2[0], r"deprecated and will be removed") self._assert_subset(set(["after " + date, instructions, "d2"]), set(args2[1:])) # Assert calls with the deprecated arguments don't log warnings if # the value matches the 'ok_val'. mock_warning.reset_mock() self.assertEqual(3, _fn(1, None, 2, d2="my_ok_val")) self.assertEqual(0, mock_warning.call_count) class DeprecatedArgValuesTest(test.TestCase): def _assert_subset(self, expected_subset, actual_set): self.assertTrue( actual_set.issuperset(expected_subset), msg="%s is not a superset of %s." % (actual_set, expected_subset)) def test_deprecated_illegal_args(self): instructions = "This is how you update..." with self.assertRaisesRegexp(ValueError, "YYYY-MM-DD"): deprecation.deprecated_arg_values("", instructions, deprecated=True) with self.assertRaisesRegexp(ValueError, "YYYY-MM-DD"): deprecation.deprecated_arg_values( "07-04-2016", instructions, deprecated=True) date = "2016-07-04" with self.assertRaisesRegexp(ValueError, "instructions"): deprecation.deprecated_arg_values(date, None, deprecated=True) with self.assertRaisesRegexp(ValueError, "instructions"): deprecation.deprecated_arg_values(date, "", deprecated=True) with self.assertRaisesRegexp(ValueError, "argument", deprecated=True): deprecation.deprecated_arg_values(date, instructions) @test.mock.patch.object(logging, "warning", autospec=True) def test_static_fn_with_doc(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." @deprecation.deprecated_arg_values(date, instructions, deprecated=True) def _fn(arg0, arg1, deprecated=True): """fn doc. Args: arg0: Arg 0. arg1: Arg 1. deprecated: Deprecated! Returns: Sum of args. """ return arg0 + arg1 if deprecated else arg1 + arg0 # Assert function docs are properly updated. self.assertEqual("_fn", _fn.__name__) self.assertEqual( "fn doc. (deprecated arguments)" "\n" "\nSOME ARGUMENTS ARE DEPRECATED. They will be removed after %s." "\nInstructions for updating:\n%s" "\n" "\nArgs:" "\n arg0: Arg 0." "\n arg1: Arg 1." "\n deprecated: Deprecated!" "\n" "\nReturns:" "\n Sum of args." % (date, instructions), _fn.__doc__) # Assert calling new fn with non-deprecated value logs nothing. self.assertEqual(3, _fn(1, 2, deprecated=False)) self.assertEqual(0, mock_warning.call_count) # Assert calling new fn with deprecated value issues log warning. self.assertEqual(3, _fn(1, 2, deprecated=True)) self.assertEqual(1, mock_warning.call_count) (args, _) = mock_warning.call_args self.assertRegexpMatches(args[0], r"deprecated and will be removed") self._assert_subset(set(["after " + date, instructions]), set(args[1:])) # Assert calling new fn with default deprecated value issues log warning. self.assertEqual(3, _fn(1, 2)) self.assertEqual(2, mock_warning.call_count) @test.mock.patch.object(logging, "warning", autospec=True) def test_static_fn_with_one_line_doc(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." @deprecation.deprecated_arg_values(date, instructions, deprecated=True) def _fn(arg0, arg1, deprecated=True): """fn doc.""" return arg0 + arg1 if deprecated else arg1 + arg0 # Assert function docs are properly updated. self.assertEqual("_fn", _fn.__name__) self.assertEqual( "fn doc. (deprecated arguments)" "\n" "\nSOME ARGUMENTS ARE DEPRECATED. They will be removed after %s." "\nInstructions for updating:\n%s" % (date, instructions), _fn.__doc__) # Assert calling new fn with non-deprecated value logs nothing. self.assertEqual(3, _fn(1, 2, deprecated=False)) self.assertEqual(0, mock_warning.call_count) # Assert calling new fn with deprecated value issues log warning. self.assertEqual(3, _fn(1, 2, deprecated=True)) self.assertEqual(1, mock_warning.call_count) (args, _) = mock_warning.call_args self.assertRegexpMatches(args[0], r"deprecated and will be removed") self._assert_subset(set(["after " + date, instructions]), set(args[1:])) # Assert calling new fn with default deprecated value issues log warning. self.assertEqual(3, _fn(1, 2)) self.assertEqual(2, mock_warning.call_count) @test.mock.patch.object(logging, "warning", autospec=True) def test_static_fn_no_doc(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." @deprecation.deprecated_arg_values(date, instructions, deprecated=True) def _fn(arg0, arg1, deprecated=True): return arg0 + arg1 if deprecated else arg1 + arg0 # Assert function docs are properly updated. self.assertEqual("_fn", _fn.__name__) self.assertEqual( "DEPRECATED FUNCTION ARGUMENTS" "\n" "\nSOME ARGUMENTS ARE DEPRECATED. They will be removed after %s." "\nInstructions for updating:" "\n%s" % (date, instructions), _fn.__doc__) # Assert calling new fn with non-deprecated value logs nothing. self.assertEqual(3, _fn(1, 2, deprecated=False)) self.assertEqual(0, mock_warning.call_count) # Assert calling new fn issues log warning. self.assertEqual(3, _fn(1, 2, deprecated=True)) self.assertEqual(1, mock_warning.call_count) (args, _) = mock_warning.call_args self.assertRegexpMatches(args[0], r"deprecated and will be removed") self._assert_subset(set(["after " + date, instructions]), set(args[1:])) # Assert calling new fn with default deprecated value issues log warning. self.assertEqual(3, _fn(1, 2)) self.assertEqual(2, mock_warning.call_count) class DeprecationArgumentsTest(test.TestCase): def testDeprecatedArgumentLookup(self): good_value = 3 self.assertEqual( deprecation.deprecated_argument_lookup("val_new", good_value, "val_old", None), good_value) self.assertEqual( deprecation.deprecated_argument_lookup("val_new", None, "val_old", good_value), good_value) with self.assertRaisesRegexp(ValueError, "Cannot specify both 'val_old' and 'val_new'"): self.assertEqual( deprecation.deprecated_argument_lookup("val_new", good_value, "val_old", good_value), good_value) def testRewriteArgumentDocstring(self): docs = """Add `a` and `b` Args: a: first arg b: second arg """ new_docs = deprecation.rewrite_argument_docstring( deprecation.rewrite_argument_docstring(docs, "a", "left"), "b", "right") new_docs_ref = """Add `left` and `right` Args: left: first arg right: second arg """ self.assertEqual(new_docs, new_docs_ref) if __name__ == "__main__": test.main()
npuichigo/ttsflow
third_party/tensorflow/tensorflow/python/util/deprecation_test.py
Python
apache-2.0
28,547
from __future__ import division, absolute_import, print_function import numpy as np from numpy.testing import assert_array_equal, assert_equal, assert_raises def test_packbits(): # Copied from the docstring. a = [[[1, 0, 1], [0, 1, 0]], [[1, 1, 0], [0, 0, 1]]] for dt in '?bBhHiIlLqQ': arr = np.array(a, dtype=dt) b = np.packbits(arr, axis=-1) assert_equal(b.dtype, np.uint8) assert_array_equal(b, np.array([[[160], [64]], [[192], [32]]])) assert_raises(TypeError, np.packbits, np.array(a, dtype=float)) def test_packbits_empty(): shapes = [ (0,), (10, 20, 0), (10, 0, 20), (0, 10, 20), (20, 0, 0), (0, 20, 0), (0, 0, 20), (0, 0, 0), ] for dt in '?bBhHiIlLqQ': for shape in shapes: a = np.empty(shape, dtype=dt) b = np.packbits(a) assert_equal(b.dtype, np.uint8) assert_equal(b.shape, (0,)) def test_packbits_empty_with_axis(): # Original shapes and lists of packed shapes for different axes. shapes = [ ((0,), [(0,)]), ((10, 20, 0), [(2, 20, 0), (10, 3, 0), (10, 20, 0)]), ((10, 0, 20), [(2, 0, 20), (10, 0, 20), (10, 0, 3)]), ((0, 10, 20), [(0, 10, 20), (0, 2, 20), (0, 10, 3)]), ((20, 0, 0), [(3, 0, 0), (20, 0, 0), (20, 0, 0)]), ((0, 20, 0), [(0, 20, 0), (0, 3, 0), (0, 20, 0)]), ((0, 0, 20), [(0, 0, 20), (0, 0, 20), (0, 0, 3)]), ((0, 0, 0), [(0, 0, 0), (0, 0, 0), (0, 0, 0)]), ] for dt in '?bBhHiIlLqQ': for in_shape, out_shapes in shapes: for ax, out_shape in enumerate(out_shapes): a = np.empty(in_shape, dtype=dt) b = np.packbits(a, axis=ax) assert_equal(b.dtype, np.uint8) assert_equal(b.shape, out_shape) def test_unpackbits(): # Copied from the docstring. a = np.array([[2], [7], [23]], dtype=np.uint8) b = np.unpackbits(a, axis=1) assert_equal(b.dtype, np.uint8) assert_array_equal(b, np.array([[0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 0, 1, 1, 1]])) def test_unpackbits_empty(): a = np.empty((0,), dtype=np.uint8) b = np.unpackbits(a) assert_equal(b.dtype, np.uint8) assert_array_equal(b, np.empty((0,))) def test_unpackbits_empty_with_axis(): # Lists of packed shapes for different axes and unpacked shapes. shapes = [ ([(0,)], (0,)), ([(2, 24, 0), (16, 3, 0), (16, 24, 0)], (16, 24, 0)), ([(2, 0, 24), (16, 0, 24), (16, 0, 3)], (16, 0, 24)), ([(0, 16, 24), (0, 2, 24), (0, 16, 3)], (0, 16, 24)), ([(3, 0, 0), (24, 0, 0), (24, 0, 0)], (24, 0, 0)), ([(0, 24, 0), (0, 3, 0), (0, 24, 0)], (0, 24, 0)), ([(0, 0, 24), (0, 0, 24), (0, 0, 3)], (0, 0, 24)), ([(0, 0, 0), (0, 0, 0), (0, 0, 0)], (0, 0, 0)), ] for in_shapes, out_shape in shapes: for ax, in_shape in enumerate(in_shapes): a = np.empty(in_shape, dtype=np.uint8) b = np.unpackbits(a, axis=ax) assert_equal(b.dtype, np.uint8) assert_equal(b.shape, out_shape)
jjas0nn/solvem
tensorflow/lib/python2.7/site-packages/numpy/lib/tests/test_packbits.py
Python
mit
3,214
from sentry.testutils.cases import RuleTestCase from sentry.rules.conditions.level import LevelCondition, LevelMatchType class LevelConditionTest(RuleTestCase): rule_cls = LevelCondition def get_event(self): event = self.event event.group.level = 20 return event def test_equals(self): event = self.get_event() rule = self.get_rule({ 'match': LevelMatchType.EQUAL, 'level': '20', }) self.assertPasses(rule, event) rule = self.get_rule({ 'match': LevelMatchType.EQUAL, 'level': '30', }) self.assertDoesNotPass(rule, event) def test_greater_than(self): event = self.get_event() rule = self.get_rule({ 'match': LevelMatchType.GREATER_OR_EQUAL, 'level': '40', }) self.assertDoesNotPass(rule, event) rule = self.get_rule({ 'match': LevelMatchType.GREATER_OR_EQUAL, 'level': '20', }) self.assertPasses(rule, event) def test_less_than(self): event = self.get_event() rule = self.get_rule({ 'match': LevelMatchType.LESS_OR_EQUAL, 'level': '10', }) self.assertDoesNotPass(rule, event) rule = self.get_rule({ 'match': LevelMatchType.LESS_OR_EQUAL, 'level': '30', }) self.assertPasses(rule, event)
wujuguang/sentry
tests/sentry/rules/conditions/test_level_event.py
Python
bsd-3-clause
1,452
#!/usr/bin/python """ Test the TahoeLAFS @author: Marek Palatinus <marek@palatinus.cz> """ import sys import logging import unittest from fs.base import FS import fs.errors as errors from fs.tests import FSTestCases, ThreadingTestCases from fs.contrib.tahoelafs import TahoeLAFS, Connection logging.getLogger().setLevel(logging.DEBUG) logging.getLogger('fs.tahoelafs').addHandler(logging.StreamHandler(sys.stdout)) WEBAPI = 'http://insecure.tahoe-lafs.org' # The public grid is too slow for threading testcases, disabling for now... class TestTahoeLAFS(unittest.TestCase,FSTestCases):#,ThreadingTestCases): # Disabled by default because it takes a *really* long time. __test__ = False def setUp(self): self.dircap = TahoeLAFS.createdircap(WEBAPI) self.fs = TahoeLAFS(self.dircap, cache_timeout=0, webapi=WEBAPI) def tearDown(self): self.fs.close() def test_dircap(self): # Is dircap in correct format? self.assert_(self.dircap.startswith('URI:DIR2:') and len(self.dircap) > 50) def test_concurrent_copydir(self): # makedir() on TahoeLAFS is currently not atomic pass def test_makedir_winner(self): # makedir() on TahoeLAFS is currently not atomic pass def test_big_file(self): pass if __name__ == '__main__': unittest.main()
GbalsaC/bitnamiP
venv/lib/python2.7/site-packages/fs/contrib/tahoelafs/test_tahoelafs.py
Python
agpl-3.0
1,455
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function import numbers from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import tensor_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops import gen_math_ops from tensorflow.python.ops import math_ops def alpha_dropout(x, keep_prob, noise_shape=None, seed=None, name=None): # pylint: disable=invalid-name """Computes alpha dropout. Alpha Dropout is a dropout that maintains the self-normalizing property. For an input with zero mean and unit standard deviation, the output of Alpha Dropout maintains the original mean and standard deviation of the input. See [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515) Args: x: A tensor. keep_prob: A scalar `Tensor` with the same type as x. The probability that each element is kept. noise_shape: A 1-D `Tensor` of type `int32`, representing the shape for randomly generated keep/drop flags. seed: A Python integer. Used to create random seeds. See `tf.set_random_seed` for behavior. name: A name for this operation (optional). Returns: A Tensor of the same shape of `x`. Raises: ValueError: If `keep_prob` is not in `(0, 1]`. """ with ops.name_scope(name, "alpha_dropout", [x]) as name: x = ops.convert_to_tensor(x, name="x") if isinstance(keep_prob, numbers.Real) and not 0 < keep_prob <= 1.: raise ValueError("keep_prob must be a scalar tensor or a float in the " "range (0, 1], got %g" % keep_prob) keep_prob = ops.convert_to_tensor(keep_prob, dtype=x.dtype, name="keep_prob") keep_prob.get_shape().assert_is_compatible_with(tensor_shape.scalar()) # Do nothing if we know keep_prob == 1 if tensor_util.constant_value(keep_prob) == 1: return x alpha = -1.7580993408473766 noise_shape = noise_shape if noise_shape is not None else array_ops.shape(x) random_tensor = random_ops.random_uniform(noise_shape, seed=seed, dtype=x.dtype) kept_idx = gen_math_ops.greater_equal(random_tensor, 1 - keep_prob) kept_idx = math_ops.cast(kept_idx, x.dtype) # Mask x = x * kept_idx + alpha * (1 - kept_idx) # Affine transformation parameters a = (keep_prob + keep_prob * (1 - keep_prob) * alpha ** 2) ** -0.5 b = -a * alpha * (1 - keep_prob) # Affine transformation return a * x + b
jbedorf/tensorflow
tensorflow/contrib/nn/python/ops/alpha_dropout.py
Python
apache-2.0
3,426
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """extenders tests.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib.data.python.ops import dataset_ops from tensorflow.contrib.estimator.python.estimator import extenders from tensorflow.python.estimator import estimator_lib from tensorflow.python.estimator.canned import linear from tensorflow.python.feature_column import feature_column as fc from tensorflow.python.framework import constant_op from tensorflow.python.framework import ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.ops import metrics as metrics_lib from tensorflow.python.ops import variables from tensorflow.python.platform import test from tensorflow.python.training import training def get_input_fn(x, y): def input_fn(): dataset = dataset_ops.Dataset.from_tensor_slices({'x': x, 'y': y}) iterator = dataset.make_one_shot_iterator() features = iterator.get_next() labels = features.pop('y') return features, labels return input_fn class AddMetricsTest(test.TestCase): def test_should_add_metrics(self): input_fn = get_input_fn( x=np.arange(4)[:, None, None], y=np.ones(4)[:, None]) estimator = linear.LinearClassifier([fc.numeric_column('x')]) def metric_fn(features): return {'mean_x': metrics_lib.mean(features['x'])} estimator = extenders.add_metrics(estimator, metric_fn) estimator.train(input_fn=input_fn) metrics = estimator.evaluate(input_fn=input_fn) self.assertIn('mean_x', metrics) self.assertEqual(1.5, metrics['mean_x']) # assert that it keeps original estimators metrics self.assertIn('auc', metrics) def test_should_error_out_for_not_recognized_args(self): estimator = linear.LinearClassifier([fc.numeric_column('x')]) def metric_fn(features, not_recognized): _, _ = features, not_recognized return {} with self.assertRaisesRegexp(ValueError, 'not_recognized'): estimator = extenders.add_metrics(estimator, metric_fn) def test_all_supported_args(self): input_fn = get_input_fn(x=[[[0.]]], y=[[[1]]]) estimator = linear.LinearClassifier([fc.numeric_column('x')]) def metric_fn(features, predictions, labels, config): self.assertIn('x', features) self.assertIsNotNone(labels) self.assertIn('logistic', predictions) self.assertTrue(isinstance(config, estimator_lib.RunConfig)) return {} estimator = extenders.add_metrics(estimator, metric_fn) estimator.train(input_fn=input_fn) estimator.evaluate(input_fn=input_fn) def test_all_supported_args_in_different_order(self): input_fn = get_input_fn(x=[[[0.]]], y=[[[1]]]) estimator = linear.LinearClassifier([fc.numeric_column('x')]) def metric_fn(labels, config, features, predictions): self.assertIn('x', features) self.assertIsNotNone(labels) self.assertIn('logistic', predictions) self.assertTrue(isinstance(config, estimator_lib.RunConfig)) return {} estimator = extenders.add_metrics(estimator, metric_fn) estimator.train(input_fn=input_fn) estimator.evaluate(input_fn=input_fn) def test_all_args_are_optional(self): input_fn = get_input_fn(x=[[[0.]]], y=[[[1]]]) estimator = linear.LinearClassifier([fc.numeric_column('x')]) def metric_fn(): return {'two': metrics_lib.mean(constant_op.constant([2.]))} estimator = extenders.add_metrics(estimator, metric_fn) estimator.train(input_fn=input_fn) metrics = estimator.evaluate(input_fn=input_fn) self.assertEqual(2., metrics['two']) def test_overrides_existing_metrics(self): input_fn = get_input_fn(x=[[[0.]]], y=[[[1]]]) estimator = linear.LinearClassifier([fc.numeric_column('x')]) estimator.train(input_fn=input_fn) metrics = estimator.evaluate(input_fn=input_fn) self.assertNotEqual(2., metrics['auc']) def metric_fn(): return {'auc': metrics_lib.mean(constant_op.constant([2.]))} estimator = extenders.add_metrics(estimator, metric_fn) metrics = estimator.evaluate(input_fn=input_fn) self.assertEqual(2., metrics['auc']) class ClipGradientsByNormTest(test.TestCase): """Tests clip_gradients_by_norm.""" def test_applies_norm(self): optimizer = extenders.clip_gradients_by_norm( training.GradientDescentOptimizer(1.0), clip_norm=3.) with ops.Graph().as_default(): w = variables.Variable(1., name='weight') x = constant_op.constant(5.) y = -x * w grads = optimizer.compute_gradients(y, var_list=[w])[0] opt_op = optimizer.minimize(y, var_list=[w]) with training.MonitoredSession() as sess: grads_value = sess.run(grads) self.assertEqual(-5., grads_value[0]) sess.run(opt_op) new_w = sess.run(w) self.assertEqual(4., new_w) # 1 + 1*3 (w - lr * clipped_grad) def test_name(self): optimizer = extenders.clip_gradients_by_norm( training.GradientDescentOptimizer(1.0), clip_norm=3.) self.assertEqual('ClipByNormGradientDescent', optimizer.get_name()) class ForwardFeaturesTest(test.TestCase): """Tests forward_features.""" def test_forward_single_key(self): def input_fn(): return {'x': [[3.], [5.]], 'id': [[101], [102]]}, [[1.], [2.]] estimator = linear.LinearRegressor([fc.numeric_column('x')]) estimator.train(input_fn=input_fn, steps=1) self.assertNotIn('id', next(estimator.predict(input_fn=input_fn))) estimator = extenders.forward_features(estimator, 'id') predictions = next(estimator.predict(input_fn=input_fn)) self.assertIn('id', predictions) self.assertEqual(101, predictions['id']) def test_forward_list(self): def input_fn(): return {'x': [[3.], [5.]], 'id': [[101], [102]]}, [[1.], [2.]] estimator = linear.LinearRegressor([fc.numeric_column('x')]) estimator.train(input_fn=input_fn, steps=1) self.assertNotIn('id', next(estimator.predict(input_fn=input_fn))) estimator = extenders.forward_features(estimator, ['x', 'id']) predictions = next(estimator.predict(input_fn=input_fn)) self.assertIn('id', predictions) self.assertIn('x', predictions) self.assertEqual(101, predictions['id']) self.assertEqual(3., predictions['x']) def test_forward_all(self): def input_fn(): return {'x': [[3.], [5.]], 'id': [[101], [102]]}, [[1.], [2.]] estimator = linear.LinearRegressor([fc.numeric_column('x')]) estimator.train(input_fn=input_fn, steps=1) self.assertNotIn('id', next(estimator.predict(input_fn=input_fn))) self.assertNotIn('x', next(estimator.predict(input_fn=input_fn))) estimator = extenders.forward_features(estimator) predictions = next(estimator.predict(input_fn=input_fn)) self.assertIn('id', predictions) self.assertIn('x', predictions) self.assertEqual(101, predictions['id']) self.assertEqual(3., predictions['x']) def test_key_should_be_string(self): estimator = linear.LinearRegressor([fc.numeric_column('x')]) with self.assertRaisesRegexp(TypeError, 'keys should be either a string'): extenders.forward_features(estimator, estimator) def test_key_should_be_list_of_string(self): estimator = linear.LinearRegressor([fc.numeric_column('x')]) with self.assertRaisesRegexp(TypeError, 'should be a string'): extenders.forward_features(estimator, ['x', estimator]) def test_key_should_be_in_features(self): def input_fn(): return {'x': [[3.], [5.]], 'id': [[101], [102]]}, [[1.], [2.]] estimator = linear.LinearRegressor([fc.numeric_column('x')]) estimator.train(input_fn=input_fn, steps=1) estimator = extenders.forward_features(estimator, 'y') with self.assertRaisesRegexp(ValueError, 'keys should be exist in features'): next(estimator.predict(input_fn=input_fn)) def test_forwarded_feature_should_not_be_a_sparse_tensor(self): def input_fn(): return { 'x': [[3.], [5.]], 'id': sparse_tensor.SparseTensor( values=['1', '2'], indices=[[0, 0], [1, 0]], dense_shape=[2, 1]) }, [[1.], [2.]] estimator = linear.LinearRegressor([fc.numeric_column('x')]) estimator.train(input_fn=input_fn, steps=1) estimator = extenders.forward_features(estimator) with self.assertRaisesRegexp(ValueError, 'Forwarded feature.* should be a Tensor.'): next(estimator.predict(input_fn=input_fn)) def test_predictions_should_be_dict(self): def input_fn(): return {'x': [[3.], [5.]], 'id': [[101], [102]]} def model_fn(features, mode): del features global_step = training.get_global_step() return estimator_lib.EstimatorSpec( mode, loss=constant_op.constant([5.]), predictions=constant_op.constant([5.]), train_op=global_step.assign_add(1)) estimator = estimator_lib.Estimator(model_fn=model_fn) estimator.train(input_fn=input_fn, steps=1) estimator = extenders.forward_features(estimator) with self.assertRaisesRegexp(ValueError, 'Predictions should be a dict'): next(estimator.predict(input_fn=input_fn)) def test_should_not_conflict_with_existing_predictions(self): def input_fn(): return {'x': [[3.], [5.]], 'id': [[101], [102]]} def model_fn(features, mode): del features global_step = training.get_global_step() return estimator_lib.EstimatorSpec( mode, loss=constant_op.constant([5.]), predictions={'x': constant_op.constant([5.])}, train_op=global_step.assign_add(1)) estimator = estimator_lib.Estimator(model_fn=model_fn) estimator.train(input_fn=input_fn, steps=1) estimator = extenders.forward_features(estimator) with self.assertRaisesRegexp(ValueError, 'Cannot forward feature key'): next(estimator.predict(input_fn=input_fn)) if __name__ == '__main__': test.main()
eadgarchen/tensorflow
tensorflow/contrib/estimator/python/estimator/extenders_test.py
Python
apache-2.0
10,770
# ============================================================================= # 2013+ Copyright (c) Alexey Ivanov <rbtz@ph34r.me> # All rights reserved. # # 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. # ============================================================================= from __future__ import absolute_import
reverbrain/elliptics
recovery/elliptics_recovery/types/__init__.py
Python
lgpl-3.0
769
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import shutil from errno import EEXIST from ansible.errors import AnsibleError from ansible.module_utils._text import to_bytes, to_native, to_text __all__ = ['unfrackpath', 'makedirs_safe'] def unfrackpath(path, follow=True, basedir=None): ''' Returns a path that is free of symlinks (if follow=True), environment variables, relative path traversals and symbols (~) :arg path: A byte or text string representing a path to be canonicalized :arg follow: A boolean to indicate of symlinks should be resolved or not :raises UnicodeDecodeError: If the canonicalized version of the path contains non-utf8 byte sequences. :rtype: A text string (unicode on pyyhon2, str on python3). :returns: An absolute path with symlinks, environment variables, and tilde expanded. Note that this does not check whether a path exists. example:: '$HOME/../../var/mail' becomes '/var/spool/mail' ''' b_basedir = to_bytes(basedir, errors='surrogate_or_strict', nonstring='passthru') if b_basedir is None: b_basedir = to_bytes(os.getcwd(), errors='surrogate_or_strict') elif os.path.isfile(b_basedir): b_basedir = os.path.dirname(b_basedir) b_final_path = os.path.expanduser(os.path.expandvars(to_bytes(path, errors='surrogate_or_strict'))) if not os.path.isabs(b_final_path): b_final_path = os.path.join(b_basedir, b_final_path) if follow: b_final_path = os.path.realpath(b_final_path) return to_text(os.path.normpath(b_final_path), errors='surrogate_or_strict') def makedirs_safe(path, mode=None): ''' A *potentially insecure* way to ensure the existence of a directory chain. The "safe" in this function's name refers only to its ability to ignore `EEXIST` in the case of multiple callers operating on the same part of the directory chain. This function is not safe to use under world-writable locations when the first level of the path to be created contains a predictable component. Always create a randomly-named element first if there is any chance the parent directory might be world-writable (eg, /tmp) to prevent symlink hijacking and potential disclosure or modification of sensitive file contents. :arg path: A byte or text string representing a directory chain to be created :kwarg mode: If given, the mode to set the directory to :raises AnsibleError: If the directory cannot be created and does not already exist. :raises UnicodeDecodeError: if the path is not decodable in the utf-8 encoding. ''' rpath = unfrackpath(path) b_rpath = to_bytes(rpath) if not os.path.exists(b_rpath): try: if mode: os.makedirs(b_rpath, mode) else: os.makedirs(b_rpath) except OSError as e: if e.errno != EEXIST: raise AnsibleError("Unable to create local directories(%s): %s" % (to_native(rpath), to_native(e))) def basedir(source): """ returns directory for inventory or playbook """ source = to_bytes(source, errors='surrogate_or_strict') dname = None if os.path.isdir(source): dname = source elif source in [None, '', '.']: dname = os.getcwd() elif os.path.isfile(source): dname = os.path.dirname(source) if dname: # don't follow symlinks for basedir, enables source re-use dname = os.path.abspath(dname) return to_text(dname, errors='surrogate_or_strict') def cleanup_tmp_file(path, warn=False): """ Removes temporary file or directory. Optionally display a warning if unable to remove the file or directory. :arg path: Path to file or directory to be removed :kwarg warn: Whether or not to display a warning when the file or directory cannot be removed """ try: if os.path.exists(path): try: if os.path.isdir(path): shutil.rmtree(path) elif os.path.isfile(path): os.unlink(path) except Exception as e: if warn: # Importing here to avoid circular import from ansible.utils.display import Display display = Display() display.display(u'Unable to remove temporary file {0}'.format(to_text(e))) except Exception: pass
thaim/ansible
lib/ansible/utils/path.py
Python
mit
5,225
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import os import shutil from unittest import TestCase, TestSuite, TestLoader, TextTestRunner from babelfish import Language from subliminal import list_subtitles, download_subtitles, save_subtitles, download_best_subtitles, scan_video from subliminal.tests.common import MOVIES, EPISODES TEST_DIR = 'test_data' class ApiTestCase(TestCase): def setUp(self): os.mkdir(TEST_DIR) def tearDown(self): shutil.rmtree(TEST_DIR) def test_list_subtitles_movie_0(self): videos = [MOVIES[0]] languages = {Language('eng')} subtitles = list_subtitles(videos, languages) self.assertEqual(len(subtitles), len(videos)) self.assertGreater(len(subtitles[videos[0]]), 0) def test_list_subtitles_movie_0_por_br(self): videos = [MOVIES[0]] languages = {Language('por', 'BR')} subtitles = list_subtitles(videos, languages) self.assertEqual(len(subtitles), len(videos)) self.assertGreater(len(subtitles[videos[0]]), 0) def test_list_subtitles_episodes(self): videos = [EPISODES[0], EPISODES[1]] languages = {Language('eng'), Language('fra')} subtitles = list_subtitles(videos, languages) self.assertEqual(len(subtitles), len(videos)) self.assertGreater(len(subtitles[videos[0]]), 0) def test_download_subtitles(self): videos = [EPISODES[0]] for video in videos: video.name = os.path.join(TEST_DIR, os.path.split(video.name)[1]) languages = {Language('eng')} subtitles = list_subtitles(videos, languages) download_subtitles(subtitles[videos[0]][:5]) self.assertGreaterEqual(len([s for s in subtitles[videos[0]] if s.content is not None]), 4) def test_download_best_subtitles(self): videos = [EPISODES[0], EPISODES[1]] for video in videos: video.name = os.path.join(TEST_DIR, os.path.split(video.name)[1]) languages = {Language('eng'), Language('fra')} subtitles = download_best_subtitles(videos, languages) for video in videos: self.assertIn(video, subtitles) self.assertEqual(len(subtitles[video]), 2) def test_save_subtitles(self): videos = [EPISODES[0], EPISODES[1]] for video in videos: video.name = os.path.join(TEST_DIR, os.path.split(video.name)[1]) languages = {Language('eng'), Language('fra')} subtitles = list_subtitles(videos, languages) # make a list of subtitles to download (one per language per video) subtitles_to_download = [] for video, video_subtitles in subtitles.items(): video_subtitle_languages = set() for video_subtitle in video_subtitles: if video_subtitle.language in video_subtitle_languages: continue subtitles_to_download.append(video_subtitle) video_subtitle_languages.add(video_subtitle.language) if video_subtitle_languages == languages: break self.assertEqual(len(subtitles_to_download), 4) # download download_subtitles(subtitles_to_download) save_subtitles(subtitles) for video in videos: self.assertTrue(os.path.exists(os.path.splitext(video.name)[0] + '.en.srt')) self.assertTrue(os.path.exists(os.path.splitext(video.name)[0] + '.fr.srt')) def test_save_subtitles_single(self): videos = [EPISODES[0], EPISODES[1]] for video in videos: video.name = os.path.join(TEST_DIR, os.path.split(video.name)[1]) languages = {Language('eng'), Language('fra')} subtitles = download_best_subtitles(videos, languages) save_subtitles(subtitles, single=True) for video in videos: self.assertIn(video, subtitles) self.assertEqual(len(subtitles[video]), 2) self.assertTrue(os.path.exists(os.path.splitext(video.name)[0] + '.srt')) def test_download_best_subtitles_min_score(self): videos = [MOVIES[0]] for video in videos: video.name = os.path.join(TEST_DIR, os.path.split(video.name)[1]) languages = {Language('eng'), Language('fra')} subtitles = download_best_subtitles(videos, languages, min_score=1000) self.assertEqual(len(subtitles), 0) def test_download_best_subtitles_hearing_impaired(self): videos = [MOVIES[0]] for video in videos: video.name = os.path.join(TEST_DIR, os.path.split(video.name)[1]) languages = {Language('eng')} subtitles = download_best_subtitles(videos, languages, hearing_impaired=True) self.assertTrue(subtitles[videos[0]][0].hearing_impaired) class VideoTestCase(TestCase): def setUp(self): os.mkdir(TEST_DIR) for video in MOVIES + EPISODES: open(os.path.join(TEST_DIR, os.path.split(video.name)[1]), 'w').close() def tearDown(self): shutil.rmtree(TEST_DIR) def test_scan_video_movie(self): video = MOVIES[0] scanned_video = scan_video(os.path.join(TEST_DIR, os.path.split(video.name)[1])) self.assertEqual(scanned_video.name, os.path.join(TEST_DIR, os.path.split(video.name)[1])) self.assertEqual(scanned_video.title.lower(), video.title.lower()) self.assertEqual(scanned_video.year, video.year) self.assertEqual(scanned_video.video_codec, video.video_codec) self.assertEqual(scanned_video.format, video.format) self.assertEqual(scanned_video.resolution, video.resolution) self.assertEqual(scanned_video.release_group, video.release_group) self.assertEqual(scanned_video.subtitle_languages, set()) self.assertEqual(scanned_video.hashes, {}) self.assertIsNone(scanned_video.audio_codec) self.assertIsNone(scanned_video.imdb_id) self.assertEqual(scanned_video.size, 0) def test_scan_video_episode(self): video = EPISODES[0] scanned_video = scan_video(os.path.join(TEST_DIR, os.path.split(video.name)[1])) self.assertEqual(scanned_video.name, os.path.join(TEST_DIR, os.path.split(video.name)[1])) self.assertEqual(scanned_video.series, video.series) self.assertEqual(scanned_video.season, video.season) self.assertEqual(scanned_video.episode, video.episode) self.assertEqual(scanned_video.video_codec, video.video_codec) self.assertEqual(scanned_video.format, video.format) self.assertEqual(scanned_video.resolution, video.resolution) self.assertEqual(scanned_video.release_group, video.release_group) self.assertEqual(scanned_video.subtitle_languages, set()) self.assertEqual(scanned_video.hashes, {}) self.assertIsNone(scanned_video.title) self.assertIsNone(scanned_video.tvdb_id) self.assertIsNone(scanned_video.imdb_id) self.assertIsNone(scanned_video.audio_codec) self.assertEqual(scanned_video.size, 0) def test_scan_video_subtitle_language_und(self): video = EPISODES[0] open(os.path.join(TEST_DIR, os.path.splitext(os.path.split(video.name)[1])[0]) + '.srt', 'w').close() scanned_video = scan_video(os.path.join(TEST_DIR, os.path.split(video.name)[1])) self.assertEqual(scanned_video.subtitle_languages, {Language('und')}) def test_scan_video_subtitles_language_eng(self): video = EPISODES[0] open(os.path.join(TEST_DIR, os.path.splitext(os.path.split(video.name)[1])[0]) + '.en.srt', 'w').close() scanned_video = scan_video(os.path.join(TEST_DIR, os.path.split(video.name)[1])) self.assertEqual(scanned_video.subtitle_languages, {Language('eng')}) def test_scan_video_subtitles_languages(self): video = EPISODES[0] open(os.path.join(TEST_DIR, os.path.splitext(os.path.split(video.name)[1])[0]) + '.en.srt', 'w').close() open(os.path.join(TEST_DIR, os.path.splitext(os.path.split(video.name)[1])[0]) + '.fr.srt', 'w').close() open(os.path.join(TEST_DIR, os.path.splitext(os.path.split(video.name)[1])[0]) + '.srt', 'w').close() scanned_video = scan_video(os.path.join(TEST_DIR, os.path.split(video.name)[1])) self.assertEqual(scanned_video.subtitle_languages, {Language('eng'), Language('fra'), Language('und')}) def suite(): suite = TestSuite() suite.addTest(TestLoader().loadTestsFromTestCase(ApiTestCase)) suite.addTest(TestLoader().loadTestsFromTestCase(VideoTestCase)) return suite if __name__ == '__main__': TextTestRunner().run(suite())
ravselj/subliminal
subliminal/tests/test_subliminal.py
Python
mit
8,711
""" FacetGrid with custom projection ================================ _thumb: .33, .5 """ import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns sns.set() # Generate an example radial datast r = np.linspace(0, 10, num=100) df = pd.DataFrame({'r': r, 'slow': r, 'medium': 2 * r, 'fast': 4 * r}) # Convert the dataframe to long-form or "tidy" format df = pd.melt(df, id_vars=['r'], var_name='speed', value_name='theta') # Set up a grid of axes with a polar projection g = sns.FacetGrid(df, col="speed", hue="speed", subplot_kws=dict(projection='polar'), size=4.5, sharex=False, sharey=False, despine=False) # Draw a scatterplot onto each axes in the grid g.map(plt.scatter, "theta", "r")
lypzln/seaborn
examples/facets_with_custom_projection.py
Python
bsd-3-clause
767
# -*- coding: utf-8 -*- # Copyright: (c) 2014, Hewlett-Packard Development Company, L.P. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) class ModuleDocFragment(object): # Standard openstack documentation fragment DOCUMENTATION = r''' options: cloud: description: - Named cloud or cloud config to operate against. If I(cloud) is a string, it references a named cloud config as defined in an OpenStack clouds.yaml file. Provides default values for I(auth) and I(auth_type). This parameter is not needed if I(auth) is provided or if OpenStack OS_* environment variables are present. If I(cloud) is a dict, it contains a complete cloud configuration like would be in a section of clouds.yaml. type: raw auth: description: - Dictionary containing auth information as needed by the cloud's auth plugin strategy. For the default I(password) plugin, this would contain I(auth_url), I(username), I(password), I(project_name) and any information about domains (for example, I(os_user_domain_name) or I(os_project_domain_name)) if the cloud supports them. For other plugins, this param will need to contain whatever parameters that auth plugin requires. This parameter is not needed if a named cloud is provided or OpenStack OS_* environment variables are present. type: dict auth_type: description: - Name of the auth plugin to use. If the cloud uses something other than password authentication, the name of the plugin should be indicated here and the contents of the I(auth) parameter should be updated accordingly. type: str region_name: description: - Name of the region. type: str wait: description: - Should ansible wait until the requested resource is complete. type: bool default: yes timeout: description: - How long should ansible wait for the requested resource. type: int default: 180 api_timeout: description: - How long should the socket layer wait before timing out for API calls. If this is omitted, nothing will be passed to the requests library. type: int validate_certs: description: - Whether or not SSL API requests should be verified. - Before Ansible 2.3 this defaulted to C(yes). type: bool default: no aliases: [ verify ] ca_cert: description: - A path to a CA Cert bundle that can be used as part of verifying SSL API requests. type: str aliases: [ cacert ] client_cert: description: - A path to a client certificate to use as part of the SSL transaction. type: str aliases: [ cert ] client_key: description: - A path to a client key to use as part of the SSL transaction. type: str aliases: [ key ] interface: description: - Endpoint URL type to fetch from the service catalog. type: str choices: [ admin, internal, public ] default: public aliases: [ endpoint_type ] version_added: "2.3" requirements: - python >= 2.7 - openstacksdk >= 0.12.0 notes: - The standard OpenStack environment variables, such as C(OS_USERNAME) may be used instead of providing explicit values. - Auth information is driven by openstacksdk, which means that values can come from a yaml config file in /etc/ansible/openstack.yaml, /etc/openstack/clouds.yaml or ~/.config/openstack/clouds.yaml, then from standard environment variables, then finally by explicit parameters in plays. More information can be found at U(https://docs.openstack.org/openstacksdk/) '''
thaim/ansible
lib/ansible/plugins/doc_fragments/openstack.py
Python
mit
3,726
# cerbero - a multi-platform build system for Open Source software # Copyright (C) 2012 Andoni Morales Alastruey <ylatuya@gmail.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Library General Public License for more details. # # You should have received a copy of the GNU Library General Public # License along with this library; if not, write to the # Free Software Foundation, Inc., 59 Temple Place - Suite 330, # Boston, MA 02111-1307, USA. import unittest import StringIO from cerbero import hacks from cerbero.build import recipe from cerbero.config import Platform from cerbero.packages import package from cerbero.packages.wix import MergeModule from cerbero.utils import etree from test.test_build_common import create_cookbook from test.test_packages_common import create_store from test.test_common import DummyConfig class Recipe1(recipe.Recipe): name = 'recipe-test' files_misc = ['bin/test.exe', 'bin/test2.exe', 'bin/test3.exe', 'README', 'lib/libfoo.dll', 'lib/gstreamer-0.10/libgstplugins.dll'] class Package(package.Package): name = 'gstreamer-test' shortdesc = 'GStreamer Test' longdesc = 'test' version = '1.0' licences = ['LGPL'] uuid = '1' vendor = 'GStreamer Project' files = ['recipe-test:misc'] MERGE_MODULE = '''\ <?xml version="1.0" ?> <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"> <Module Id="_gstreamer_test" Language="1033" Version="1.0"> <Package Comments="test" Description="GStreamer Test" Id="1" Manufacturer="GStreamer Project"/> <Directory Id="TARGETDIR" Name="SourceDir"> <Component Guid="1" Id="_readme"> <File Id="_readme_1" Name="README" Source="z:\\\\\\test\\\\README"/> </Component> <Directory Id="_bin" Name="bin"> <Component Guid="1" Id="_test.exe"> <File Id="_testexe" Name="test.exe" Source="z:\\\\\\test\\\\bin\\\\test.exe"/> </Component> <Component Guid="1" Id="_test2.exe"> <File Id="_test2exe" Name="test2.exe" Source="z:\\\\\\test\\\\bin\\\\test2.exe"/> </Component> <Component Guid="1" Id="_test3.exe"> <File Id="_test3exe" Name="test3.exe" Source="z:\\\\\\test\\\\bin\\\\test3.exe"/> </Component> </Directory> <Directory Id="_lib" Name="lib"> <Directory Id="_gstreamer_0.10" Name="gstreamer-0.10"> <Component Guid="1" Id="_libgstplugins.dll"> <File Id="_libgstpluginsdll" Name="libgstplugins.dll" Source="z:\\\\\\test\\\\lib\\\\gstreamer-0.10\\\\libgstplugins.dll"/> </Component> </Directory> <Component Guid="1" Id="_libfoo.dll"> <File Id="_libfoodll" Name="libfoo.dll" Source="z:\\\\\\test\\\\lib\\\\libfoo.dll"/> </Component> </Directory> </Directory> </Module> </Wix> ''' class MergeModuleTest(unittest.TestCase): def setUp(self): self.config = DummyConfig() cb = create_cookbook(self.config) store = create_store(self.config) cb.add_recipe(Recipe1(self.config)) self.package = Package(self.config, store, cb) self.mergemodule = MergeModule(self.config, self.package.files_list(), self.package) def test_add_root(self): self.mergemodule._add_root() self.assertEquals( '<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi" />', etree.tostring(self.mergemodule.root)) def test_add_module(self): self.mergemodule._add_root() self.mergemodule._add_module() self.assertEquals( '<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">' '<Module Id="_gstreamer_test" Language="1033" Version="1.0" />' '</Wix>', etree.tostring(self.mergemodule.root)) def test_add_package(self): self.mergemodule._add_root() self.mergemodule._add_module() self.mergemodule._add_package() self.assertEquals( '<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">' '<Module Id="_gstreamer_test" Language="1033" Version="1.0">' '<Package Comments="test" Description="GStreamer Test" Id="1" ' 'Manufacturer="GStreamer Project" />' '</Module>' '</Wix>', etree.tostring(self.mergemodule.root)) def test_add_root_dir(self): self.mergemodule._add_root() self.mergemodule._add_module() self.mergemodule._add_package() self.mergemodule._add_root_dir() self.assertEquals( '<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">' '<Module Id="_gstreamer_test" Language="1033" Version="1.0">' '<Package Comments="test" Description="GStreamer Test" Id="1" ' 'Manufacturer="GStreamer Project" />' '<Directory Id="TARGETDIR" Name="SourceDir" />' '</Module>' '</Wix>', etree.tostring(self.mergemodule.root)) def test_add_directory(self): self.mergemodule._add_root() self.mergemodule._add_module() self.mergemodule._add_package() self.mergemodule._add_root_dir() self.assertEquals(len(self.mergemodule._dirnodes), 1) self.assertEquals(self.mergemodule._dirnodes[''], self.mergemodule.rdir) self.mergemodule._add_directory('lib/gstreamer-0.10') self.assertEquals(len(self.mergemodule._dirnodes), 3) self.assertTrue('lib' in self.mergemodule._dirnodes) self.assertTrue('lib/gstreamer-0.10' in self.mergemodule._dirnodes) self.mergemodule._add_directory('bin') self.assertEquals(len(self.mergemodule._dirnodes), 4) self.assertTrue('bin' in self.mergemodule._dirnodes) def test_add_file(self): self.mergemodule._add_root() self.mergemodule._add_module() self.mergemodule._add_package() self.mergemodule._add_root_dir() self.assertEquals(len(self.mergemodule._dirnodes), 1) self.assertEquals(self.mergemodule._dirnodes[''], self.mergemodule.rdir) self.mergemodule._add_file('bin/gst-inspect-0.10.exe') self.assertEquals(len(self.mergemodule._dirnodes), 2) self.assertTrue('bin' in self.mergemodule._dirnodes) self.assertTrue('gstreamer-0.10.exe' not in self.mergemodule._dirnodes) self.mergemodule._add_file('bin/gst-launch-0.10.exe') self.assertEquals(len(self.mergemodule._dirnodes), 2) self.assertTrue('bin' in self.mergemodule._dirnodes) self.assertTrue('gstreamer-0.10.exe' not in self.mergemodule._dirnodes) def test_render_xml(self): self.config.platform = Platform.WINDOWS self.mergemodule._get_uuid = lambda : '1' self.mergemodule.fill() tmp = StringIO.StringIO() self.mergemodule.write(tmp) #self._compstr(tmp.getvalue(), MERGE_MODULE) self.assertEquals(MERGE_MODULE, tmp.getvalue()) def _compstr(self, str1, str2): str1 = str1.split('\n') str2 = str2.split('\n') for i in range(len(str1)): if str1[i] != str2[i]: print str1[i] print str2[i] print "" class InstallerTest(unittest.TestCase): def setUp(self): pass def testAddRoot(self): pass def testAddProduct(self): pass def testAddPackage(self): pass def testAddInstallDir(self): pass def testAddUIProps(self): pass def testAddMedia(self): pass def testAddMergeModules(self): pass def testAddMergeModules(self): pass def testRender(self): pass
cee1/cerbero-mac
test/test_cerbero_packages_wix.py
Python
lgpl-2.1
8,020
from __future__ import unicode_literals from frappe import _
indautgrp/frappe
frappe/config/tools.py
Python
mit
60
import os import threading import Queue # Windows import import win32file import win32pipe import win32api import win32con import win32security import win32process import win32event class Win32Spawn(object): def __init__(self, cmd, shell=False): self.queue = Queue.Queue() self.is_terminated = False self.wake_up_event = win32event.CreateEvent(None, 0, 0, None) exec_dir = os.getcwd() comspec = os.environ.get("COMSPEC", "cmd.exe") cmd = comspec + ' /c ' + cmd win32event.ResetEvent(self.wake_up_event) currproc = win32api.GetCurrentProcess() sa = win32security.SECURITY_ATTRIBUTES() sa.bInheritHandle = 1 child_stdout_rd, child_stdout_wr = win32pipe.CreatePipe(sa, 0) child_stdout_rd_dup = win32api.DuplicateHandle(currproc, child_stdout_rd, currproc, 0, 0, win32con.DUPLICATE_SAME_ACCESS) win32file.CloseHandle(child_stdout_rd) child_stderr_rd, child_stderr_wr = win32pipe.CreatePipe(sa, 0) child_stderr_rd_dup = win32api.DuplicateHandle(currproc, child_stderr_rd, currproc, 0, 0, win32con.DUPLICATE_SAME_ACCESS) win32file.CloseHandle(child_stderr_rd) child_stdin_rd, child_stdin_wr = win32pipe.CreatePipe(sa, 0) child_stdin_wr_dup = win32api.DuplicateHandle(currproc, child_stdin_wr, currproc, 0, 0, win32con.DUPLICATE_SAME_ACCESS) win32file.CloseHandle(child_stdin_wr) startup_info = win32process.STARTUPINFO() startup_info.hStdInput = child_stdin_rd startup_info.hStdOutput = child_stdout_wr startup_info.hStdError = child_stderr_wr startup_info.dwFlags = win32process.STARTF_USESTDHANDLES cr_flags = 0 cr_flags = win32process.CREATE_NEW_PROCESS_GROUP env = os.environ.copy() self.h_process, h_thread, dw_pid, dw_tid = win32process.CreateProcess(None, cmd, None, None, 1, cr_flags, env, os.path.abspath(exec_dir), startup_info) win32api.CloseHandle(h_thread) win32file.CloseHandle(child_stdin_rd) win32file.CloseHandle(child_stdout_wr) win32file.CloseHandle(child_stderr_wr) self.__child_stdout = child_stdout_rd_dup self.__child_stderr = child_stderr_rd_dup self.__child_stdin = child_stdin_wr_dup self.exit_code = -1 def close(self): win32file.CloseHandle(self.__child_stdout) win32file.CloseHandle(self.__child_stderr) win32file.CloseHandle(self.__child_stdin) win32api.CloseHandle(self.h_process) win32api.CloseHandle(self.wake_up_event) def kill_subprocess(): win32event.SetEvent(self.wake_up_event) def sleep(secs): win32event.ResetEvent(self.wake_up_event) timeout = int(1000 * secs) val = win32event.WaitForSingleObject(self.wake_up_event, timeout) if val == win32event.WAIT_TIMEOUT: return True else: # The wake_up_event must have been signalled return False def get(self, block=True, timeout=None): return self.queue.get(block=block, timeout=timeout) def qsize(self): return self.queue.qsize() def __wait_for_child(self): # kick off threads to read from stdout and stderr of the child process threading.Thread(target=self.__do_read, args=(self.__child_stdout, )).start() threading.Thread(target=self.__do_read, args=(self.__child_stderr, )).start() while True: # block waiting for the process to finish or the interrupt to happen handles = (self.wake_up_event, self.h_process) val = win32event.WaitForMultipleObjects(handles, 0, win32event.INFINITE) if val >= win32event.WAIT_OBJECT_0 and val < win32event.WAIT_OBJECT_0 + len(handles): handle = handles[val - win32event.WAIT_OBJECT_0] if handle == self.wake_up_event: win32api.TerminateProcess(self.h_process, 1) win32event.ResetEvent(self.wake_up_event) return False elif handle == self.h_process: # the process has ended naturally return True else: assert False, "Unknown handle fired" else: assert False, "Unexpected return from WaitForMultipleObjects" # Wait for job to finish. Since this method blocks, it can to be called from another thread. # If the application wants to kill the process, it should call kill_subprocess(). def wait(self): if not self.__wait_for_child(): # it's been killed result = False else: # normal termination self.exit_code = win32process.GetExitCodeProcess(self.h_process) result = self.exit_code == 0 self.close() self.is_terminated = True return result # This method gets called on a worker thread to read from either a stderr # or stdout thread from the child process. def __do_read(self, handle): bytesToRead = 1024 while 1: try: finished = 0 hr, data = win32file.ReadFile(handle, bytesToRead, None) if data: self.queue.put_nowait(data) except win32api.error: finished = 1 if finished: return def start_pipe(self): def worker(pipe): return pipe.wait() thrd = threading.Thread(target=worker, args=(self, )) thrd.start()
wizardxbl/rtt-stm32f10x
tools/win32spawn.py
Python
gpl-2.0
5,808
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # Copyright (C) 2010-2014 OpenERP s.a. (<http://openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## """ Modules dependency graph. """ import os, sys, imp from os.path import join as opj import itertools import zipimport import openerp import openerp.osv as osv import openerp.tools as tools import openerp.tools.osutil as osutil from openerp.tools.safe_eval import safe_eval as eval from openerp.tools.translate import _ import zipfile import openerp.release as release import re import base64 from zipfile import PyZipFile, ZIP_DEFLATED from cStringIO import StringIO import logging _logger = logging.getLogger(__name__) class Graph(dict): """ Modules dependency graph. The graph is a mapping from module name to Nodes. """ def add_node(self, name, info): max_depth, father = 0, None for n in [Node(x, self, None) for x in info['depends']]: if n.depth >= max_depth: father = n max_depth = n.depth if father: return father.add_child(name, info) else: return Node(name, self, info) def update_from_db(self, cr): if not len(self): return # update the graph with values from the database (if exist) ## First, we set the default values for each package in graph additional_data = dict((key, {'id': 0, 'state': 'uninstalled', 'dbdemo': False, 'installed_version': None}) for key in self.keys()) ## Then we get the values from the database cr.execute('SELECT name, id, state, demo AS dbdemo, latest_version AS installed_version' ' FROM ir_module_module' ' WHERE name IN %s',(tuple(additional_data),) ) ## and we update the default values with values from the database additional_data.update((x['name'], x) for x in cr.dictfetchall()) for package in self.values(): for k, v in additional_data[package.name].items(): setattr(package, k, v) def add_module(self, cr, module, force=None): self.add_modules(cr, [module], force) def add_modules(self, cr, module_list, force=None): if force is None: force = [] packages = [] len_graph = len(self) for module in module_list: # This will raise an exception if no/unreadable descriptor file. # NOTE The call to load_information_from_description_file is already # done by db.initialize, so it is possible to not do it again here. info = openerp.modules.module.load_information_from_description_file(module) if info and info['installable']: packages.append((module, info)) # TODO directly a dict, like in get_modules_with_version else: _logger.warning('module %s: not installable, skipped', module) dependencies = dict([(p, info['depends']) for p, info in packages]) current, later = set([p for p, info in packages]), set() while packages and current > later: package, info = packages[0] deps = info['depends'] # if all dependencies of 'package' are already in the graph, add 'package' in the graph if reduce(lambda x, y: x and y in self, deps, True): if not package in current: packages.pop(0) continue later.clear() current.remove(package) node = self.add_node(package, info) node.data = info for kind in ('init', 'demo', 'update'): if package in tools.config[kind] or 'all' in tools.config[kind] or kind in force: setattr(node, kind, True) else: later.add(package) packages.append((package, info)) packages.pop(0) self.update_from_db(cr) for package in later: unmet_deps = filter(lambda p: p not in self, dependencies[package]) _logger.error('module %s: Unmet dependencies: %s', package, ', '.join(unmet_deps)) result = len(self) - len_graph if result != len(module_list): _logger.warning('Some modules were not loaded.') return result def __iter__(self): level = 0 done = set(self.keys()) while done: level_modules = sorted((name, module) for name, module in self.items() if module.depth==level) for name, module in level_modules: done.remove(name) yield module level += 1 class Node(object): """ One module in the modules dependency graph. Node acts as a per-module singleton. A node is constructed via Graph.add_module() or Graph.add_modules(). Some of its fields are from ir_module_module (setted by Graph.update_from_db()). """ def __new__(cls, name, graph, info): if name in graph: inst = graph[name] else: inst = object.__new__(cls) inst.name = name inst.info = info graph[name] = inst return inst def __init__(self, name, graph, info): self.graph = graph if not hasattr(self, 'children'): self.children = [] if not hasattr(self, 'depth'): self.depth = 0 self.info = info or {} def add_child(self, name, info): node = Node(name, self.graph, info) node.depth = self.depth + 1 if node not in self.children: self.children.append(node) for attr in ('init', 'update', 'demo'): if hasattr(self, attr): setattr(node, attr, True) self.children.sort(lambda x, y: cmp(x.name, y.name)) return node def __setattr__(self, name, value): super(Node, self).__setattr__(name, value) if name in ('init', 'update', 'demo'): tools.config[name][self.name] = 1 for child in self.children: setattr(child, name, value) if name == 'depth': for child in self.children: setattr(child, name, value + 1) def __iter__(self): return itertools.chain(iter(self.children), *map(iter, self.children)) def __str__(self): return self._pprint() def _pprint(self, depth=0): s = '%s\n' % self.name for c in self.children: s += '%s`-> %s' % (' ' * depth, c._pprint(depth+1)) return s # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
diogocs1/comps
web/openerp/modules/graph.py
Python
apache-2.0
7,587
#!/usr/bin/env python """Check CFC - Check Compile Flow Consistency This is a compiler wrapper for testing that code generation is consistent with different compilation processes. It checks that code is not unduly affected by compiler options or other changes which should not have side effects. To use: -Ensure that the compiler under test (i.e. clang, clang++) is on the PATH -On Linux copy this script to the name of the compiler e.g. cp check_cfc.py clang && cp check_cfc.py clang++ -On Windows use setup.py to generate check_cfc.exe and copy that to clang.exe and clang++.exe -Enable the desired checks in check_cfc.cfg (in the same directory as the wrapper) e.g. [Checks] dash_g_no_change = true dash_s_no_change = false -The wrapper can be run using its absolute path or added to PATH before the compiler under test e.g. export PATH=<path to check_cfc>:$PATH -Compile as normal. The wrapper intercepts normal -c compiles and will return non-zero if the check fails. e.g. $ clang -c test.cpp Code difference detected with -g --- /tmp/tmp5nv893.o +++ /tmp/tmp6Vwjnc.o @@ -1 +1 @@ - 0: 48 8b 05 51 0b 20 00 mov 0x200b51(%rip),%rax + 0: 48 39 3d 51 0b 20 00 cmp %rdi,0x200b51(%rip) -To run LNT with Check CFC specify the absolute path to the wrapper to the --cc and --cxx options e.g. lnt runtest nt --cc <path to check_cfc>/clang \\ --cxx <path to check_cfc>/clang++ ... To add a new check: -Create a new subclass of WrapperCheck -Implement the perform_check() method. This should perform the alternate compile and do the comparison. -Add the new check to check_cfc.cfg. The check has the same name as the subclass. """ from __future__ import absolute_import, division, print_function import imp import os import platform import shutil import subprocess import sys import tempfile try: import configparser except ImportError: import ConfigParser as configparser import io import obj_diff def is_windows(): """Returns True if running on Windows.""" return platform.system() == 'Windows' class WrapperStepException(Exception): """Exception type to be used when a step other than the original compile fails.""" def __init__(self, msg, stdout, stderr): self.msg = msg self.stdout = stdout self.stderr = stderr class WrapperCheckException(Exception): """Exception type to be used when a comparison check fails.""" def __init__(self, msg): self.msg = msg def main_is_frozen(): """Returns True when running as a py2exe executable.""" return (hasattr(sys, "frozen") or # new py2exe hasattr(sys, "importers") or # old py2exe imp.is_frozen("__main__")) # tools/freeze def get_main_dir(): """Get the directory that the script or executable is located in.""" if main_is_frozen(): return os.path.dirname(sys.executable) return os.path.dirname(sys.argv[0]) def remove_dir_from_path(path_var, directory): """Remove the specified directory from path_var, a string representing PATH""" pathlist = path_var.split(os.pathsep) norm_directory = os.path.normpath(os.path.normcase(directory)) pathlist = [x for x in pathlist if os.path.normpath( os.path.normcase(x)) != norm_directory] return os.pathsep.join(pathlist) def path_without_wrapper(): """Returns the PATH variable modified to remove the path to this program.""" scriptdir = get_main_dir() path = os.environ['PATH'] return remove_dir_from_path(path, scriptdir) def flip_dash_g(args): """Search for -g in args. If it exists then return args without. If not then add it.""" if '-g' in args: # Return args without any -g return [x for x in args if x != '-g'] else: # No -g, add one return args + ['-g'] def derive_output_file(args): """Derive output file from the input file (if just one) or None otherwise.""" infile = get_input_file(args) if infile is None: return None else: return '{}.o'.format(os.path.splitext(infile)[0]) def get_output_file(args): """Return the output file specified by this command or None if not specified.""" grabnext = False for arg in args: if grabnext: return arg if arg == '-o': # Specified as a separate arg grabnext = True elif arg.startswith('-o'): # Specified conjoined with -o return arg[2:] assert grabnext == False return None def is_output_specified(args): """Return true is output file is specified in args.""" return get_output_file(args) is not None def replace_output_file(args, new_name): """Replaces the specified name of an output file with the specified name. Assumes that the output file name is specified in the command line args.""" replaceidx = None attached = False for idx, val in enumerate(args): if val == '-o': replaceidx = idx + 1 attached = False elif val.startswith('-o'): replaceidx = idx attached = True if replaceidx is None: raise Exception replacement = new_name if attached == True: replacement = '-o' + new_name args[replaceidx] = replacement return args def add_output_file(args, output_file): """Append an output file to args, presuming not already specified.""" return args + ['-o', output_file] def set_output_file(args, output_file): """Set the output file within the arguments. Appends or replaces as appropriate.""" if is_output_specified(args): args = replace_output_file(args, output_file) else: args = add_output_file(args, output_file) return args gSrcFileSuffixes = ('.c', '.cpp', '.cxx', '.c++', '.cp', '.cc') def get_input_file(args): """Return the input file string if it can be found (and there is only one).""" inputFiles = list() for arg in args: testarg = arg quotes = ('"', "'") while testarg.endswith(quotes): testarg = testarg[:-1] testarg = os.path.normcase(testarg) # Test if it is a source file if testarg.endswith(gSrcFileSuffixes): inputFiles.append(arg) if len(inputFiles) == 1: return inputFiles[0] else: return None def set_input_file(args, input_file): """Replaces the input file with that specified.""" infile = get_input_file(args) if infile: infile_idx = args.index(infile) args[infile_idx] = input_file return args else: # Could not find input file assert False def is_normal_compile(args): """Check if this is a normal compile which will output an object file rather than a preprocess or link. args is a list of command line arguments.""" compile_step = '-c' in args # Bitcode cannot be disassembled in the same way bitcode = '-flto' in args or '-emit-llvm' in args # Version and help are queries of the compiler and override -c if specified query = '--version' in args or '--help' in args # Options to output dependency files for make dependency = '-M' in args or '-MM' in args # Check if the input is recognised as a source file (this may be too # strong a restriction) input_is_valid = bool(get_input_file(args)) return compile_step and not bitcode and not query and not dependency and input_is_valid def run_step(command, my_env, error_on_failure): """Runs a step of the compilation. Reports failure as exception.""" # Need to use shell=True on Windows as Popen won't use PATH otherwise. p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=my_env, shell=is_windows()) (stdout, stderr) = p.communicate() if p.returncode != 0: raise WrapperStepException(error_on_failure, stdout, stderr) def get_temp_file_name(suffix): """Get a temporary file name with a particular suffix. Let the caller be responsible for deleting it.""" tf = tempfile.NamedTemporaryFile(suffix=suffix, delete=False) tf.close() return tf.name class WrapperCheck(object): """Base class for a check. Subclass this to add a check.""" def __init__(self, output_file_a): """Record the base output file that will be compared against.""" self._output_file_a = output_file_a def perform_check(self, arguments, my_env): """Override this to perform the modified compilation and required checks.""" raise NotImplementedError("Please Implement this method") class dash_g_no_change(WrapperCheck): def perform_check(self, arguments, my_env): """Check if different code is generated with/without the -g flag.""" output_file_b = get_temp_file_name('.o') alternate_command = list(arguments) alternate_command = flip_dash_g(alternate_command) alternate_command = set_output_file(alternate_command, output_file_b) run_step(alternate_command, my_env, "Error compiling with -g") # Compare disassembly (returns first diff if differs) difference = obj_diff.compare_object_files(self._output_file_a, output_file_b) if difference: raise WrapperCheckException( "Code difference detected with -g\n{}".format(difference)) # Clean up temp file if comparison okay os.remove(output_file_b) class dash_s_no_change(WrapperCheck): def perform_check(self, arguments, my_env): """Check if compiling to asm then assembling in separate steps results in different code than compiling to object directly.""" output_file_b = get_temp_file_name('.o') alternate_command = arguments + ['-via-file-asm'] alternate_command = set_output_file(alternate_command, output_file_b) run_step(alternate_command, my_env, "Error compiling with -via-file-asm") # Compare if object files are exactly the same exactly_equal = obj_diff.compare_exact(self._output_file_a, output_file_b) if not exactly_equal: # Compare disassembly (returns first diff if differs) difference = obj_diff.compare_object_files(self._output_file_a, output_file_b) if difference: raise WrapperCheckException( "Code difference detected with -S\n{}".format(difference)) # Code is identical, compare debug info dbgdifference = obj_diff.compare_debug_info(self._output_file_a, output_file_b) if dbgdifference: raise WrapperCheckException( "Debug info difference detected with -S\n{}".format(dbgdifference)) raise WrapperCheckException("Object files not identical with -S\n") # Clean up temp file if comparison okay os.remove(output_file_b) if __name__ == '__main__': # Create configuration defaults from list of checks default_config = """ [Checks] """ # Find all subclasses of WrapperCheck checks = [cls.__name__ for cls in vars()['WrapperCheck'].__subclasses__()] for c in checks: default_config += "{} = false\n".format(c) config = configparser.RawConfigParser() config.readfp(io.BytesIO(default_config)) scriptdir = get_main_dir() config_path = os.path.join(scriptdir, 'check_cfc.cfg') try: config.read(os.path.join(config_path)) except: print("Could not read config from {}, " "using defaults.".format(config_path)) my_env = os.environ.copy() my_env['PATH'] = path_without_wrapper() arguments_a = list(sys.argv) # Prevent infinite loop if called with absolute path. arguments_a[0] = os.path.basename(arguments_a[0]) # Sanity check enabled_checks = [check_name for check_name in checks if config.getboolean('Checks', check_name)] checks_comma_separated = ', '.join(enabled_checks) print("Check CFC, checking: {}".format(checks_comma_separated)) # A - original compilation output_file_orig = get_output_file(arguments_a) if output_file_orig is None: output_file_orig = derive_output_file(arguments_a) p = subprocess.Popen(arguments_a, env=my_env, shell=is_windows()) p.communicate() if p.returncode != 0: sys.exit(p.returncode) if not is_normal_compile(arguments_a) or output_file_orig is None: # Bail out here if we can't apply checks in this case. # Does not indicate an error. # Maybe not straight compilation (e.g. -S or --version or -flto) # or maybe > 1 input files. sys.exit(0) # Sometimes we generate files which have very long names which can't be # read/disassembled. This will exit early if we can't find the file we # expected to be output. if not os.path.isfile(output_file_orig): sys.exit(0) # Copy output file to a temp file temp_output_file_orig = get_temp_file_name('.o') shutil.copyfile(output_file_orig, temp_output_file_orig) # Run checks, if they are enabled in config and if they are appropriate for # this command line. current_module = sys.modules[__name__] for check_name in checks: if config.getboolean('Checks', check_name): class_ = getattr(current_module, check_name) checker = class_(temp_output_file_orig) try: checker.perform_check(arguments_a, my_env) except WrapperCheckException as e: # Check failure print("{} {}".format(get_input_file(arguments_a), e.msg), file=sys.stderr) # Remove file to comply with build system expectations (no # output file if failed) os.remove(output_file_orig) sys.exit(1) except WrapperStepException as e: # Compile step failure print(e.msg, file=sys.stderr) print("*** stdout ***", file=sys.stderr) print(e.stdout, file=sys.stderr) print("*** stderr ***", file=sys.stderr) print(e.stderr, file=sys.stderr) # Remove file to comply with build system expectations (no # output file if failed) os.remove(output_file_orig) sys.exit(1)
apple/swift-clang
utils/check_cfc/check_cfc.py
Python
apache-2.0
14,638
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # # 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. # # Copyright (C) 2013 Association of Universities for Research in Astronomy # (AURA) # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # # 3. The name of AURA and its representatives may not be used to # endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY AURA ``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 AURA BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS from testtools import content from pbr.tests import base class TestCommands(base.BaseTestCase): def test_custom_build_py_command(self): """Test custom build_py command. Test that a custom subclass of the build_py command runs when listed in the commands [global] option, rather than the normal build command. """ stdout, stderr, return_code = self.run_setup('build_py') self.addDetail('stdout', content.text_content(stdout)) self.addDetail('stderr', content.text_content(stderr)) self.assertIn('Running custom build_py command.', stdout) self.assertEqual(0, return_code) def test_custom_deb_version_py_command(self): """Test custom deb_version command.""" stdout, stderr, return_code = self.run_setup('deb_version') self.addDetail('stdout', content.text_content(stdout)) self.addDetail('stderr', content.text_content(stderr)) self.assertIn('Extracting deb version', stdout) self.assertEqual(0, return_code) def test_custom_rpm_version_py_command(self): """Test custom rpm_version command.""" stdout, stderr, return_code = self.run_setup('rpm_version') self.addDetail('stdout', content.text_content(stdout)) self.addDetail('stderr', content.text_content(stderr)) self.assertIn('Extracting rpm version', stdout) self.assertEqual(0, return_code) def test_freeze_command(self): """Test that freeze output is sorted in a case-insensitive manner.""" stdout, stderr, return_code = self.run_pbr('freeze') self.assertEqual(0, return_code) pkgs = [] for l in stdout.split('\n'): pkgs.append(l.split('==')[0].lower()) pkgs_sort = sorted(pkgs[:]) self.assertEqual(pkgs_sort, pkgs)
cvegaj/ElectriCERT
venv3/lib/python3.6/site-packages/pbr/tests/test_commands.py
Python
gpl-3.0
3,688
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.python.threadable}. """ from __future__ import division, absolute_import import sys, pickle try: import threading except ImportError: threadingSkip = "Platform lacks thread support" else: threadingSkip = None from twisted.python.compat import _PY3 from twisted.trial import unittest from twisted.python import threadable class TestObject: synchronized = ['aMethod'] x = -1 y = 1 def aMethod(self): for i in range(10): self.x, self.y = self.y, self.x self.z = self.x + self.y assert self.z == 0, "z == %d, not 0 as expected" % (self.z,) threadable.synchronize(TestObject) class SynchronizationTestCase(unittest.SynchronousTestCase): def setUp(self): """ Reduce the CPython check interval so that thread switches happen much more often, hopefully exercising more possible race conditions. Also, delay actual test startup until the reactor has been started. """ if _PY3: if getattr(sys, 'getswitchinterval', None) is not None: self.addCleanup(sys.setswitchinterval, sys.getswitchinterval()) sys.setswitchinterval(0.0000001) else: if getattr(sys, 'getcheckinterval', None) is not None: self.addCleanup(sys.setcheckinterval, sys.getcheckinterval()) sys.setcheckinterval(7) def test_synchronizedName(self): """ The name of a synchronized method is inaffected by the synchronization decorator. """ self.assertEqual("aMethod", TestObject.aMethod.__name__) def test_isInIOThread(self): """ L{threadable.isInIOThread} returns C{True} if and only if it is called in the same thread as L{threadable.registerAsIOThread}. """ threadable.registerAsIOThread() foreignResult = [] t = threading.Thread( target=lambda: foreignResult.append(threadable.isInIOThread())) t.start() t.join() self.assertFalse( foreignResult[0], "Non-IO thread reported as IO thread") self.assertTrue( threadable.isInIOThread(), "IO thread reported as not IO thread") def testThreadedSynchronization(self): o = TestObject() errors = [] def callMethodLots(): try: for i in range(1000): o.aMethod() except AssertionError as e: errors.append(str(e)) threads = [] for x in range(5): t = threading.Thread(target=callMethodLots) threads.append(t) t.start() for t in threads: t.join() if errors: raise unittest.FailTest(errors) if threadingSkip is not None: testThreadedSynchronization.skip = threadingSkip test_isInIOThread.skip = threadingSkip def testUnthreadedSynchronization(self): o = TestObject() for i in range(1000): o.aMethod() class SerializationTestCase(unittest.SynchronousTestCase): def testPickling(self): lock = threadable.XLock() lockType = type(lock) lockPickle = pickle.dumps(lock) newLock = pickle.loads(lockPickle) self.assertTrue(isinstance(newLock, lockType)) if threadingSkip is not None: testPickling.skip = threadingSkip def testUnpickling(self): lockPickle = b'ctwisted.python.threadable\nunpickle_lock\np0\n(tp1\nRp2\n.' lock = pickle.loads(lockPickle) newPickle = pickle.dumps(lock, 2) newLock = pickle.loads(newPickle)
skycucumber/Messaging-Gateway
webapp/venv/lib/python2.7/site-packages/twisted/test/test_threadable.py
Python
gpl-2.0
3,760
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Presubmit script for Chromium theme resources. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details about the presubmit API built into depot_tools, and see http://www.chromium.org/developers/web-development-style-guide for the rules we're checking against here. """ def CheckChangeOnUpload(input_api, output_api): return _CommonChecks(input_api, output_api) def CheckChangeOnCommit(input_api, output_api): return _CommonChecks(input_api, output_api) def _CommonChecks(input_api, output_api): """Checks common to both upload and commit.""" results = [] resources = input_api.os_path.join(input_api.PresubmitLocalPath(), '../../../ui/resources') # List of paths with their associated scale factor. This is used to verify # that the images modified in one are the correct scale of the other. path_scales = [ [(100, 'default_100_percent/'), (200, 'default_200_percent/')], ] import sys old_path = sys.path try: sys.path = [resources] + old_path from resource_check import resource_scale_factors for paths in path_scales: results.extend(resource_scale_factors.ResourceScaleFactors( input_api, output_api, paths).RunChecks()) finally: sys.path = old_path return results
Chilledheart/chromium
chrome/app/theme/PRESUBMIT.py
Python
bsd-3-clause
1,456
from mkt.collections.models import Collection def run(): """Backfill slugs.""" for c in Collection.objects.all(): c.save()
harikishen/addons-server
src/olympia/migrations/645-collection-backfill-slugs.py
Python
bsd-3-clause
141
# # Copyright 2018 Red Hat Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.plugins.action.network import ActionModule as ActionNetworkModule class ActionModule(ActionNetworkModule): def run(self, tmp=None, task_vars=None): del tmp # tmp no longer has any effect self._config_module = True if self._play_context.connection != 'network_cli': return {'failed': True, 'msg': 'Connection type %s is not valid for cli_config module' % self._play_context.connection} return super(ActionModule, self).run(task_vars=task_vars)
alxgu/ansible
lib/ansible/plugins/action/cli_config.py
Python
gpl-3.0
1,287
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Business Applications # Copyright (c) 2013-TODAY OpenERP S.A. <http://openerp.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.addons.portal_project.tests.test_access_rights import TestPortalProjectBase from openerp.exceptions import AccessError from openerp.osv.orm import except_orm from openerp.tools import mute_logger class TestPortalProjectBase(TestPortalProjectBase): def setUp(self): super(TestPortalProjectBase, self).setUp() cr, uid = self.cr, self.uid # Useful models self.project_issue = self.registry('project.issue') # Various test issues self.issue_1_id = self.project_issue.create(cr, uid, { 'name': 'Test1', 'user_id': False, 'project_id': self.project_pigs_id}, {'mail_create_nolog': True}) self.issue_2_id = self.project_issue.create(cr, uid, { 'name': 'Test2', 'user_id': False, 'project_id': self.project_pigs_id}, {'mail_create_nolog': True}) self.issue_3_id = self.project_issue.create(cr, uid, { 'name': 'Test3', 'user_id': False, 'project_id': self.project_pigs_id}, {'mail_create_nolog': True}) self.issue_4_id = self.project_issue.create(cr, uid, { 'name': 'Test4', 'user_id': self.user_projectuser_id, 'project_id': self.project_pigs_id}, {'mail_create_nolog': True}) self.issue_5_id = self.project_issue.create(cr, uid, { 'name': 'Test5', 'user_id': self.user_portal_id, 'project_id': self.project_pigs_id}, {'mail_create_nolog': True}) self.issue_6_id = self.project_issue.create(cr, uid, { 'name': 'Test6', 'user_id': self.user_public_id, 'project_id': self.project_pigs_id}, {'mail_create_nolog': True}) class TestPortalIssue(TestPortalProjectBase): @mute_logger('openerp.addons.base.ir.ir_model', 'openerp.osv.orm') def test_00_project_access_rights(self): """ Test basic project access rights, for project and portal_project """ cr, uid, pigs_id = self.cr, self.uid, self.project_pigs_id # ---------------------------------------- # CASE1: public project # ---------------------------------------- # Do: Alfred reads project -> ok (employee ok public) # Test: all project issues visible issue_ids = self.project_issue.search(cr, self.user_projectuser_id, [('project_id', '=', pigs_id)]) test_issue_ids = set([self.issue_1_id, self.issue_2_id, self.issue_3_id, self.issue_4_id, self.issue_5_id, self.issue_6_id]) self.assertEqual(set(issue_ids), test_issue_ids, 'access rights: project user cannot see all issues of a public project') # Test: all project issues readable self.project_issue.read(cr, self.user_projectuser_id, issue_ids, ['name']) # Test: all project issues writable self.project_issue.write(cr, self.user_projectuser_id, issue_ids, {'description': 'TestDescription'}) # Do: Bert reads project -> crash, no group # Test: no project issue visible self.assertRaises(AccessError, self.project_issue.search, cr, self.user_none_id, [('project_id', '=', pigs_id)]) # Test: no project issue readable self.assertRaises(AccessError, self.project_issue.read, cr, self.user_none_id, issue_ids, ['name']) # Test: no project issue writable self.assertRaises(AccessError, self.project_issue.write, cr, self.user_none_id, issue_ids, {'description': 'TestDescription'}) # Do: Chell reads project -> ok (portal ok public) # Test: all project issues visible issue_ids = self.project_issue.search(cr, self.user_portal_id, [('project_id', '=', pigs_id)]) self.assertEqual(set(issue_ids), test_issue_ids, 'access rights: project user cannot see all issues of a public project') # Test: all project issues readable self.project_issue.read(cr, self.user_portal_id, issue_ids, ['name']) # Test: no project issue writable self.assertRaises(AccessError, self.project_issue.write, cr, self.user_portal_id, issue_ids, {'description': 'TestDescription'}) # Do: Donovan reads project -> ok (public ok public) # Test: all project issues visible issue_ids = self.project_issue.search(cr, self.user_public_id, [('project_id', '=', pigs_id)]) self.assertEqual(set(issue_ids), test_issue_ids, 'access rights: project user cannot see all issues of a public project') # ---------------------------------------- # CASE2: portal project # ---------------------------------------- self.project_project.write(cr, uid, [pigs_id], {'privacy_visibility': 'portal'}) # Do: Alfred reads project -> ok (employee ok public) # Test: all project issues visible issue_ids = self.project_issue.search(cr, self.user_projectuser_id, [('project_id', '=', pigs_id)]) self.assertEqual(set(issue_ids), test_issue_ids, 'access rights: project user cannot see all issues of a portal project') # Do: Bert reads project -> crash, no group # Test: no project issue searchable self.assertRaises(AccessError, self.project_issue.search, cr, self.user_none_id, [('project_id', '=', pigs_id)]) # Data: issue follower self.project_issue.message_subscribe_users(cr, self.user_projectuser_id, [self.issue_1_id, self.issue_3_id], [self.user_portal_id]) # Do: Chell reads project -> ok (portal ok public) # Test: only followed project issues visible + assigned issue_ids = self.project_issue.search(cr, self.user_portal_id, [('project_id', '=', pigs_id)]) test_issue_ids = set([self.issue_1_id, self.issue_3_id, self.issue_5_id]) self.assertEqual(set(issue_ids), test_issue_ids, 'access rights: portal user should see the followed issues of a portal project') # Data: issue follower cleaning self.project_issue.message_unsubscribe_users(cr, self.user_projectuser_id, [self.issue_1_id, self.issue_3_id], [self.user_portal_id]) # ---------------------------------------- # CASE3: employee project # ---------------------------------------- self.project_project.write(cr, uid, [pigs_id], {'privacy_visibility': 'employees'}) # Do: Alfred reads project -> ok (employee ok employee) # Test: all project issues visible issue_ids = self.project_issue.search(cr, self.user_projectuser_id, [('project_id', '=', pigs_id)]) test_issue_ids = set([self.issue_1_id, self.issue_2_id, self.issue_3_id, self.issue_4_id, self.issue_5_id, self.issue_6_id]) self.assertEqual(set(issue_ids), test_issue_ids, 'access rights: project user cannot see all issues of an employees project') # Do: Chell reads project -> ko (portal ko employee) # Test: no project issue visible + assigned issue_ids = self.project_issue.search(cr, self.user_portal_id, [('project_id', '=', pigs_id)]) self.assertFalse(issue_ids, 'access rights: portal user should not see issues of an employees project, even if assigned') # ---------------------------------------- # CASE4: followers project # ---------------------------------------- self.project_project.write(cr, uid, [pigs_id], {'privacy_visibility': 'followers'}) # Do: Alfred reads project -> ko (employee ko followers) # Test: no project issue visible issue_ids = self.project_issue.search(cr, self.user_projectuser_id, [('project_id', '=', pigs_id)]) test_issue_ids = set([self.issue_4_id]) self.assertEqual(set(issue_ids), test_issue_ids, 'access rights: employee user should not see issues of a not-followed followers project, only assigned') # Do: Chell reads project -> ko (portal ko employee) # Test: no project issue visible issue_ids = self.project_issue.search(cr, self.user_portal_id, [('project_id', '=', pigs_id)]) test_issue_ids = set([self.issue_5_id]) self.assertEqual(set(issue_ids), test_issue_ids, 'access rights: portal user should not see issues of a not-followed followers project, only assigned') # Data: subscribe Alfred, Chell and Donovan as follower self.project_project.message_subscribe_users(cr, uid, [pigs_id], [self.user_projectuser_id, self.user_portal_id, self.user_public_id]) self.project_issue.message_subscribe_users(cr, self.user_manager_id, [self.issue_1_id, self.issue_3_id], [self.user_portal_id, self.user_projectuser_id]) # Do: Alfred reads project -> ok (follower ok followers) # Test: followed + assigned issues visible issue_ids = self.project_issue.search(cr, self.user_projectuser_id, [('project_id', '=', pigs_id)]) test_issue_ids = set([self.issue_1_id, self.issue_3_id, self.issue_4_id]) self.assertEqual(set(issue_ids), test_issue_ids, 'access rights: employee user should not see followed + assigned issues of a follower project') # Do: Chell reads project -> ok (follower ok follower) # Test: followed + assigned issues visible issue_ids = self.project_issue.search(cr, self.user_portal_id, [('project_id', '=', pigs_id)]) test_issue_ids = set([self.issue_1_id, self.issue_3_id, self.issue_5_id]) self.assertEqual(set(issue_ids), test_issue_ids, 'access rights: employee user should not see followed + assigned issues of a follower project')
poiesisconsulting/openerp-restaurant
portal_project_issue/tests/test_access_rights.py
Python
agpl-3.0
10,548
"""Tests for distutils.msvc9compiler.""" import sys import unittest import os from distutils.errors import DistutilsPlatformError from distutils.tests import support from test.support import run_unittest _MANIFEST = """\ <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> <security> <requestedPrivileges> <requestedExecutionLevel level="asInvoker" uiAccess="false"> </requestedExecutionLevel> </requestedPrivileges> </security> </trustInfo> <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="Microsoft.VC90.CRT" version="9.0.21022.8" processorArchitecture="x86" publicKeyToken="XXXX"> </assemblyIdentity> </dependentAssembly> </dependency> <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="Microsoft.VC90.MFC" version="9.0.21022.8" processorArchitecture="x86" publicKeyToken="XXXX"></assemblyIdentity> </dependentAssembly> </dependency> </assembly> """ _CLEANED_MANIFEST = """\ <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> <security> <requestedPrivileges> <requestedExecutionLevel level="asInvoker" uiAccess="false"> </requestedExecutionLevel> </requestedPrivileges> </security> </trustInfo> <dependency> </dependency> <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="Microsoft.VC90.MFC" version="9.0.21022.8" processorArchitecture="x86" publicKeyToken="XXXX"></assemblyIdentity> </dependentAssembly> </dependency> </assembly>""" if sys.platform=="win32": from distutils.msvccompiler import get_build_version if get_build_version()>=8.0: SKIP_MESSAGE = None else: SKIP_MESSAGE = "These tests are only for MSVC8.0 or above" else: SKIP_MESSAGE = "These tests are only for win32" @unittest.skipUnless(SKIP_MESSAGE is None, SKIP_MESSAGE) class msvc9compilerTestCase(support.TempdirManager, unittest.TestCase): def test_no_compiler(self): # makes sure query_vcvarsall throws # a DistutilsPlatformError if the compiler # is not found from distutils.msvc9compiler import query_vcvarsall def _find_vcvarsall(version): return None from distutils import msvc9compiler old_find_vcvarsall = msvc9compiler.find_vcvarsall msvc9compiler.find_vcvarsall = _find_vcvarsall try: self.assertRaises(DistutilsPlatformError, query_vcvarsall, 'wont find this version') finally: msvc9compiler.find_vcvarsall = old_find_vcvarsall def test_reg_class(self): from distutils.msvc9compiler import Reg self.assertRaises(KeyError, Reg.get_value, 'xxx', 'xxx') # looking for values that should exist on all # windows registeries versions. path = r'Control Panel\Desktop' v = Reg.get_value(path, 'dragfullwindows') self.assertTrue(v in ('0', '1', '2')) import winreg HKCU = winreg.HKEY_CURRENT_USER keys = Reg.read_keys(HKCU, 'xxxx') self.assertEqual(keys, None) keys = Reg.read_keys(HKCU, r'Control Panel') self.assertTrue('Desktop' in keys) def test_remove_visual_c_ref(self): from distutils.msvc9compiler import MSVCCompiler tempdir = self.mkdtemp() manifest = os.path.join(tempdir, 'manifest') f = open(manifest, 'w') try: f.write(_MANIFEST) finally: f.close() compiler = MSVCCompiler() compiler._remove_visual_c_ref(manifest) # see what we got f = open(manifest) try: # removing trailing spaces content = '\n'.join([line.rstrip() for line in f.readlines()]) finally: f.close() # makes sure the manifest was properly cleaned self.assertEqual(content, _CLEANED_MANIFEST) def test_suite(): return unittest.makeSuite(msvc9compilerTestCase) if __name__ == "__main__": run_unittest(test_suite())
invisiblek/python-for-android
python3-alpha/python3-src/Lib/distutils/tests/test_msvc9compiler.py
Python
apache-2.0
4,424
#!/usr/bin/env python # -*- coding: utf-8 -*- """Compiler for keymap.c files This scrip will generate a keymap.c file from a simple markdown file with a specific layout. Usage: python compile_keymap.py INPUT_PATH [OUTPUT_PATH] """ from __future__ import division from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals import os import io import re import sys import json import unicodedata import collections import itertools as it PY2 = sys.version_info.major == 2 if PY2: chr = unichr KEYBOARD_LAYOUTS = { # These map positions in the parsed layout to # positions in the LAYOUT_ergodox MATRIX 'ergodox_ez': [ [ 0, 1, 2, 3, 4, 5, 6], [38, 39, 40, 41, 42, 43, 44], [ 7, 8, 9, 10, 11, 12, 13], [45, 46, 47, 48, 49, 50, 51], [14, 15, 16, 17, 18, 19 ], [ 52, 53, 54, 55, 56, 57], [20, 21, 22, 23, 24, 25, 26], [58, 59, 60, 61, 62, 63, 64], [27, 28, 29, 30, 31 ], [ 65, 66, 67, 68, 69], [ 32, 33], [70, 71 ], [ 34], [72 ], [ 35, 36, 37], [73, 74, 75 ], ] } ROW_INDENTS = { 'ergodox_ez': [0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 5, 0, 6, 0, 4, 0] } BLANK_LAYOUTS = [ # Compact Layout """ .------------------------------------.------------------------------------. | | | | | | | | | | | | | | | !-----+----+----+----+----+----------!-----+----+----+----+----+----+-----! | | | | | | | | | | | | | | | !-----+----+----+----x----x----! ! !----x----x----+----+----+-----! | | | | | | |-----!-----! | | | | | | !-----+----+----+----x----x----! ! !----x----x----+----+----+-----! | | | | | | | | | | | | | | | '-----+----+----+----+----+----------'----------+----+----+----+----+-----' | | | | | | ! | | | | | '------------------------' '------------------------' .-----------. .-----------. | | | ! | | .-----+-----+-----! !-----+-----+-----. ! ! | | ! | ! ! ! ! !-----! !-----! ! ! | | | | ! | | | '-----------------' '-----------------' """, # Wide Layout """ .---------------------------------------------. .---------------------------------------------. | | | | | | | | ! | | | | | | | !-------+-----+-----+-----+-----+-------------! !-------+-----+-----+-----+-----+-----+-------! | | | | | | | | ! | | | | | | | !-------+-----+-----+-----x-----x-----! ! ! !-----x-----x-----+-----+-----+-------! | | | | | | |-------! !-------! | | | | | | !-------+-----+-----+-----x-----x-----! ! ! !-----x-----x-----+-----+-----+-------! | | | | | | | | ! | | | | | | | '-------+-----+-----+-----+-----+-------------' '-------------+-----+-----+-----+-----+-------' | | | | | | ! | | | | | '------------------------------' '------------------------------' .---------------. .---------------. | | | ! | | .-------+-------+-------! !-------+-------+-------. ! ! | | ! | ! ! ! ! !-------! !-------! ! ! | | | | ! | | | '-----------------------' '-----------------------' """, ] DEFAULT_CONFIG = { "keymaps_includes": [ "keymap_common.h", ], 'filler': "-+.'!:x", 'separator': "|", 'default_key_prefix': ["KC_"], } SECTIONS = [ 'layout_config', 'layers', ] # Markdown Parsing ONELINE_COMMENT_RE = re.compile(r""" ^ # comment must be at the start of the line \s* # arbitrary whitespace // # start of the comment (.*) # the comment $ # until the end of line """, re.MULTILINE | re.VERBOSE ) INLINE_COMMENT_RE = re.compile(r""" ([\,\"\[\]\{\}\d]) # anythig that might end a expression \s+ # comment must be preceded by whitespace // # start of the comment \s # and succeded by whitespace (?:[^\"\]\}\{\[]*) # the comment (except things which might be json) $ # until the end of line """, re.MULTILINE | re.VERBOSE) TRAILING_COMMA_RE = re.compile(r""" , # the comma (?:\s*) # arbitrary whitespace $ # only works if the trailing comma is followed by newline (\s*) # arbitrary whitespace ([\]\}]) # end of an array or object """, re.MULTILINE | re.VERBOSE) def loads(raw_data): if isinstance(raw_data, bytes): raw_data = raw_data.decode('utf-8') raw_data = ONELINE_COMMENT_RE.sub(r"", raw_data) raw_data = INLINE_COMMENT_RE.sub(r"\1", raw_data) raw_data = TRAILING_COMMA_RE.sub(r"\1\2", raw_data) return json.loads(raw_data) def parse_config(path): def reset_section(): section.update({ 'name': section.get('name', ""), 'sub_name': "", 'start_line': -1, 'end_line': -1, 'code_lines': [], }) def start_section(line_index, line): end_section() if line.startswith("# "): name = line[2:] elif line.startswith("## "): name = line[3:] else: name = "" name = name.strip().replace(" ", "_").lower() if name in SECTIONS: section['name'] = name else: section['sub_name'] = name section['start_line'] = line_index def end_section(): if section['start_line'] >= 0: if section['name'] == 'layout_config': config.update(loads("\n".join( section['code_lines'] ))) elif section['sub_name'].startswith('layer'): layer_name = section['sub_name'] config['layer_lines'][layer_name] = section['code_lines'] reset_section() def amend_section(line_index, line): section['end_line'] = line_index section['code_lines'].append(line) config = DEFAULT_CONFIG.copy() config.update({ 'layer_lines': collections.OrderedDict(), 'macro_ids': {'UM'}, 'unicode_macros': {}, }) section = {} reset_section() with io.open(path, encoding="utf-8") as fh: for i, line in enumerate(fh): if line.startswith("#"): start_section(i, line) elif line.startswith(" "): amend_section(i, line[4:]) else: # TODO: maybe parse description pass end_section() assert 'layout' in config return config # header file parsing IF0_RE = re.compile(r""" ^ #if 0 $.*? #endif """, re.MULTILINE | re.DOTALL | re.VERBOSE) COMMENT_RE = re.compile(r""" /\* .*? \*/" """, re.MULTILINE | re.DOTALL | re.VERBOSE) def read_header_file(path): with io.open(path, encoding="utf-8") as fh: data = fh.read() data, _ = COMMENT_RE.subn("", data) data, _ = IF0_RE.subn("", data) return data def regex_partial(re_str_fmt, flags): def partial(*args, **kwargs): re_str = re_str_fmt.format(*args, **kwargs) return re.compile(re_str, flags) return partial KEYDEF_REP = regex_partial(r""" #define \s ( (?:{}) # the prefixes (?:\w+) # the key name ) # capture group end """, re.MULTILINE | re.DOTALL | re.VERBOSE) ENUM_RE = re.compile(r""" ( enum \s\w+\s \{ .*? # the enum content \} ; ) # capture group end """, re.MULTILINE | re.DOTALL | re.VERBOSE) ENUM_KEY_REP = regex_partial(r""" ( {} # the prefixes \w+ # the key name ) # capture group end """, re.MULTILINE | re.DOTALL | re.VERBOSE) def parse_keydefs(config, data): prefix_options = "|".join(config['key_prefixes']) keydef_re = KEYDEF_REP(prefix_options) enum_key_re = ENUM_KEY_REP(prefix_options) for match in keydef_re.finditer(data): yield match.groups()[0] for enum_match in ENUM_RE.finditer(data): enum = enum_match.groups()[0] for key_match in enum_key_re.finditer(enum): yield key_match.groups()[0] def parse_valid_keys(config, out_path): basepath = os.path.abspath(os.path.join(os.path.dirname(out_path))) dirpaths = [] subpaths = [] while len(subpaths) < 6: path = os.path.join(basepath, *subpaths) dirpaths.append(path) dirpaths.append(os.path.join(path, "tmk_core", "common")) dirpaths.append(os.path.join(path, "quantum")) subpaths.append('..') includes = set(config['keymaps_includes']) includes.add("keycode.h") valid_keycodes = set() for dirpath, include in it.product(dirpaths, includes): include_path = os.path.join(dirpath, include) if os.path.exists(include_path): header_data = read_header_file(include_path) valid_keycodes.update( parse_keydefs(config, header_data) ) return valid_keycodes # Keymap Parsing def iter_raw_codes(layer_lines, filler, separator): filler_re = re.compile("[" + filler + " ]") for line in layer_lines: line, _ = filler_re.subn("", line.strip()) if not line: continue codes = line.split(separator) for code in codes[1:-1]: yield code def iter_indexed_codes(raw_codes, key_indexes): key_rows = {} key_indexes_flat = [] for row_index, key_indexes in enumerate(key_indexes): for key_index in key_indexes: key_rows[key_index] = row_index key_indexes_flat.extend(key_indexes) assert len(raw_codes) == len(key_indexes_flat) for raw_code, key_index in zip(raw_codes, key_indexes_flat): # we keep track of the row mostly for layout purposes yield raw_code, key_index, key_rows[key_index] LAYER_CHANGE_RE = re.compile(r""" (DF|TG|MO)\(\d+\) """, re.VERBOSE) MACRO_RE = re.compile(r""" M\(\w+\) """, re.VERBOSE) UNICODE_RE = re.compile(r""" U[0-9A-F]{4} """, re.VERBOSE) NON_CODE = re.compile(r""" ^[^A-Z0-9_]$ """, re.VERBOSE) def parse_uni_code(raw_code): macro_id = "UC_" + ( unicodedata.name(raw_code) .replace(" ", "_") .replace("-", "_") ) code = "M({})".format(macro_id) uc_hex = "{:04X}".format(ord(raw_code)) return code, macro_id, uc_hex def parse_key_code(raw_code, key_prefixes, valid_keycodes): if raw_code in valid_keycodes: return raw_code for prefix in key_prefixes: code = prefix + raw_code if code in valid_keycodes: return code def parse_code(raw_code, key_prefixes, valid_keycodes): if not raw_code: return 'KC_TRNS', None, None if LAYER_CHANGE_RE.match(raw_code): return raw_code, None, None if MACRO_RE.match(raw_code): macro_id = raw_code[2:-1] return raw_code, macro_id, None if UNICODE_RE.match(raw_code): hex_code = raw_code[1:] return parse_uni_code(chr(int(hex_code, 16))) if NON_CODE.match(raw_code): return parse_uni_code(raw_code) code = parse_key_code(raw_code, key_prefixes, valid_keycodes) return code, None, None def parse_keymap(config, key_indexes, layer_lines, valid_keycodes): keymap = {} raw_codes = list(iter_raw_codes( layer_lines, config['filler'], config['separator'] )) indexed_codes = iter_indexed_codes(raw_codes, key_indexes) key_prefixes = config['key_prefixes'] for raw_code, key_index, row_index in indexed_codes: code, macro_id, uc_hex = parse_code( raw_code, key_prefixes, valid_keycodes ) # TODO: line numbers for invalid codes err_msg = "Could not parse key '{}' on row {}".format( raw_code, row_index ) assert code is not None, err_msg # print(repr(raw_code), repr(code), macro_id, uc_hex) if macro_id: config['macro_ids'].add(macro_id) if uc_hex: config['unicode_macros'][macro_id] = uc_hex keymap[key_index] = (code, row_index) return keymap def parse_keymaps(config, valid_keycodes): keymaps = collections.OrderedDict() key_indexes = config.get( 'key_indexes', KEYBOARD_LAYOUTS[config['layout']] ) # TODO: maybe validate key_indexes for layer_name, layer_lines, in config['layer_lines'].items(): keymaps[layer_name] = parse_keymap( config, key_indexes, layer_lines, valid_keycodes ) return keymaps # keymap.c output USERCODE = """ // Runs just one time when the keyboard initializes. void matrix_init_user(void) { }; // Runs constantly in the background, in a loop. void matrix_scan_user(void) { uint8_t layer = biton32(layer_state); ergodox_board_led_off(); ergodox_right_led_1_off(); ergodox_right_led_2_off(); ergodox_right_led_3_off(); switch (layer) { case L1: ergodox_right_led_1_on(); break; case L2: ergodox_right_led_2_on(); break; case L3: ergodox_right_led_3_on(); break; case L4: ergodox_right_led_1_on(); ergodox_right_led_2_on(); break; case L5: ergodox_right_led_1_on(); ergodox_right_led_3_on(); break; // case L6: // ergodox_right_led_2_on(); // ergodox_right_led_3_on(); // break; // case L7: // ergodox_right_led_1_on(); // ergodox_right_led_2_on(); // ergodox_right_led_3_on(); // break; default: ergodox_board_led_off(); break; } }; """ MACROCODE = """ #define UC_MODE_WIN 0 #define UC_MODE_LINUX 1 #define UC_MODE_OSX 2 // TODO: allow default mode to be configured static uint16_t unicode_mode = UC_MODE_WIN; uint16_t hextokeycode(uint8_t hex) {{ if (hex == 0x0) {{ return KC_P0; }} if (hex < 0xA) {{ return KC_P1 + (hex - 0x1); }} return KC_A + (hex - 0xA); }} void unicode_action_function(uint16_t hi, uint16_t lo) {{ switch (unicode_mode) {{ case UC_MODE_WIN: register_code(KC_LALT); register_code(KC_PPLS); unregister_code(KC_PPLS); register_code(hextokeycode((hi & 0xF0) >> 4)); unregister_code(hextokeycode((hi & 0xF0) >> 4)); register_code(hextokeycode((hi & 0x0F))); unregister_code(hextokeycode((hi & 0x0F))); register_code(hextokeycode((lo & 0xF0) >> 4)); unregister_code(hextokeycode((lo & 0xF0) >> 4)); register_code(hextokeycode((lo & 0x0F))); unregister_code(hextokeycode((lo & 0x0F))); unregister_code(KC_LALT); break; case UC_MODE_LINUX: register_code(KC_LCTL); register_code(KC_LSFT); register_code(KC_U); unregister_code(KC_U); register_code(hextokeycode((hi & 0xF0) >> 4)); unregister_code(hextokeycode((hi & 0xF0) >> 4)); register_code(hextokeycode((hi & 0x0F))); unregister_code(hextokeycode((hi & 0x0F))); register_code(hextokeycode((lo & 0xF0) >> 4)); unregister_code(hextokeycode((lo & 0xF0) >> 4)); register_code(hextokeycode((lo & 0x0F))); unregister_code(hextokeycode((lo & 0x0F))); unregister_code(KC_LCTL); unregister_code(KC_LSFT); break; case UC_MODE_OSX: break; }} }} const macro_t *action_get_macro(keyrecord_t *record, uint8_t id, uint8_t opt) {{ if (!record->event.pressed) {{ return MACRO_NONE; }} // MACRODOWN only works in this function switch(id) {{ case UM: unicode_mode = (unicode_mode + 1) % 2; break; {macro_cases} {unicode_macro_cases} default: break; }} return MACRO_NONE; }}; """ UNICODE_MACRO_TEMPLATE = """ case {macro_id}: unicode_action_function(0x{hi:02x}, 0x{lo:02x}); break; """.strip() def unicode_macro_cases(config): for macro_id, uc_hex in config['unicode_macros'].items(): hi = int(uc_hex, 16) >> 8 lo = int(uc_hex, 16) & 0xFF unimacro_keys = ", ".join( "T({})".format( "KP_" + digit if digit.isdigit() else digit ) for digit in uc_hex ) yield UNICODE_MACRO_TEMPLATE.format( macro_id=macro_id, hi=hi, lo=lo ) def iter_keymap_lines(keymap, row_indents=None): col_widths = {} col = 0 # first pass, figure out the column widths prev_row_index = None for code, row_index in keymap.values(): if row_index != prev_row_index: col = 0 if row_indents: col = row_indents[row_index] col_widths[col] = max(len(code), col_widths.get(col, 0)) prev_row_index = row_index col += 1 # second pass, yield the cell values col = 0 prev_row_index = None for key_index in sorted(keymap): code, row_index = keymap[key_index] if row_index != prev_row_index: col = 0 yield "\n" if row_indents: for indent_col in range(row_indents[row_index]): pad = " " * (col_widths[indent_col] - 4) yield (" /*-*/" + pad) col = row_indents[row_index] else: yield pad yield " {}".format(code) if key_index < len(keymap) - 1: yield "," # This will be yielded on the next iteration when # we know that we're not at the end of a line. pad = " " * (col_widths[col] - len(code)) prev_row_index = row_index col += 1 def iter_keymap_parts(config, keymaps): # includes for include_path in config['keymaps_includes']: yield '#include "{}"\n'.format(include_path) yield "\n" # definitions for i, macro_id in enumerate(sorted(config['macro_ids'])): yield "#define {} {}\n".format(macro_id, i) yield "\n" for i, layer_name in enumerate(config['layer_lines']): yield '#define L{0:<3} {0:<5} // {1}\n'.format(i, layer_name) yield "\n" # keymaps yield "const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = {\n" for i, layer_name in enumerate(config['layer_lines']): # comment layer_lines = config['layer_lines'][layer_name] prefixed_lines = " * " + " * ".join(layer_lines) yield "/*\n{} */\n".format(prefixed_lines) # keymap codes keymap = keymaps[layer_name] row_indents = ROW_INDENTS.get(config['layout']) keymap_lines = "".join(iter_keymap_lines(keymap, row_indents)) yield "[L{0}] = LAYOUT_ergodox({1}\n),\n".format(i, keymap_lines) yield "};\n\n" # macros yield MACROCODE.format( macro_cases="", unicode_macro_cases="\n".join(unicode_macro_cases(config)), ) # TODO: dynamically create blinking lights yield USERCODE def main(argv=sys.argv[1:]): if not argv or '-h' in argv or '--help' in argv: print(__doc__) return 0 in_path = os.path.abspath(argv[0]) if not os.path.exists(in_path): print("No such file '{}'".format(in_path)) return 1 if len(argv) > 1: out_path = os.path.abspath(argv[1]) else: dirname = os.path.dirname(in_path) out_path = os.path.join(dirname, "keymap.c") config = parse_config(in_path) valid_keys = parse_valid_keys(config, out_path) keymaps = parse_keymaps(config, valid_keys) with io.open(out_path, mode="w", encoding="utf-8") as fh: for part in iter_keymap_parts(config, keymaps): fh.write(part) if __name__ == '__main__': sys.exit(main())
paxy97/qmk_firmware
layouts/community/ergodox/german-manuneo/compile_keymap.py
Python
gpl-2.0
21,163
# -*- encoding: utf-8 -*- """ Tests for django.core.servers. """ from __future__ import unicode_literals import os import socket from django.core.exceptions import ImproperlyConfigured from django.test import LiveServerTestCase from django.test.utils import override_settings from django.utils.http import urlencode from django.utils.six.moves.urllib.error import HTTPError from django.utils.six.moves.urllib.request import urlopen from django.utils._os import upath from .models import Person TEST_ROOT = os.path.dirname(upath(__file__)) TEST_SETTINGS = { 'MEDIA_URL': '/media/', 'MEDIA_ROOT': os.path.join(TEST_ROOT, 'media'), 'STATIC_URL': '/static/', 'STATIC_ROOT': os.path.join(TEST_ROOT, 'static'), } class LiveServerBase(LiveServerTestCase): available_apps = [ 'servers', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', ] fixtures = ['testdata.json'] urls = 'servers.urls' @classmethod def setUpClass(cls): # Override settings cls.settings_override = override_settings(**TEST_SETTINGS) cls.settings_override.enable() super(LiveServerBase, cls).setUpClass() @classmethod def tearDownClass(cls): # Restore original settings cls.settings_override.disable() super(LiveServerBase, cls).tearDownClass() def urlopen(self, url): return urlopen(self.live_server_url + url) class LiveServerAddress(LiveServerBase): """ Ensure that the address set in the environment variable is valid. Refs #2879. """ @classmethod def setUpClass(cls): # Backup original environment variable address_predefined = 'DJANGO_LIVE_TEST_SERVER_ADDRESS' in os.environ old_address = os.environ.get('DJANGO_LIVE_TEST_SERVER_ADDRESS') # Just the host is not accepted cls.raises_exception('localhost', ImproperlyConfigured) # The host must be valid cls.raises_exception('blahblahblah:8081', socket.error) # The list of ports must be in a valid format cls.raises_exception('localhost:8081,', ImproperlyConfigured) cls.raises_exception('localhost:8081,blah', ImproperlyConfigured) cls.raises_exception('localhost:8081-', ImproperlyConfigured) cls.raises_exception('localhost:8081-blah', ImproperlyConfigured) cls.raises_exception('localhost:8081-8082-8083', ImproperlyConfigured) # If contrib.staticfiles isn't configured properly, the exception # should bubble up to the main thread. old_STATIC_URL = TEST_SETTINGS['STATIC_URL'] TEST_SETTINGS['STATIC_URL'] = None cls.raises_exception('localhost:8081', ImproperlyConfigured) TEST_SETTINGS['STATIC_URL'] = old_STATIC_URL # Restore original environment variable if address_predefined: os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = old_address else: del os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] @classmethod def tearDownClass(cls): # skip it, as setUpClass doesn't call its parent either pass @classmethod def raises_exception(cls, address, exception): os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = address try: super(LiveServerAddress, cls).setUpClass() raise Exception("The line above should have raised an exception") except exception: pass finally: super(LiveServerAddress, cls).tearDownClass() def test_test_test(self): # Intentionally empty method so that the test is picked up by the # test runner and the overriden setUpClass() method is executed. pass class LiveServerViews(LiveServerBase): def test_404(self): """ Ensure that the LiveServerTestCase serves 404s. Refs #2879. """ try: self.urlopen('/') except HTTPError as err: self.assertEqual(err.code, 404, 'Expected 404 response') else: self.fail('Expected 404 response') def test_view(self): """ Ensure that the LiveServerTestCase serves views. Refs #2879. """ f = self.urlopen('/example_view/') self.assertEqual(f.read(), b'example view') def test_static_files(self): """ Ensure that the LiveServerTestCase serves static files. Refs #2879. """ f = self.urlopen('/static/example_static_file.txt') self.assertEqual(f.read().rstrip(b'\r\n'), b'example static file') def test_media_files(self): """ Ensure that the LiveServerTestCase serves media files. Refs #2879. """ f = self.urlopen('/media/example_media_file.txt') self.assertEqual(f.read().rstrip(b'\r\n'), b'example media file') def test_environ(self): f = self.urlopen('/environ_view/?%s' % urlencode({'q': 'тест'})) self.assertIn(b"QUERY_STRING: 'q=%D1%82%D0%B5%D1%81%D1%82'", f.read()) class LiveServerDatabase(LiveServerBase): def test_fixtures_loaded(self): """ Ensure that fixtures are properly loaded and visible to the live server thread. Refs #2879. """ f = self.urlopen('/model_view/') self.assertEqual(f.read().splitlines(), [b'jane', b'robert']) def test_database_writes(self): """ Ensure that data written to the database by a view can be read. Refs #2879. """ self.urlopen('/create_model_instance/') self.assertQuerysetEqual( Person.objects.all().order_by('pk'), ['jane', 'robert', 'emily'], lambda b: b.name )
atruberg/django-custom
tests/servers/tests.py
Python
bsd-3-clause
5,773
"""AutoComplete.py - An IDLE extension for automatically completing names. This extension can complete either attribute names of file names. It can pop a window with all available names, for the user to select from. """ import os import sys import string from configHandler import idleConf import AutoCompleteWindow from HyperParser import HyperParser import __main__ # This string includes all chars that may be in a file name (without a path # separator) FILENAME_CHARS = string.ascii_letters + string.digits + os.curdir + "._~#$:-" # This string includes all chars that may be in an identifier ID_CHARS = string.ascii_letters + string.digits + "_" # These constants represent the two different types of completions COMPLETE_ATTRIBUTES, COMPLETE_FILES = range(1, 2+1) SEPS = os.sep if os.altsep: # e.g. '/' on Windows... SEPS += os.altsep class AutoComplete: menudefs = [ ('edit', [ ("Show Completions", "<<force-open-completions>>"), ]) ] popupwait = idleConf.GetOption("extensions", "AutoComplete", "popupwait", type="int", default=0) def __init__(self, editwin=None): self.editwin = editwin if editwin is None: # subprocess and test return self.text = editwin.text self.autocompletewindow = None # id of delayed call, and the index of the text insert when the delayed # call was issued. If _delayed_completion_id is None, there is no # delayed call. self._delayed_completion_id = None self._delayed_completion_index = None def _make_autocomplete_window(self): return AutoCompleteWindow.AutoCompleteWindow(self.text) def _remove_autocomplete_window(self, event=None): if self.autocompletewindow: self.autocompletewindow.hide_window() self.autocompletewindow = None def force_open_completions_event(self, event): """Happens when the user really wants to open a completion list, even if a function call is needed. """ self.open_completions(True, False, True) def try_open_completions_event(self, event): """Happens when it would be nice to open a completion list, but not really neccesary, for example after an dot, so function calls won't be made. """ lastchar = self.text.get("insert-1c") if lastchar == ".": self._open_completions_later(False, False, False, COMPLETE_ATTRIBUTES) elif lastchar in SEPS: self._open_completions_later(False, False, False, COMPLETE_FILES) def autocomplete_event(self, event): """Happens when the user wants to complete his word, and if neccesary, open a completion list after that (if there is more than one completion) """ if hasattr(event, "mc_state") and event.mc_state: # A modifier was pressed along with the tab, continue as usual. return if self.autocompletewindow and self.autocompletewindow.is_active(): self.autocompletewindow.complete() return "break" else: opened = self.open_completions(False, True, True) if opened: return "break" def _open_completions_later(self, *args): self._delayed_completion_index = self.text.index("insert") if self._delayed_completion_id is not None: self.text.after_cancel(self._delayed_completion_id) self._delayed_completion_id = \ self.text.after(self.popupwait, self._delayed_open_completions, *args) def _delayed_open_completions(self, *args): self._delayed_completion_id = None if self.text.index("insert") != self._delayed_completion_index: return self.open_completions(*args) def open_completions(self, evalfuncs, complete, userWantsWin, mode=None): """Find the completions and create the AutoCompleteWindow. Return True if successful (no syntax error or so found). if complete is True, then if there's nothing to complete and no start of completion, won't open completions and return False. If mode is given, will open a completion list only in this mode. """ # Cancel another delayed call, if it exists. if self._delayed_completion_id is not None: self.text.after_cancel(self._delayed_completion_id) self._delayed_completion_id = None hp = HyperParser(self.editwin, "insert") curline = self.text.get("insert linestart", "insert") i = j = len(curline) if hp.is_in_string() and (not mode or mode==COMPLETE_FILES): self._remove_autocomplete_window() mode = COMPLETE_FILES while i and curline[i-1] in FILENAME_CHARS: i -= 1 comp_start = curline[i:j] j = i while i and curline[i-1] in FILENAME_CHARS + SEPS: i -= 1 comp_what = curline[i:j] elif hp.is_in_code() and (not mode or mode==COMPLETE_ATTRIBUTES): self._remove_autocomplete_window() mode = COMPLETE_ATTRIBUTES while i and curline[i-1] in ID_CHARS: i -= 1 comp_start = curline[i:j] if i and curline[i-1] == '.': hp.set_index("insert-%dc" % (len(curline)-(i-1))) comp_what = hp.get_expression() if not comp_what or \ (not evalfuncs and comp_what.find('(') != -1): return else: comp_what = "" else: return if complete and not comp_what and not comp_start: return comp_lists = self.fetch_completions(comp_what, mode) if not comp_lists[0]: return self.autocompletewindow = self._make_autocomplete_window() self.autocompletewindow.show_window(comp_lists, "insert-%dc" % len(comp_start), complete, mode, userWantsWin) return True def fetch_completions(self, what, mode): """Return a pair of lists of completions for something. The first list is a sublist of the second. Both are sorted. If there is a Python subprocess, get the comp. list there. Otherwise, either fetch_completions() is running in the subprocess itself or it was called in an IDLE EditorWindow before any script had been run. The subprocess environment is that of the most recently run script. If two unrelated modules are being edited some calltips in the current module may be inoperative if the module was not the last to run. """ try: rpcclt = self.editwin.flist.pyshell.interp.rpcclt except: rpcclt = None if rpcclt: return rpcclt.remotecall("exec", "get_the_completion_list", (what, mode), {}) else: if mode == COMPLETE_ATTRIBUTES: if what == "": namespace = __main__.__dict__.copy() namespace.update(__main__.__builtins__.__dict__) bigl = eval("dir()", namespace) bigl.sort() if "__all__" in bigl: smalll = eval("__all__", namespace) smalll.sort() else: smalll = filter(lambda s: s[:1] != '_', bigl) else: try: entity = self.get_entity(what) bigl = dir(entity) bigl.sort() if "__all__" in bigl: smalll = entity.__all__ smalll.sort() else: smalll = filter(lambda s: s[:1] != '_', bigl) except: return [], [] elif mode == COMPLETE_FILES: if what == "": what = "." try: expandedpath = os.path.expanduser(what) bigl = os.listdir(expandedpath) bigl.sort() smalll = filter(lambda s: s[:1] != '.', bigl) except OSError: return [], [] if not smalll: smalll = bigl return smalll, bigl def get_entity(self, name): """Lookup name in a namespace spanning sys.modules and __main.dict__""" namespace = sys.modules.copy() namespace.update(__main__.__dict__) return eval(name, namespace)
leighpauls/k2cro4
third_party/python_26/Lib/idlelib/AutoComplete.py
Python
bsd-3-clause
9,041
"""distutils.command.build_clib Implements the Distutils 'build_clib' command, to build a C/C++ library that is included in the module distribution and needed by an extension module.""" __revision__ = "$Id$" # XXX this module has *lots* of code ripped-off quite transparently from # build_ext.py -- not surprisingly really, as the work required to build # a static library from a collection of C source files is not really all # that different from what's required to build a shared object file from # a collection of C source files. Nevertheless, I haven't done the # necessary refactoring to account for the overlap in code between the # two modules, mainly because a number of subtle details changed in the # cut 'n paste. Sigh. import os from distutils.core import Command from distutils.errors import DistutilsSetupError from distutils.ccompiler import customize_compiler from distutils import log def show_compilers(): from distutils.ccompiler import show_compilers show_compilers() class build_clib(Command): description = "build C/C++ libraries used by Python extensions" user_options = [ ('build-clib=', 'b', "directory to build C/C++ libraries to"), ('build-temp=', 't', "directory to put temporary build by-products"), ('debug', 'g', "compile with debugging information"), ('force', 'f', "forcibly build everything (ignore file timestamps)"), ('compiler=', 'c', "specify the compiler type"), ] boolean_options = ['debug', 'force'] help_options = [ ('help-compiler', None, "list available compilers", show_compilers), ] def initialize_options(self): self.build_clib = None self.build_temp = None # List of libraries to build self.libraries = None # Compilation options for all libraries self.include_dirs = None self.define = None self.undef = None self.debug = None self.force = 0 self.compiler = None def finalize_options(self): # This might be confusing: both build-clib and build-temp default # to build-temp as defined by the "build" command. This is because # I think that C libraries are really just temporary build # by-products, at least from the point of view of building Python # extensions -- but I want to keep my options open. self.set_undefined_options('build', ('build_temp', 'build_clib'), ('build_temp', 'build_temp'), ('compiler', 'compiler'), ('debug', 'debug'), ('force', 'force')) self.libraries = self.distribution.libraries if self.libraries: self.check_library_list(self.libraries) if self.include_dirs is None: self.include_dirs = self.distribution.include_dirs or [] if isinstance(self.include_dirs, str): self.include_dirs = self.include_dirs.split(os.pathsep) # XXX same as for build_ext -- what about 'self.define' and # 'self.undef' ? def run(self): if not self.libraries: return # Yech -- this is cut 'n pasted from build_ext.py! from distutils.ccompiler import new_compiler self.compiler = new_compiler(compiler=self.compiler, dry_run=self.dry_run, force=self.force) customize_compiler(self.compiler) if self.include_dirs is not None: self.compiler.set_include_dirs(self.include_dirs) if self.define is not None: # 'define' option is a list of (name,value) tuples for (name,value) in self.define: self.compiler.define_macro(name, value) if self.undef is not None: for macro in self.undef: self.compiler.undefine_macro(macro) self.build_libraries(self.libraries) def check_library_list(self, libraries): """Ensure that the list of libraries is valid. `library` is presumably provided as a command option 'libraries'. This method checks that it is a list of 2-tuples, where the tuples are (library_name, build_info_dict). Raise DistutilsSetupError if the structure is invalid anywhere; just returns otherwise. """ if not isinstance(libraries, list): raise DistutilsSetupError, \ "'libraries' option must be a list of tuples" for lib in libraries: if not isinstance(lib, tuple) and len(lib) != 2: raise DistutilsSetupError, \ "each element of 'libraries' must a 2-tuple" name, build_info = lib if not isinstance(name, str): raise DistutilsSetupError, \ "first element of each tuple in 'libraries' " + \ "must be a string (the library name)" if '/' in name or (os.sep != '/' and os.sep in name): raise DistutilsSetupError, \ ("bad library name '%s': " + "may not contain directory separators") % \ lib[0] if not isinstance(build_info, dict): raise DistutilsSetupError, \ "second element of each tuple in 'libraries' " + \ "must be a dictionary (build info)" def get_library_names(self): # Assume the library list is valid -- 'check_library_list()' is # called from 'finalize_options()', so it should be! if not self.libraries: return None lib_names = [] for (lib_name, build_info) in self.libraries: lib_names.append(lib_name) return lib_names def get_source_files(self): self.check_library_list(self.libraries) filenames = [] for (lib_name, build_info) in self.libraries: sources = build_info.get('sources') if sources is None or not isinstance(sources, (list, tuple)): raise DistutilsSetupError, \ ("in 'libraries' option (library '%s'), " "'sources' must be present and must be " "a list of source filenames") % lib_name filenames.extend(sources) return filenames def build_libraries(self, libraries): for (lib_name, build_info) in libraries: sources = build_info.get('sources') if sources is None or not isinstance(sources, (list, tuple)): raise DistutilsSetupError, \ ("in 'libraries' option (library '%s'), " + "'sources' must be present and must be " + "a list of source filenames") % lib_name sources = list(sources) log.info("building '%s' library", lib_name) # First, compile the source code to object files in the library # directory. (This should probably change to putting object # files in a temporary build directory.) macros = build_info.get('macros') include_dirs = build_info.get('include_dirs') objects = self.compiler.compile(sources, output_dir=self.build_temp, macros=macros, include_dirs=include_dirs, debug=self.debug) # Now "link" the object files together into a static library. # (On Unix at least, this isn't really linking -- it just # builds an archive. Whatever.) self.compiler.create_static_lib(objects, lib_name, output_dir=self.build_clib, debug=self.debug)
ktan2020/legacy-automation
win/Lib/distutils/command/build_clib.py
Python
mit
8,340
""" Abstract base classes define the primitives that renderers and graphics contexts must implement to serve as a matplotlib backend :class:`RendererBase` An abstract base class to handle drawing/rendering operations. :class:`FigureCanvasBase` The abstraction layer that separates the :class:`matplotlib.figure.Figure` from the backend specific details like a user interface drawing area :class:`GraphicsContextBase` An abstract base class that provides color, line styles, etc... :class:`Event` The base class for all of the matplotlib event handling. Derived classes suh as :class:`KeyEvent` and :class:`MouseEvent` store the meta data like keys and buttons pressed, x and y locations in pixel and :class:`~matplotlib.axes.Axes` coordinates. """ from __future__ import division import os, warnings, time import numpy as np import matplotlib.cbook as cbook import matplotlib.colors as colors import matplotlib.transforms as transforms import matplotlib.widgets as widgets from matplotlib import rcParams class RendererBase: """An abstract base class to handle drawing/rendering operations. The following methods *must* be implemented in the backend: * :meth:`draw_path` * :meth:`draw_image` * :meth:`draw_text` * :meth:`get_text_width_height_descent` The following methods *should* be implemented in the backend for optimization reasons: * :meth:`draw_markers` * :meth:`draw_path_collection` * :meth:`draw_quad_mesh` """ def __init__(self): self._texmanager = None def open_group(self, s): """ Open a grouping element with label *s*. Is only currently used by :mod:`~matplotlib.backends.backend_svg` """ pass def close_group(self, s): """ Close a grouping element with label *s* Is only currently used by :mod:`~matplotlib.backends.backend_svg` """ pass def draw_path(self, gc, path, transform, rgbFace=None): """ Draws a :class:`~matplotlib.path.Path` instance using the given affine transform. """ raise NotImplementedError def draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace=None): """ Draws a marker at each of the vertices in path. This includes all vertices, including control points on curves. To avoid that behavior, those vertices should be removed before calling this function. *gc* the :class:`GraphicsContextBase` instance *marker_trans* is an affine transform applied to the marker. *trans* is an affine transform applied to the path. This provides a fallback implementation of draw_markers that makes multiple calls to :meth:`draw_path`. Some backends may want to override this method in order to draw the marker only once and reuse it multiple times. """ tpath = trans.transform_path(path) for vertices, codes in tpath.iter_segments(): if len(vertices): x,y = vertices[-2:] self.draw_path(gc, marker_path, marker_trans + transforms.Affine2D().translate(x, y), rgbFace) def draw_path_collection(self, master_transform, cliprect, clippath, clippath_trans, paths, all_transforms, offsets, offsetTrans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls): """ Draws a collection of paths, selecting drawing properties from the lists *facecolors*, *edgecolors*, *linewidths*, *linestyles* and *antialiaseds*. *offsets* is a list of offsets to apply to each of the paths. The offsets in *offsets* are first transformed by *offsetTrans* before being applied. This provides a fallback implementation of :meth:`draw_path_collection` that makes multiple calls to draw_path. Some backends may want to override this in order to render each set of path data only once, and then reference that path multiple times with the different offsets, colors, styles etc. The generator methods :meth:`_iter_collection_raw_paths` and :meth:`_iter_collection` are provided to help with (and standardize) the implementation across backends. It is highly recommended to use those generators, so that changes to the behavior of :meth:`draw_path_collection` can be made globally. """ path_ids = [] for path, transform in self._iter_collection_raw_paths( master_transform, paths, all_transforms): path_ids.append((path, transform)) for xo, yo, path_id, gc, rgbFace in self._iter_collection( path_ids, cliprect, clippath, clippath_trans, offsets, offsetTrans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls): path, transform = path_id transform = transforms.Affine2D(transform.get_matrix()).translate(xo, yo) self.draw_path(gc, path, transform, rgbFace) def draw_quad_mesh(self, master_transform, cliprect, clippath, clippath_trans, meshWidth, meshHeight, coordinates, offsets, offsetTrans, facecolors, antialiased, showedges): """ This provides a fallback implementation of :meth:`draw_quad_mesh` that generates paths and then calls :meth:`draw_path_collection`. """ from matplotlib.collections import QuadMesh paths = QuadMesh.convert_mesh_to_paths( meshWidth, meshHeight, coordinates) if showedges: edgecolors = np.array([[0.0, 0.0, 0.0, 1.0]], np.float_) linewidths = np.array([1.0], np.float_) else: edgecolors = facecolors linewidths = np.array([0.0], np.float_) return self.draw_path_collection( master_transform, cliprect, clippath, clippath_trans, paths, [], offsets, offsetTrans, facecolors, edgecolors, linewidths, [], [antialiased], [None]) def _iter_collection_raw_paths(self, master_transform, paths, all_transforms): """ This is a helper method (along with :meth:`_iter_collection`) to make it easier to write a space-efficent :meth:`draw_path_collection` implementation in a backend. This method yields all of the base path/transform combinations, given a master transform, a list of paths and list of transforms. The arguments should be exactly what is passed in to :meth:`draw_path_collection`. The backend should take each yielded path and transform and create an object that can be referenced (reused) later. """ Npaths = len(paths) Ntransforms = len(all_transforms) N = max(Npaths, Ntransforms) if Npaths == 0: return transform = transforms.IdentityTransform() for i in xrange(N): path = paths[i % Npaths] if Ntransforms: transform = all_transforms[i % Ntransforms] yield path, transform + master_transform def _iter_collection(self, path_ids, cliprect, clippath, clippath_trans, offsets, offsetTrans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls): """ This is a helper method (along with :meth:`_iter_collection_raw_paths`) to make it easier to write a space-efficent :meth:`draw_path_collection` implementation in a backend. This method yields all of the path, offset and graphics context combinations to draw the path collection. The caller should already have looped over the results of :meth:`_iter_collection_raw_paths` to draw this collection. The arguments should be the same as that passed into :meth:`draw_path_collection`, with the exception of *path_ids*, which is a list of arbitrary objects that the backend will use to reference one of the paths created in the :meth:`_iter_collection_raw_paths` stage. Each yielded result is of the form:: xo, yo, path_id, gc, rgbFace where *xo*, *yo* is an offset; *path_id* is one of the elements of *path_ids*; *gc* is a graphics context and *rgbFace* is a color to use for filling the path. """ Npaths = len(path_ids) Noffsets = len(offsets) N = max(Npaths, Noffsets) Nfacecolors = len(facecolors) Nedgecolors = len(edgecolors) Nlinewidths = len(linewidths) Nlinestyles = len(linestyles) Naa = len(antialiaseds) Nurls = len(urls) if (Nfacecolors == 0 and Nedgecolors == 0) or Npaths == 0: return if Noffsets: toffsets = offsetTrans.transform(offsets) gc = self.new_gc() gc.set_clip_rectangle(cliprect) if clippath is not None: clippath = transforms.TransformedPath(clippath, clippath_trans) gc.set_clip_path(clippath) if Nfacecolors == 0: rgbFace = None if Nedgecolors == 0: gc.set_linewidth(0.0) xo, yo = 0, 0 for i in xrange(N): path_id = path_ids[i % Npaths] if Noffsets: xo, yo = toffsets[i % Noffsets] if Nfacecolors: rgbFace = facecolors[i % Nfacecolors] if Nedgecolors: gc.set_foreground(edgecolors[i % Nedgecolors]) if Nlinewidths: gc.set_linewidth(linewidths[i % Nlinewidths]) if Nlinestyles: gc.set_dashes(*linestyles[i % Nlinestyles]) if rgbFace is not None and len(rgbFace)==4: gc.set_alpha(rgbFace[-1]) rgbFace = rgbFace[:3] gc.set_antialiased(antialiaseds[i % Naa]) if Nurls: gc.set_url(urls[i % Nurls]) yield xo, yo, path_id, gc, rgbFace def get_image_magnification(self): """ Get the factor by which to magnify images passed to :meth:`draw_image`. Allows a backend to have images at a different resolution to other artists. """ return 1.0 def draw_image(self, x, y, im, bbox, clippath=None, clippath_trans=None): """ Draw the image instance into the current axes; *x* is the distance in pixels from the left hand side of the canvas. *y* the distance from the origin. That is, if origin is upper, y is the distance from top. If origin is lower, y is the distance from bottom *im* the :class:`matplotlib._image.Image` instance *bbox* a :class:`matplotlib.transforms.Bbox` instance for clipping, or None """ raise NotImplementedError def option_image_nocomposite(self): """ overwrite this method for renderers that do not necessarily want to rescale and composite raster images. (like SVG) """ return False def draw_tex(self, gc, x, y, s, prop, angle, ismath='TeX!'): raise NotImplementedError def draw_text(self, gc, x, y, s, prop, angle, ismath=False): """ Draw the text instance *gc* the :class:`GraphicsContextBase` instance *x* the x location of the text in display coords *y* the y location of the text in display coords *s* a :class:`matplotlib.text.Text` instance *prop* a :class:`matplotlib.font_manager.FontProperties` instance *angle* the rotation angle in degrees **backend implementers note** When you are trying to determine if you have gotten your bounding box right (which is what enables the text layout/alignment to work properly), it helps to change the line in text.py:: if 0: bbox_artist(self, renderer) to if 1, and then the actual bounding box will be blotted along with your text. """ raise NotImplementedError def flipy(self): """ Return true if y small numbers are top for renderer Is used for drawing text (:mod:`matplotlib.text`) and images (:mod:`matplotlib.image`) only """ return True def get_canvas_width_height(self): 'return the canvas width and height in display coords' return 1, 1 def get_texmanager(self): """ return the :class:`matplotlib.texmanager.TexManager` instance """ if self._texmanager is None: from matplotlib.texmanager import TexManager self._texmanager = TexManager() return self._texmanager def get_text_width_height_descent(self, s, prop, ismath): """ get the width and height, and the offset from the bottom to the baseline (descent), in display coords of the string s with :class:`~matplotlib.font_manager.FontProperties` prop """ raise NotImplementedError def new_gc(self): """ Return an instance of a :class:`GraphicsContextBase` """ return GraphicsContextBase() def points_to_pixels(self, points): """ Convert points to display units *points* a float or a numpy array of float return points converted to pixels You need to override this function (unless your backend doesn't have a dpi, eg, postscript or svg). Some imaging systems assume some value for pixels per inch:: points to pixels = points * pixels_per_inch/72.0 * dpi/72.0 """ return points def strip_math(self, s): return cbook.strip_math(s) def start_rasterizing(self): pass def stop_rasterizing(self): pass class GraphicsContextBase: """ An abstract base class that provides color, line styles, etc... """ # a mapping from dash styles to suggested offset, dash pairs dashd = { 'solid' : (None, None), 'dashed' : (0, (6.0, 6.0)), 'dashdot' : (0, (3.0, 5.0, 1.0, 5.0)), 'dotted' : (0, (1.0, 3.0)), } def __init__(self): self._alpha = 1.0 self._antialiased = 1 # use 0,1 not True, False for extension code self._capstyle = 'butt' self._cliprect = None self._clippath = None self._dashes = None, None self._joinstyle = 'miter' self._linestyle = 'solid' self._linewidth = 1 self._rgb = (0.0, 0.0, 0.0) self._hatch = None self._url = None self._snap = None def copy_properties(self, gc): 'Copy properties from gc to self' self._alpha = gc._alpha self._antialiased = gc._antialiased self._capstyle = gc._capstyle self._cliprect = gc._cliprect self._clippath = gc._clippath self._dashes = gc._dashes self._joinstyle = gc._joinstyle self._linestyle = gc._linestyle self._linewidth = gc._linewidth self._rgb = gc._rgb self._hatch = gc._hatch self._url = gc._url self._snap = gc._snap def get_alpha(self): """ Return the alpha value used for blending - not supported on all backends """ return self._alpha def get_antialiased(self): "Return true if the object should try to do antialiased rendering" return self._antialiased def get_capstyle(self): """ Return the capstyle as a string in ('butt', 'round', 'projecting') """ return self._capstyle def get_clip_rectangle(self): """ Return the clip rectangle as a :class:`~matplotlib.transforms.Bbox` instance """ return self._cliprect def get_clip_path(self): """ Return the clip path in the form (path, transform), where path is a :class:`~matplotlib.path.Path` instance, and transform is an affine transform to apply to the path before clipping. """ if self._clippath is not None: return self._clippath.get_transformed_path_and_affine() return None, None def get_dashes(self): """ Return the dash information as an offset dashlist tuple. The dash list is a even size list that gives the ink on, ink off in pixels. See p107 of to PostScript `BLUEBOOK <http://www-cdf.fnal.gov/offline/PostScript/BLUEBOOK.PDF>`_ for more info. Default value is None """ return self._dashes def get_joinstyle(self): """ Return the line join style as one of ('miter', 'round', 'bevel') """ return self._joinstyle def get_linestyle(self, style): """ Return the linestyle: one of ('solid', 'dashed', 'dashdot', 'dotted'). """ return self._linestyle def get_linewidth(self): """ Return the line width in points as a scalar """ return self._linewidth def get_rgb(self): """ returns a tuple of three floats from 0-1. color can be a matlab format string, a html hex color string, or a rgb tuple """ return self._rgb def get_url(self): """ returns a url if one is set, None otherwise """ return self._url def get_snap(self): """ returns the snap setting which may be: * True: snap vertices to the nearest pixel center * False: leave vertices as-is * None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center """ return self._snap def set_alpha(self, alpha): """ Set the alpha value used for blending - not supported on all backends """ self._alpha = alpha def set_antialiased(self, b): """ True if object should be drawn with antialiased rendering """ # use 0, 1 to make life easier on extension code trying to read the gc if b: self._antialiased = 1 else: self._antialiased = 0 def set_capstyle(self, cs): """ Set the capstyle as a string in ('butt', 'round', 'projecting') """ if cs in ('butt', 'round', 'projecting'): self._capstyle = cs else: raise ValueError('Unrecognized cap style. Found %s' % cs) def set_clip_rectangle(self, rectangle): """ Set the clip rectangle with sequence (left, bottom, width, height) """ self._cliprect = rectangle def set_clip_path(self, path): """ Set the clip path and transformation. Path should be a :class:`~matplotlib.transforms.TransformedPath` instance. """ assert path is None or isinstance(path, transforms.TransformedPath) self._clippath = path def set_dashes(self, dash_offset, dash_list): """ Set the dash style for the gc. *dash_offset* is the offset (usually 0). *dash_list* specifies the on-off sequence as points. ``(None, None)`` specifies a solid line """ self._dashes = dash_offset, dash_list def set_foreground(self, fg, isRGB=False): """ Set the foreground color. fg can be a matlab format string, a html hex color string, an rgb unit tuple, or a float between 0 and 1. In the latter case, grayscale is used. The :class:`GraphicsContextBase` converts colors to rgb internally. If you know the color is rgb already, you can set ``isRGB=True`` to avoid the performace hit of the conversion """ if isRGB: self._rgb = fg else: self._rgb = colors.colorConverter.to_rgba(fg) def set_graylevel(self, frac): """ Set the foreground color to be a gray level with *frac* """ self._rgb = (frac, frac, frac) def set_joinstyle(self, js): """ Set the join style to be one of ('miter', 'round', 'bevel') """ if js in ('miter', 'round', 'bevel'): self._joinstyle = js else: raise ValueError('Unrecognized join style. Found %s' % js) def set_linewidth(self, w): """ Set the linewidth in points """ self._linewidth = w def set_linestyle(self, style): """ Set the linestyle to be one of ('solid', 'dashed', 'dashdot', 'dotted'). """ try: offset, dashes = self.dashd[style] except: raise ValueError('Unrecognized linestyle: %s' % style) self._linestyle = style self.set_dashes(offset, dashes) def set_url(self, url): """ Sets the url for links in compatible backends """ self._url = url def set_snap(self, snap): """ Sets the snap setting which may be: * True: snap vertices to the nearest pixel center * False: leave vertices as-is * None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center """ self._snap = snap def set_hatch(self, hatch): """ Sets the hatch style for filling """ self._hatch = hatch def get_hatch(self): """ Gets the current hatch style """ return self._hatch class Event: """ A matplotlib event. Attach additional attributes as defined in :meth:`FigureCanvasBase.mpl_connect`. The following attributes are defined and shown with their default values *name* the event name *canvas* the FigureCanvas instance generating the event *guiEvent* the GUI event that triggered the matplotlib event """ def __init__(self, name, canvas,guiEvent=None): self.name = name self.canvas = canvas self.guiEvent = guiEvent class IdleEvent(Event): """ An event triggered by the GUI backend when it is idle -- useful for passive animation """ pass class DrawEvent(Event): """ An event triggered by a draw operation on the canvas In addition to the :class:`Event` attributes, the following event attributes are defined: *renderer* the :class:`RendererBase` instance for the draw event """ def __init__(self, name, canvas, renderer): Event.__init__(self, name, canvas) self.renderer = renderer class ResizeEvent(Event): """ An event triggered by a canvas resize In addition to the :class:`Event` attributes, the following event attributes are defined: *width* width of the canvas in pixels *height* height of the canvas in pixels """ def __init__(self, name, canvas): Event.__init__(self, name, canvas) self.width, self.height = canvas.get_width_height() class LocationEvent(Event): """ A event that has a screen location The following additional attributes are defined and shown with their default values In addition to the :class:`Event` attributes, the following event attributes are defined: *x* x position - pixels from left of canvas *y* y position - pixels from bottom of canvas *inaxes* the :class:`~matplotlib.axes.Axes` instance if mouse is over axes *xdata* x coord of mouse in data coords *ydata* y coord of mouse in data coords """ x = None # x position - pixels from left of canvas y = None # y position - pixels from right of canvas inaxes = None # the Axes instance if mouse us over axes xdata = None # x coord of mouse in data coords ydata = None # y coord of mouse in data coords # the last event that was triggered before this one lastevent = None def __init__(self, name, canvas, x, y,guiEvent=None): """ *x*, *y* in figure coords, 0,0 = bottom, left """ Event.__init__(self, name, canvas,guiEvent=guiEvent) self.x = x self.y = y if x is None or y is None: # cannot check if event was in axes if no x,y info self.inaxes = None self._update_enter_leave() return # Find all axes containing the mouse axes_list = [a for a in self.canvas.figure.get_axes() if a.in_axes(self)] if len(axes_list) == 0: # None found self.inaxes = None self._update_enter_leave() return elif (len(axes_list) > 1): # Overlap, get the highest zorder axCmp = lambda _x,_y: cmp(_x.zorder, _y.zorder) axes_list.sort(axCmp) self.inaxes = axes_list[-1] # Use the highest zorder else: # Just found one hit self.inaxes = axes_list[0] try: xdata, ydata = self.inaxes.transData.inverted().transform_point((x, y)) except ValueError: self.xdata = None self.ydata = None else: self.xdata = xdata self.ydata = ydata self._update_enter_leave() def _update_enter_leave(self): 'process the figure/axes enter leave events' if LocationEvent.lastevent is not None: last = LocationEvent.lastevent if last.inaxes!=self.inaxes: # process axes enter/leave events if last.inaxes is not None: last.canvas.callbacks.process('axes_leave_event', last) if self.inaxes is not None: self.canvas.callbacks.process('axes_enter_event', self) else: # process a figure enter event if self.inaxes is not None: self.canvas.callbacks.process('axes_enter_event', self) LocationEvent.lastevent = self class MouseEvent(LocationEvent): """ A mouse event ('button_press_event', 'button_release_event', 'scroll_event', 'motion_notify_event'). In addition to the :class:`Event` and :class:`LocationEvent` attributes, the following attributes are defined: *button* button pressed None, 1, 2, 3, 'up', 'down' (up and down are used for scroll events) *key* the key pressed: None, chr(range(255), 'shift', 'win', or 'control' *step* number of scroll steps (positive for 'up', negative for 'down') Example usage:: def on_press(event): print 'you pressed', event.button, event.xdata, event.ydata cid = fig.canvas.mpl_connect('button_press_event', on_press) """ x = None # x position - pixels from left of canvas y = None # y position - pixels from right of canvas button = None # button pressed None, 1, 2, 3 inaxes = None # the Axes instance if mouse us over axes xdata = None # x coord of mouse in data coords ydata = None # y coord of mouse in data coords step = None # scroll steps for scroll events def __init__(self, name, canvas, x, y, button=None, key=None, step=0, guiEvent=None): """ x, y in figure coords, 0,0 = bottom, left button pressed None, 1, 2, 3, 'up', 'down' """ LocationEvent.__init__(self, name, canvas, x, y, guiEvent=guiEvent) self.button = button self.key = key self.step = step class PickEvent(Event): """ a pick event, fired when the user picks a location on the canvas sufficiently close to an artist. Attrs: all the :class:`Event` attributes plus *mouseevent* the :class:`MouseEvent` that generated the pick *artist* the :class:`~matplotlib.artist.Artist` picked other extra class dependent attrs -- eg a :class:`~matplotlib.lines.Line2D` pick may define different extra attributes than a :class:`~matplotlib.collections.PatchCollection` pick event Example usage:: line, = ax.plot(rand(100), 'o', picker=5) # 5 points tolerance def on_pick(event): thisline = event.artist xdata, ydata = thisline.get_data() ind = event.ind print 'on pick line:', zip(xdata[ind], ydata[ind]) cid = fig.canvas.mpl_connect('pick_event', on_pick) """ def __init__(self, name, canvas, mouseevent, artist, guiEvent=None, **kwargs): Event.__init__(self, name, canvas, guiEvent) self.mouseevent = mouseevent self.artist = artist self.__dict__.update(kwargs) class KeyEvent(LocationEvent): """ A key event (key press, key release). Attach additional attributes as defined in :meth:`FigureCanvasBase.mpl_connect`. In addition to the :class:`Event` and :class:`LocationEvent` attributes, the following attributes are defined: *key* the key pressed: None, chr(range(255), shift, win, or control This interface may change slightly when better support for modifier keys is included. Example usage:: def on_key(event): print 'you pressed', event.key, event.xdata, event.ydata cid = fig.canvas.mpl_connect('key_press_event', on_key) """ def __init__(self, name, canvas, key, x=0, y=0, guiEvent=None): LocationEvent.__init__(self, name, canvas, x, y, guiEvent=guiEvent) self.key = key class FigureCanvasBase: """ The canvas the figure renders into. Public attributes *figure* A :class:`matplotlib.figure.Figure` instance """ events = [ 'resize_event', 'draw_event', 'key_press_event', 'key_release_event', 'button_press_event', 'button_release_event', 'scroll_event', 'motion_notify_event', 'pick_event', 'idle_event', 'figure_enter_event', 'figure_leave_event', 'axes_enter_event', 'axes_leave_event' ] def __init__(self, figure): figure.set_canvas(self) self.figure = figure # a dictionary from event name to a dictionary that maps cid->func self.callbacks = cbook.CallbackRegistry(self.events) self.widgetlock = widgets.LockDraw() self._button = None # the button pressed self._key = None # the key pressed self._lastx, self._lasty = None, None self.button_pick_id = self.mpl_connect('button_press_event',self.pick) self.scroll_pick_id = self.mpl_connect('scroll_event',self.pick) if False: ## highlight the artists that are hit self.mpl_connect('motion_notify_event',self.onHilite) ## delete the artists that are clicked on #self.mpl_disconnect(self.button_pick_id) #self.mpl_connect('button_press_event',self.onRemove) def onRemove(self, ev): """ Mouse event processor which removes the top artist under the cursor. Connect this to the 'mouse_press_event' using:: canvas.mpl_connect('mouse_press_event',canvas.onRemove) """ def sort_artists(artists): # This depends on stable sort and artists returned # from get_children in z order. L = [ (h.zorder, h) for h in artists ] L.sort() return [ h for zorder, h in L ] # Find the top artist under the cursor under = sort_artists(self.figure.hitlist(ev)) h = None if under: h = under[-1] # Try deleting that artist, or its parent if you # can't delete the artist while h: print "Removing",h if h.remove(): self.draw_idle() break parent = None for p in under: if h in p.get_children(): parent = p break h = parent def onHilite(self, ev): """ Mouse event processor which highlights the artists under the cursor. Connect this to the 'motion_notify_event' using:: canvas.mpl_connect('motion_notify_event',canvas.onHilite) """ if not hasattr(self,'_active'): self._active = dict() under = self.figure.hitlist(ev) enter = [a for a in under if a not in self._active] leave = [a for a in self._active if a not in under] print "within:"," ".join([str(x) for x in under]) #print "entering:",[str(a) for a in enter] #print "leaving:",[str(a) for a in leave] # On leave restore the captured colour for a in leave: if hasattr(a,'get_color'): a.set_color(self._active[a]) elif hasattr(a,'get_edgecolor'): a.set_edgecolor(self._active[a][0]) a.set_facecolor(self._active[a][1]) del self._active[a] # On enter, capture the color and repaint the artist # with the highlight colour. Capturing colour has to # be done first in case the parent recolouring affects # the child. for a in enter: if hasattr(a,'get_color'): self._active[a] = a.get_color() elif hasattr(a,'get_edgecolor'): self._active[a] = (a.get_edgecolor(),a.get_facecolor()) else: self._active[a] = None for a in enter: if hasattr(a,'get_color'): a.set_color('red') elif hasattr(a,'get_edgecolor'): a.set_edgecolor('red') a.set_facecolor('lightblue') else: self._active[a] = None self.draw_idle() def pick(self, mouseevent): if not self.widgetlock.locked(): self.figure.pick(mouseevent) def blit(self, bbox=None): """ blit the canvas in bbox (default entire canvas) """ pass def resize(self, w, h): """ set the canvas size in pixels """ pass def draw_event(self, renderer): """ This method will be call all functions connected to the 'draw_event' with a :class:`DrawEvent` """ s = 'draw_event' event = DrawEvent(s, self, renderer) self.callbacks.process(s, event) def resize_event(self): """ This method will be call all functions connected to the 'resize_event' with a :class:`ResizeEvent` """ s = 'resize_event' event = ResizeEvent(s, self) self.callbacks.process(s, event) def key_press_event(self, key, guiEvent=None): """ This method will be call all functions connected to the 'key_press_event' with a :class:`KeyEvent` """ self._key = key s = 'key_press_event' event = KeyEvent(s, self, key, self._lastx, self._lasty, guiEvent=guiEvent) self.callbacks.process(s, event) def key_release_event(self, key, guiEvent=None): """ This method will be call all functions connected to the 'key_release_event' with a :class:`KeyEvent` """ s = 'key_release_event' event = KeyEvent(s, self, key, self._lastx, self._lasty, guiEvent=guiEvent) self.callbacks.process(s, event) self._key = None def pick_event(self, mouseevent, artist, **kwargs): """ This method will be called by artists who are picked and will fire off :class:`PickEvent` callbacks registered listeners """ s = 'pick_event' event = PickEvent(s, self, mouseevent, artist, **kwargs) self.callbacks.process(s, event) def scroll_event(self, x, y, step, guiEvent=None): """ Backend derived classes should call this function on any scroll wheel event. x,y are the canvas coords: 0,0 is lower, left. button and key are as defined in MouseEvent. This method will be call all functions connected to the 'scroll_event' with a :class:`MouseEvent` instance. """ if step >= 0: self._button = 'up' else: self._button = 'down' s = 'scroll_event' mouseevent = MouseEvent(s, self, x, y, self._button, self._key, step=step, guiEvent=guiEvent) self.callbacks.process(s, mouseevent) def button_press_event(self, x, y, button, guiEvent=None): """ Backend derived classes should call this function on any mouse button press. x,y are the canvas coords: 0,0 is lower, left. button and key are as defined in :class:`MouseEvent`. This method will be call all functions connected to the 'button_press_event' with a :class:`MouseEvent` instance. """ self._button = button s = 'button_press_event' mouseevent = MouseEvent(s, self, x, y, button, self._key, guiEvent=guiEvent) self.callbacks.process(s, mouseevent) def button_release_event(self, x, y, button, guiEvent=None): """ Backend derived classes should call this function on any mouse button release. *x* the canvas coordinates where 0=left *y* the canvas coordinates where 0=bottom *guiEvent* the native UI event that generated the mpl event This method will be call all functions connected to the 'button_release_event' with a :class:`MouseEvent` instance. """ s = 'button_release_event' event = MouseEvent(s, self, x, y, button, self._key, guiEvent=guiEvent) self.callbacks.process(s, event) self._button = None def motion_notify_event(self, x, y, guiEvent=None): """ Backend derived classes should call this function on any motion-notify-event. *x* the canvas coordinates where 0=left *y* the canvas coordinates where 0=bottom *guiEvent* the native UI event that generated the mpl event This method will be call all functions connected to the 'motion_notify_event' with a :class:`MouseEvent` instance. """ self._lastx, self._lasty = x, y s = 'motion_notify_event' event = MouseEvent(s, self, x, y, self._button, self._key, guiEvent=guiEvent) self.callbacks.process(s, event) def leave_notify_event(self, guiEvent=None): """ Backend derived classes should call this function when leaving canvas *guiEvent* the native UI event that generated the mpl event """ self.callbacks.process('figure_leave_event', LocationEvent.lastevent) LocationEvent.lastevent = None def enter_notify_event(self, guiEvent=None): """ Backend derived classes should call this function when entering canvas *guiEvent* the native UI event that generated the mpl event """ event = Event('figure_enter_event', self, guiEvent) self.callbacks.process('figure_enter_event', event) def idle_event(self, guiEvent=None): 'call when GUI is idle' s = 'idle_event' event = IdleEvent(s, self, guiEvent=guiEvent) self.callbacks.process(s, event) def draw(self, *args, **kwargs): """ Render the :class:`~matplotlib.figure.Figure` """ pass def draw_idle(self, *args, **kwargs): """ :meth:`draw` only if idle; defaults to draw but backends can overrride """ self.draw(*args, **kwargs) def draw_cursor(self, event): """ Draw a cursor in the event.axes if inaxes is not None. Use native GUI drawing for efficiency if possible """ pass def get_width_height(self): """ return the figure width and height in points or pixels (depending on the backend), truncated to integers """ return int(self.figure.bbox.width), int(self.figure.bbox.height) filetypes = { 'emf': 'Enhanced Metafile', 'eps': 'Encapsulated Postscript', 'pdf': 'Portable Document Format', 'png': 'Portable Network Graphics', 'ps' : 'Postscript', 'raw': 'Raw RGBA bitmap', 'rgba': 'Raw RGBA bitmap', 'svg': 'Scalable Vector Graphics', 'svgz': 'Scalable Vector Graphics' } # All of these print_* functions do a lazy import because # a) otherwise we'd have cyclical imports, since all of these # classes inherit from FigureCanvasBase # b) so we don't import a bunch of stuff the user may never use def print_emf(self, *args, **kwargs): from backends.backend_emf import FigureCanvasEMF # lazy import emf = self.switch_backends(FigureCanvasEMF) return emf.print_emf(*args, **kwargs) def print_eps(self, *args, **kwargs): from backends.backend_ps import FigureCanvasPS # lazy import ps = self.switch_backends(FigureCanvasPS) return ps.print_eps(*args, **kwargs) def print_pdf(self, *args, **kwargs): from backends.backend_pdf import FigureCanvasPdf # lazy import pdf = self.switch_backends(FigureCanvasPdf) return pdf.print_pdf(*args, **kwargs) def print_png(self, *args, **kwargs): from backends.backend_agg import FigureCanvasAgg # lazy import agg = self.switch_backends(FigureCanvasAgg) return agg.print_png(*args, **kwargs) def print_ps(self, *args, **kwargs): from backends.backend_ps import FigureCanvasPS # lazy import ps = self.switch_backends(FigureCanvasPS) return ps.print_ps(*args, **kwargs) def print_raw(self, *args, **kwargs): from backends.backend_agg import FigureCanvasAgg # lazy import agg = self.switch_backends(FigureCanvasAgg) return agg.print_raw(*args, **kwargs) print_bmp = print_rgb = print_raw def print_svg(self, *args, **kwargs): from backends.backend_svg import FigureCanvasSVG # lazy import svg = self.switch_backends(FigureCanvasSVG) return svg.print_svg(*args, **kwargs) def print_svgz(self, *args, **kwargs): from backends.backend_svg import FigureCanvasSVG # lazy import svg = self.switch_backends(FigureCanvasSVG) return svg.print_svgz(*args, **kwargs) def get_supported_filetypes(self): return self.filetypes def get_supported_filetypes_grouped(self): groupings = {} for ext, name in self.filetypes.items(): groupings.setdefault(name, []).append(ext) groupings[name].sort() return groupings def print_figure(self, filename, dpi=None, facecolor='w', edgecolor='w', orientation='portrait', format=None, **kwargs): """ Render the figure to hardcopy. Set the figure patch face and edge colors. This is useful because some of the GUIs have a gray figure face color background and you'll probably want to override this on hardcopy. Arguments are: *filename* can also be a file object on image backends *orientation* only currently applies to PostScript printing. *dpi* the dots per inch to save the figure in; if None, use savefig.dpi *facecolor* the facecolor of the figure *edgecolor* the edgecolor of the figure *orientation* ' landscape' | 'portrait' (not supported on all backends) *format* when set, forcibly set the file format to save to """ if format is None: if cbook.is_string_like(filename): format = os.path.splitext(filename)[1][1:] if format is None or format == '': format = self.get_default_filetype() if cbook.is_string_like(filename): filename = filename.rstrip('.') + '.' + format format = format.lower() method_name = 'print_%s' % format if (format not in self.filetypes or not hasattr(self, method_name)): formats = self.filetypes.keys() formats.sort() raise ValueError( 'Format "%s" is not supported.\n' 'Supported formats: ' '%s.' % (format, ', '.join(formats))) if dpi is None: dpi = rcParams['savefig.dpi'] origDPI = self.figure.dpi origfacecolor = self.figure.get_facecolor() origedgecolor = self.figure.get_edgecolor() self.figure.dpi = dpi self.figure.set_facecolor(facecolor) self.figure.set_edgecolor(edgecolor) try: result = getattr(self, method_name)( filename, dpi=dpi, facecolor=facecolor, edgecolor=edgecolor, orientation=orientation, **kwargs) finally: self.figure.dpi = origDPI self.figure.set_facecolor(origfacecolor) self.figure.set_edgecolor(origedgecolor) self.figure.set_canvas(self) #self.figure.canvas.draw() ## seems superfluous return result def get_default_filetype(self): raise NotImplementedError def set_window_title(self, title): """ Set the title text of the window containing the figure. Note that this has no effect if there is no window (eg, a PS backend). """ if hasattr(self, "manager"): self.manager.set_window_title(title) def switch_backends(self, FigureCanvasClass): """ instantiate an instance of FigureCanvasClass This is used for backend switching, eg, to instantiate a FigureCanvasPS from a FigureCanvasGTK. Note, deep copying is not done, so any changes to one of the instances (eg, setting figure size or line props), will be reflected in the other """ newCanvas = FigureCanvasClass(self.figure) return newCanvas def mpl_connect(self, s, func): """ Connect event with string *s* to *func*. The signature of *func* is:: def func(event) where event is a :class:`matplotlib.backend_bases.Event`. The following events are recognized - 'button_press_event' - 'button_release_event' - 'draw_event' - 'key_press_event' - 'key_release_event' - 'motion_notify_event' - 'pick_event' - 'resize_event' - 'scroll_event' For the location events (button and key press/release), if the mouse is over the axes, the variable ``event.inaxes`` will be set to the :class:`~matplotlib.axes.Axes` the event occurs is over, and additionally, the variables ``event.xdata`` and ``event.ydata`` will be defined. This is the mouse location in data coords. See :class:`~matplotlib.backend_bases.KeyEvent` and :class:`~matplotlib.backend_bases.MouseEvent` for more info. Return value is a connection id that can be used with :meth:`~matplotlib.backend_bases.Event.mpl_disconnect`. Example usage:: def on_press(event): print 'you pressed', event.button, event.xdata, event.ydata cid = canvas.mpl_connect('button_press_event', on_press) """ return self.callbacks.connect(s, func) def mpl_disconnect(self, cid): """ disconnect callback id cid Example usage:: cid = canvas.mpl_connect('button_press_event', on_press) #...later canvas.mpl_disconnect(cid) """ return self.callbacks.disconnect(cid) def flush_events(self): """ Flush the GUI events for the figure. Implemented only for backends with GUIs. """ raise NotImplementedError def start_event_loop(self,timeout): """ Start an event loop. This is used to start a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. This should not be confused with the main GUI event loop, which is always running and has nothing to do with this. This is implemented only for backends with GUIs. """ raise NotImplementedError def stop_event_loop(self): """ Stop an event loop. This is used to stop a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. This is implemented only for backends with GUIs. """ raise NotImplementedError def start_event_loop_default(self,timeout=0): """ Start an event loop. This is used to start a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. This should not be confused with the main GUI event loop, which is always running and has nothing to do with this. This function provides default event loop functionality based on time.sleep that is meant to be used until event loop functions for each of the GUI backends can be written. As such, it throws a deprecated warning. Call signature:: start_event_loop_default(self,timeout=0) This call blocks until a callback function triggers stop_event_loop() or *timeout* is reached. If *timeout* is <=0, never timeout. """ str = "Using default event loop until function specific" str += " to this GUI is implemented" warnings.warn(str,DeprecationWarning) if timeout <= 0: timeout = np.inf timestep = 0.01 counter = 0 self._looping = True while self._looping and counter*timestep < timeout: self.flush_events() time.sleep(timestep) counter += 1 def stop_event_loop_default(self): """ Stop an event loop. This is used to stop a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. Call signature:: stop_event_loop_default(self) """ self._looping = False class FigureManagerBase: """ Helper class for matlab mode, wraps everything up into a neat bundle Public attibutes: *canvas* A :class:`FigureCanvasBase` instance *num* The figure nuamber """ def __init__(self, canvas, num): self.canvas = canvas canvas.manager = self # store a pointer to parent self.num = num self.canvas.mpl_connect('key_press_event', self.key_press) def destroy(self): pass def full_screen_toggle (self): pass def resize(self, w, h): 'For gui backends: resize window in pixels' pass def key_press(self, event): # these bindings happen whether you are over an axes or not #if event.key == 'q': # self.destroy() # how cruel to have to destroy oneself! # return if event.key == 'f': self.full_screen_toggle() # *h*ome or *r*eset mnemonic elif event.key == 'h' or event.key == 'r' or event.key == "home": self.canvas.toolbar.home() # c and v to enable left handed quick navigation elif event.key == 'left' or event.key == 'c' or event.key == 'backspace': self.canvas.toolbar.back() elif event.key == 'right' or event.key == 'v': self.canvas.toolbar.forward() # *p*an mnemonic elif event.key == 'p': self.canvas.toolbar.pan() # z*o*om mnemonic elif event.key == 'o': self.canvas.toolbar.zoom() elif event.key == 's': self.canvas.toolbar.save_figure(self.canvas.toolbar) if event.inaxes is None: return # the mouse has to be over an axes to trigger these if event.key == 'g': event.inaxes.grid() self.canvas.draw() elif event.key == 'l': ax = event.inaxes scale = ax.get_yscale() if scale=='log': ax.set_yscale('linear') ax.figure.canvas.draw() elif scale=='linear': ax.set_yscale('log') ax.figure.canvas.draw() elif event.key is not None and (event.key.isdigit() and event.key!='0') or event.key=='a': # 'a' enables all axes if event.key!='a': n=int(event.key)-1 for i, a in enumerate(self.canvas.figure.get_axes()): if event.x is not None and event.y is not None and a.in_axes(event): if event.key=='a': a.set_navigate(True) else: a.set_navigate(i==n) def show_popup(self, msg): """ Display message in a popup -- GUI only """ pass def set_window_title(self, title): """ Set the title text of the window containing the figure. Note that this has no effect if there is no window (eg, a PS backend). """ pass # cursors class Cursors: #namespace HAND, POINTER, SELECT_REGION, MOVE = range(4) cursors = Cursors() class NavigationToolbar2: """ Base class for the navigation cursor, version 2 backends must implement a canvas that handles connections for 'button_press_event' and 'button_release_event'. See :meth:`FigureCanvasBase.mpl_connect` for more information They must also define :meth:`save_figure` save the current figure :meth:`set_cursor` if you want the pointer icon to change :meth:`_init_toolbar` create your toolbar widget :meth:`draw_rubberband` (optional) draw the zoom to rect "rubberband" rectangle :meth:`press` (optional) whenever a mouse button is pressed, you'll be notified with the event :meth:`release` (optional) whenever a mouse button is released, you'll be notified with the event :meth:`dynamic_update` (optional) dynamically update the window while navigating :meth:`set_message` (optional) display message :meth:`set_history_buttons` (optional) you can change the history back / forward buttons to indicate disabled / enabled state. That's it, we'll do the rest! """ def __init__(self, canvas): self.canvas = canvas canvas.toolbar = self # a dict from axes index to a list of view limits self._views = cbook.Stack() self._positions = cbook.Stack() # stack of subplot positions self._xypress = None # the location and axis info at the time of the press self._idPress = None self._idRelease = None self._active = None self._lastCursor = None self._init_toolbar() self._idDrag=self.canvas.mpl_connect('motion_notify_event', self.mouse_move) self._button_pressed = None # determined by the button pressed at start self.mode = '' # a mode string for the status bar self.set_history_buttons() def set_message(self, s): 'display a message on toolbar or in status bar' pass def back(self, *args): 'move back up the view lim stack' self._views.back() self._positions.back() self.set_history_buttons() self._update_view() def dynamic_update(self): pass def draw_rubberband(self, event, x0, y0, x1, y1): 'draw a rectangle rubberband to indicate zoom limits' pass def forward(self, *args): 'move forward in the view lim stack' self._views.forward() self._positions.forward() self.set_history_buttons() self._update_view() def home(self, *args): 'restore the original view' self._views.home() self._positions.home() self.set_history_buttons() self._update_view() def _init_toolbar(self): """ This is where you actually build the GUI widgets (called by __init__). The icons ``home.xpm``, ``back.xpm``, ``forward.xpm``, ``hand.xpm``, ``zoom_to_rect.xpm`` and ``filesave.xpm`` are standard across backends (there are ppm versions in CVS also). You just need to set the callbacks home : self.home back : self.back forward : self.forward hand : self.pan zoom_to_rect : self.zoom filesave : self.save_figure You only need to define the last one - the others are in the base class implementation. """ raise NotImplementedError def mouse_move(self, event): #print 'mouse_move', event.button if not event.inaxes or not self._active: if self._lastCursor != cursors.POINTER: self.set_cursor(cursors.POINTER) self._lastCursor = cursors.POINTER else: if self._active=='ZOOM': if self._lastCursor != cursors.SELECT_REGION: self.set_cursor(cursors.SELECT_REGION) self._lastCursor = cursors.SELECT_REGION if self._xypress: x, y = event.x, event.y lastx, lasty, a, ind, lim, trans = self._xypress[0] self.draw_rubberband(event, x, y, lastx, lasty) elif (self._active=='PAN' and self._lastCursor != cursors.MOVE): self.set_cursor(cursors.MOVE) self._lastCursor = cursors.MOVE if event.inaxes and event.inaxes.get_navigate(): try: s = event.inaxes.format_coord(event.xdata, event.ydata) except ValueError: pass except OverflowError: pass else: if len(self.mode): self.set_message('%s : %s' % (self.mode, s)) else: self.set_message(s) else: self.set_message(self.mode) def pan(self,*args): 'Activate the pan/zoom tool. pan with left button, zoom with right' # set the pointer icon and button press funcs to the # appropriate callbacks if self._active == 'PAN': self._active = None else: self._active = 'PAN' if self._idPress is not None: self._idPress = self.canvas.mpl_disconnect(self._idPress) self.mode = '' if self._idRelease is not None: self._idRelease = self.canvas.mpl_disconnect(self._idRelease) self.mode = '' if self._active: self._idPress = self.canvas.mpl_connect( 'button_press_event', self.press_pan) self._idRelease = self.canvas.mpl_connect( 'button_release_event', self.release_pan) self.mode = 'pan/zoom mode' self.canvas.widgetlock(self) else: self.canvas.widgetlock.release(self) for a in self.canvas.figure.get_axes(): a.set_navigate_mode(self._active) self.set_message(self.mode) def press(self, event): 'this will be called whenver a mouse button is pressed' pass def press_pan(self, event): 'the press mouse button in pan/zoom mode callback' if event.button == 1: self._button_pressed=1 elif event.button == 3: self._button_pressed=3 else: self._button_pressed=None return x, y = event.x, event.y # push the current view to define home if stack is empty if self._views.empty(): self.push_current() self._xypress=[] for i, a in enumerate(self.canvas.figure.get_axes()): if x is not None and y is not None and a.in_axes(event) and a.get_navigate(): a.start_pan(x, y, event.button) self._xypress.append((a, i)) self.canvas.mpl_disconnect(self._idDrag) self._idDrag=self.canvas.mpl_connect('motion_notify_event', self.drag_pan) self.press(event) def press_zoom(self, event): 'the press mouse button in zoom to rect mode callback' if event.button == 1: self._button_pressed=1 elif event.button == 3: self._button_pressed=3 else: self._button_pressed=None return x, y = event.x, event.y # push the current view to define home if stack is empty if self._views.empty(): self.push_current() self._xypress=[] for i, a in enumerate(self.canvas.figure.get_axes()): if x is not None and y is not None and a.in_axes(event) \ and a.get_navigate() and a.can_zoom(): self._xypress.append(( x, y, a, i, a.viewLim.frozen(), a.transData.frozen())) self.press(event) def push_current(self): 'push the current view limits and position onto the stack' lims = []; pos = [] for a in self.canvas.figure.get_axes(): xmin, xmax = a.get_xlim() ymin, ymax = a.get_ylim() lims.append( (xmin, xmax, ymin, ymax) ) # Store both the original and modified positions pos.append( ( a.get_position(True).frozen(), a.get_position().frozen() ) ) self._views.push(lims) self._positions.push(pos) self.set_history_buttons() def release(self, event): 'this will be called whenever mouse button is released' pass def release_pan(self, event): 'the release mouse button callback in pan/zoom mode' self.canvas.mpl_disconnect(self._idDrag) self._idDrag=self.canvas.mpl_connect('motion_notify_event', self.mouse_move) for a, ind in self._xypress: a.end_pan() if not self._xypress: return self._xypress = [] self._button_pressed=None self.push_current() self.release(event) self.draw() def drag_pan(self, event): 'the drag callback in pan/zoom mode' for a, ind in self._xypress: #safer to use the recorded button at the press than current button: #multiple button can get pressed during motion... a.drag_pan(self._button_pressed, event.key, event.x, event.y) self.dynamic_update() def release_zoom(self, event): 'the release mouse button callback in zoom to rect mode' if not self._xypress: return last_a = [] for cur_xypress in self._xypress: x, y = event.x, event.y lastx, lasty, a, ind, lim, trans = cur_xypress # ignore singular clicks - 5 pixels is a threshold if abs(x-lastx)<5 or abs(y-lasty)<5: self._xypress = None self.release(event) self.draw() return x0, y0, x1, y1 = lim.extents # zoom to rect inverse = a.transData.inverted() lastx, lasty = inverse.transform_point( (lastx, lasty) ) x, y = inverse.transform_point( (x, y) ) Xmin,Xmax=a.get_xlim() Ymin,Ymax=a.get_ylim() # detect twinx,y axes and avoid double zooming twinx, twiny = False, False if last_a: for la in last_a: if a.get_shared_x_axes().joined(a,la): twinx=True if a.get_shared_y_axes().joined(a,la): twiny=True last_a.append(a) if twinx: x0, x1 = Xmin, Xmax else: if Xmin < Xmax: if x<lastx: x0, x1 = x, lastx else: x0, x1 = lastx, x if x0 < Xmin: x0=Xmin if x1 > Xmax: x1=Xmax else: if x>lastx: x0, x1 = x, lastx else: x0, x1 = lastx, x if x0 > Xmin: x0=Xmin if x1 < Xmax: x1=Xmax if twiny: y0, y1 = Ymin, Ymax else: if Ymin < Ymax: if y<lasty: y0, y1 = y, lasty else: y0, y1 = lasty, y if y0 < Ymin: y0=Ymin if y1 > Ymax: y1=Ymax else: if y>lasty: y0, y1 = y, lasty else: y0, y1 = lasty, y if y0 > Ymin: y0=Ymin if y1 < Ymax: y1=Ymax if self._button_pressed == 1: a.set_xlim((x0, x1)) a.set_ylim((y0, y1)) elif self._button_pressed == 3: if a.get_xscale()=='log': alpha=np.log(Xmax/Xmin)/np.log(x1/x0) rx1=pow(Xmin/x0,alpha)*Xmin rx2=pow(Xmax/x0,alpha)*Xmin else: alpha=(Xmax-Xmin)/(x1-x0) rx1=alpha*(Xmin-x0)+Xmin rx2=alpha*(Xmax-x0)+Xmin if a.get_yscale()=='log': alpha=np.log(Ymax/Ymin)/np.log(y1/y0) ry1=pow(Ymin/y0,alpha)*Ymin ry2=pow(Ymax/y0,alpha)*Ymin else: alpha=(Ymax-Ymin)/(y1-y0) ry1=alpha*(Ymin-y0)+Ymin ry2=alpha*(Ymax-y0)+Ymin a.set_xlim((rx1, rx2)) a.set_ylim((ry1, ry2)) self.draw() self._xypress = None self._button_pressed = None self.push_current() self.release(event) def draw(self): 'redraw the canvases, update the locators' for a in self.canvas.figure.get_axes(): xaxis = getattr(a, 'xaxis', None) yaxis = getattr(a, 'yaxis', None) locators = [] if xaxis is not None: locators.append(xaxis.get_major_locator()) locators.append(xaxis.get_minor_locator()) if yaxis is not None: locators.append(yaxis.get_major_locator()) locators.append(yaxis.get_minor_locator()) for loc in locators: loc.refresh() self.canvas.draw() def _update_view(self): '''update the viewlim and position from the view and position stack for each axes ''' lims = self._views() if lims is None: return pos = self._positions() if pos is None: return for i, a in enumerate(self.canvas.figure.get_axes()): xmin, xmax, ymin, ymax = lims[i] a.set_xlim((xmin, xmax)) a.set_ylim((ymin, ymax)) # Restore both the original and modified positions a.set_position( pos[i][0], 'original' ) a.set_position( pos[i][1], 'active' ) self.draw() def save_figure(self, *args): 'save the current figure' raise NotImplementedError def set_cursor(self, cursor): """ Set the current cursor to one of the :class:`Cursors` enums values """ pass def update(self): 'reset the axes stack' self._views.clear() self._positions.clear() self.set_history_buttons() def zoom(self, *args): 'activate zoom to rect mode' if self._active == 'ZOOM': self._active = None else: self._active = 'ZOOM' if self._idPress is not None: self._idPress=self.canvas.mpl_disconnect(self._idPress) self.mode = '' if self._idRelease is not None: self._idRelease=self.canvas.mpl_disconnect(self._idRelease) self.mode = '' if self._active: self._idPress = self.canvas.mpl_connect('button_press_event', self.press_zoom) self._idRelease = self.canvas.mpl_connect('button_release_event', self.release_zoom) self.mode = 'Zoom to rect mode' self.canvas.widgetlock(self) else: self.canvas.widgetlock.release(self) for a in self.canvas.figure.get_axes(): a.set_navigate_mode(self._active) self.set_message(self.mode) def set_history_buttons(self): 'enable or disable back/forward button' pass
tkaitchuck/nupic
external/linux64/lib/python2.6/site-packages/matplotlib/backend_bases.py
Python
gpl-3.0
69,740
""" pip.vendor is for vendoring dependencies of pip to prevent needing pip to depend on something external. Files inside of pip.vendor should be considered immutable and should only be updated to versions from upstream. """ from __future__ import absolute_import
piyush82/icclab-rcb-web
virtualenv/lib/python2.7/site-packages/pip/vendor/__init__.py
Python
apache-2.0
264
# 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. # ============================================================================== """AffineLinearOperator bijector.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # go/tf-wildcard-import # pylint: disable=wildcard-import from tensorflow.contrib.distributions.python.ops.bijectors.affine_linear_operator_impl import * # pylint: enable=wildcard-import from tensorflow.python.util.all_util import remove_undocumented _allowed_symbols = ["AffineLinearOperator"] remove_undocumented(__name__, _allowed_symbols)
unnikrishnankgs/va
venv/lib/python3.5/site-packages/tensorflow/contrib/distributions/python/ops/bijectors/affine_linear_operator.py
Python
bsd-2-clause
1,182
# Copyright (c) 2007 The Hewlett-Packard Development Company # All rights reserved. # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware implementation of the functionality of the software # licensed hereunder. You may use the software subject to the license # terms below provided that you ensure that this notice is replicated # unmodified and in its entirety in all distributions of the software, # modified or unmodified, in source code or in binary form. # # 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 copyright holders 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. # # Authors: Gabe Black categories = ["convert_floating_point_to_floating_point", "convert_floating_point_to_xmm_integer", "convert_floating_point_to_mmx_integer", "convert_floating_point_to_gpr_integer"] microcode = ''' # SSE instructions ''' for category in categories: exec "import %s as cat" % category microcode += cat.microcode
samueldotj/TeeRISC-Simulator
src/arch/x86/isa/insts/simd128/floating_point/data_conversion/__init__.py
Python
bsd-3-clause
2,483
""" Settings and configuration for Django. Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment variable, and then from django.conf.global_settings; see the global settings file for a list of all possible variables. """ import logging import os import sys import time # Needed for Windows import warnings from django.conf import global_settings from django.core.exceptions import ImproperlyConfigured from django.utils.functional import LazyObject, empty from django.utils import importlib from django.utils.module_loading import import_by_path from django.utils import six ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE" class LazySettings(LazyObject): """ A lazy proxy for either global Django settings or a custom settings object. The user can manually configure settings prior to using them. Otherwise, Django uses the settings module pointed to by DJANGO_SETTINGS_MODULE. """ def _setup(self, name=None): """ Load the settings module pointed to by the environment variable. This is used the first time we need any settings at all, if the user has not previously configured the settings manually. """ try: settings_module = os.environ[ENVIRONMENT_VARIABLE] if not settings_module: # If it's set but is an empty string. raise KeyError except KeyError: desc = ("setting %s" % name) if name else "settings" raise ImproperlyConfigured( "Requested %s, but settings are not configured. " "You must either define the environment variable %s " "or call settings.configure() before accessing settings." % (desc, ENVIRONMENT_VARIABLE)) self._wrapped = Settings(settings_module) self._configure_logging() def __getattr__(self, name): if self._wrapped is empty: self._setup(name) return getattr(self._wrapped, name) def _configure_logging(self): """ Setup logging from LOGGING_CONFIG and LOGGING settings. """ if not sys.warnoptions: try: # Route warnings through python logging logging.captureWarnings(True) # Allow DeprecationWarnings through the warnings filters warnings.simplefilter("default", DeprecationWarning) except AttributeError: # No captureWarnings on Python 2.6, DeprecationWarnings are on anyway pass if self.LOGGING_CONFIG: from django.utils.log import DEFAULT_LOGGING # First find the logging configuration function ... logging_config_func = import_by_path(self.LOGGING_CONFIG) logging_config_func(DEFAULT_LOGGING) # ... then invoke it with the logging settings if self.LOGGING: logging_config_func(self.LOGGING) def configure(self, default_settings=global_settings, **options): """ Called to manually configure the settings. The 'default_settings' parameter sets where to retrieve any unspecified values from (its argument must support attribute access (__getattr__)). """ if self._wrapped is not empty: raise RuntimeError('Settings already configured.') holder = UserSettingsHolder(default_settings) for name, value in options.items(): setattr(holder, name, value) self._wrapped = holder self._configure_logging() @property def configured(self): """ Returns True if the settings have already been configured. """ return self._wrapped is not empty class BaseSettings(object): """ Common logic for settings whether set by a module or by the user. """ def __setattr__(self, name, value): if name in ("MEDIA_URL", "STATIC_URL") and value and not value.endswith('/'): raise ImproperlyConfigured("If set, %s must end with a slash" % name) elif name == "ALLOWED_INCLUDE_ROOTS" and isinstance(value, six.string_types): raise ValueError("The ALLOWED_INCLUDE_ROOTS setting must be set " "to a tuple, not a string.") object.__setattr__(self, name, value) class Settings(BaseSettings): def __init__(self, settings_module): # update this dict from global settings (but only for ALL_CAPS settings) for setting in dir(global_settings): if setting == setting.upper(): setattr(self, setting, getattr(global_settings, setting)) # store the settings module in case someone later cares self.SETTINGS_MODULE = settings_module try: mod = importlib.import_module(self.SETTINGS_MODULE) except ImportError as e: raise ImportError( "Could not import settings '%s' (Is it on sys.path? Is there an import error in the settings file?): %s" % (self.SETTINGS_MODULE, e) ) # Settings that should be converted into tuples if they're mistakenly entered # as strings. tuple_settings = ("INSTALLED_APPS", "TEMPLATE_DIRS") for setting in dir(mod): if setting == setting.upper(): setting_value = getattr(mod, setting) if setting in tuple_settings and \ isinstance(setting_value, six.string_types): warnings.warn("The %s setting must be a tuple. Please fix your " "settings, as auto-correction is now deprecated." % setting, DeprecationWarning, stacklevel=2) setting_value = (setting_value,) # In case the user forgot the comma. setattr(self, setting, setting_value) if not self.SECRET_KEY: raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") if hasattr(time, 'tzset') and self.TIME_ZONE: # When we can, attempt to validate the timezone. If we can't find # this file, no check happens and it's harmless. zoneinfo_root = '/usr/share/zoneinfo' if (os.path.exists(zoneinfo_root) and not os.path.exists(os.path.join(zoneinfo_root, *(self.TIME_ZONE.split('/'))))): raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE) # Move the time zone info into os.environ. See ticket #2315 for why # we don't do this unconditionally (breaks Windows). os.environ['TZ'] = self.TIME_ZONE time.tzset() class UserSettingsHolder(BaseSettings): """ Holder for user configured settings. """ # SETTINGS_MODULE doesn't make much sense in the manually configured # (standalone) case. SETTINGS_MODULE = None def __init__(self, default_settings): """ Requests for configuration variables not in this class are satisfied from the module specified in default_settings (if possible). """ self.__dict__['_deleted'] = set() self.default_settings = default_settings def __getattr__(self, name): if name in self._deleted: raise AttributeError return getattr(self.default_settings, name) def __setattr__(self, name, value): self._deleted.discard(name) return super(UserSettingsHolder, self).__setattr__(name, value) def __delattr__(self, name): self._deleted.add(name) return super(UserSettingsHolder, self).__delattr__(name) def __dir__(self): return list(self.__dict__) + dir(self.default_settings) settings = LazySettings()
edisonlz/fruit
web_project/base/site-packages/django/conf/__init__.py
Python
apache-2.0
7,796
# -*- Mode: Python; -*- # Copyright (c) 2009 INESC Porto # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation; # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Authors: Gustavo Carneiro <gjc@inescporto.pt> import sys import ns.applications import ns.core import ns.flow_monitor import ns.internet import ns.mobility import ns.network import ns.olsr import ns.wifi try: import ns.visualizer except ImportError: pass DISTANCE = 100 # (m) NUM_NODES_SIDE = 3 def main(argv): cmd = ns.core.CommandLine() cmd.NumNodesSide = None cmd.AddValue("NumNodesSide", "Grid side number of nodes (total number of nodes will be this number squared)") cmd.Results = None cmd.AddValue("Results", "Write XML results to file") cmd.Plot = None cmd.AddValue("Plot", "Plot the results using the matplotlib python module") cmd.Parse(argv) wifi = ns.wifi.WifiHelper.Default() wifiMac = ns.wifi.NqosWifiMacHelper.Default() wifiPhy = ns.wifi.YansWifiPhyHelper.Default() wifiChannel = ns.wifi.YansWifiChannelHelper.Default() wifiPhy.SetChannel(wifiChannel.Create()) ssid = ns.wifi.Ssid("wifi-default") wifi.SetRemoteStationManager("ns3::ArfWifiManager") wifiMac.SetType ("ns3::AdhocWifiMac", "Ssid", ns.wifi.SsidValue(ssid)) internet = ns.internet.InternetStackHelper() list_routing = ns.internet.Ipv4ListRoutingHelper() olsr_routing = ns.olsr.OlsrHelper() static_routing = ns.internet.Ipv4StaticRoutingHelper() list_routing.Add(static_routing, 0) list_routing.Add(olsr_routing, 100) internet.SetRoutingHelper(list_routing) ipv4Addresses = ns.internet.Ipv4AddressHelper() ipv4Addresses.SetBase(ns.network.Ipv4Address("10.0.0.0"), ns.network.Ipv4Mask("255.255.255.0")) port = 9 # Discard port(RFC 863) onOffHelper = ns.applications.OnOffHelper("ns3::UdpSocketFactory", ns.network.Address(ns.network.InetSocketAddress(ns.network.Ipv4Address("10.0.0.1"), port))) onOffHelper.SetAttribute("DataRate", ns.network.DataRateValue(ns.network.DataRate("100kbps"))) onOffHelper.SetAttribute("OnTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]")) onOffHelper.SetAttribute("OffTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=0]")) addresses = [] nodes = [] if cmd.NumNodesSide is None: num_nodes_side = NUM_NODES_SIDE else: num_nodes_side = int(cmd.NumNodesSide) for xi in range(num_nodes_side): for yi in range(num_nodes_side): node = ns.network.Node() nodes.append(node) internet.Install(ns.network.NodeContainer(node)) mobility = ns.mobility.ConstantPositionMobilityModel() mobility.SetPosition(ns.core.Vector(xi*DISTANCE, yi*DISTANCE, 0)) node.AggregateObject(mobility) devices = wifi.Install(wifiPhy, wifiMac, node) ipv4_interfaces = ipv4Addresses.Assign(devices) addresses.append(ipv4_interfaces.GetAddress(0)) for i, node in enumerate(nodes): destaddr = addresses[(len(addresses) - 1 - i) % len(addresses)] #print i, destaddr onOffHelper.SetAttribute("Remote", ns.network.AddressValue(ns.network.InetSocketAddress(destaddr, port))) app = onOffHelper.Install(ns.network.NodeContainer(node)) urv = ns.core.UniformRandomVariable() app.Start(ns.core.Seconds(urv.GetValue(20, 30))) #internet.EnablePcapAll("wifi-olsr") flowmon_helper = ns.flow_monitor.FlowMonitorHelper() #flowmon_helper.SetMonitorAttribute("StartTime", ns.core.TimeValue(ns.core.Seconds(31))) monitor = flowmon_helper.InstallAll() monitor = flowmon_helper.GetMonitor() monitor.SetAttribute("DelayBinWidth", ns.core.DoubleValue(0.001)) monitor.SetAttribute("JitterBinWidth", ns.core.DoubleValue(0.001)) monitor.SetAttribute("PacketSizeBinWidth", ns.core.DoubleValue(20)) ns.core.Simulator.Stop(ns.core.Seconds(44.0)) ns.core.Simulator.Run() def print_stats(os, st): print >> os, " Tx Bytes: ", st.txBytes print >> os, " Rx Bytes: ", st.rxBytes print >> os, " Tx Packets: ", st.txPackets print >> os, " Rx Packets: ", st.rxPackets print >> os, " Lost Packets: ", st.lostPackets if st.rxPackets > 0: print >> os, " Mean{Delay}: ", (st.delaySum.GetSeconds() / st.rxPackets) print >> os, " Mean{Jitter}: ", (st.jitterSum.GetSeconds() / (st.rxPackets-1)) print >> os, " Mean{Hop Count}: ", float(st.timesForwarded) / st.rxPackets + 1 if 0: print >> os, "Delay Histogram" for i in range(st.delayHistogram.GetNBins () ): print >> os, " ",i,"(", st.delayHistogram.GetBinStart (i), "-", \ st.delayHistogram.GetBinEnd (i), "): ", st.delayHistogram.GetBinCount (i) print >> os, "Jitter Histogram" for i in range(st.jitterHistogram.GetNBins () ): print >> os, " ",i,"(", st.jitterHistogram.GetBinStart (i), "-", \ st.jitterHistogram.GetBinEnd (i), "): ", st.jitterHistogram.GetBinCount (i) print >> os, "PacketSize Histogram" for i in range(st.packetSizeHistogram.GetNBins () ): print >> os, " ",i,"(", st.packetSizeHistogram.GetBinStart (i), "-", \ st.packetSizeHistogram.GetBinEnd (i), "): ", st.packetSizeHistogram.GetBinCount (i) for reason, drops in enumerate(st.packetsDropped): print " Packets dropped by reason %i: %i" % (reason, drops) #for reason, drops in enumerate(st.bytesDropped): # print "Bytes dropped by reason %i: %i" % (reason, drops) monitor.CheckForLostPackets() classifier = flowmon_helper.GetClassifier() if cmd.Results is None: for flow_id, flow_stats in monitor.GetFlowStats(): t = classifier.FindFlow(flow_id) proto = {6: 'TCP', 17: 'UDP'} [t.protocol] print "FlowID: %i (%s %s/%s --> %s/%i)" % \ (flow_id, proto, t.sourceAddress, t.sourcePort, t.destinationAddress, t.destinationPort) print_stats(sys.stdout, flow_stats) else: print monitor.SerializeToXmlFile(cmd.Results, True, True) if cmd.Plot is not None: import pylab delays = [] for flow_id, flow_stats in monitor.GetFlowStats(): tupl = classifier.FindFlow(flow_id) if tupl.protocol == 17 and tupl.sourcePort == 698: continue delays.append(flow_stats.delaySum.GetSeconds() / flow_stats.rxPackets) pylab.hist(delays, 20) pylab.xlabel("Delay (s)") pylab.ylabel("Number of Flows") pylab.show() return 0 if __name__ == '__main__': sys.exit(main(sys.argv))
mohittahiliani/tcp-eval-suite-ns3
src/flow-monitor/examples/wifi-olsr-flowmon.py
Python
gpl-2.0
7,439
#!/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://pythonhosted.org/setuptools/easy_install.html """ import sys import os import zipimport import shutil import tempfile import zipfile import re import stat import random import platform import textwrap import warnings import site import struct from glob import glob from distutils import log, dir_util from distutils.command.build_scripts import first_line_re import pkg_resources from setuptools import Command, _dont_write_bytecode from setuptools.sandbox import run_setup from setuptools.py31compat import get_path, get_config_vars 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 setuptools.command import setopt from setuptools.archive_util import unpack_archive from setuptools.package_index import PackageIndex from setuptools.package_index import URL_SCHEME from setuptools.command import bdist_egg, egg_info from setuptools.compat import (iteritems, maxsize, basestring, unicode, reraise) 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, ) sys_executable = os.environ.get('__PYVENV_LAUNCHER__', os.path.normpath(sys.executable)) __all__ = [ 'samefile', 'easy_install', 'PthDistributions', 'extract_wininst_cfg', 'main', 'get_exe_prefixes', ] def is_64bit(): return struct.calcsize("P") == 8 def samefile(p1, p2): 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 sys.version_info <= (3,): def _to_ascii(s): return s def isascii(s): try: unicode(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 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): if site.ENABLE_USER_SITE: whereami = os.path.abspath(__file__) self.user = whereami.startswith(site.USER_SITE) else: 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): for filename in blockers: if os.path.exists(filename) or os.path.islink(filename): log.info("Deleting %s", filename) if not self.dry_run: if os.path.isdir(filename) and not os.path.islink(filename): rmtree(filename) else: os.unlink(filename) def finalize_options(self): if self.version: print('setuptools %s' % get_distribution('setuptools').version) sys.exit() 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 # fix the install_dir if "--user" was used #XXX: duplicate of the code in the setup command if self.user and site.ENABLE_USER_SITE: self.create_home_path() if self.install_userbase is None: raise DistutilsPlatformError( "User base directory is not specified") self.install_base = self.install_platbase = self.install_userbase if os.name == 'posix': self.select_scheme("unix_user") else: self.select_scheme(os.name + "_user") 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, basestring): 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 _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.""" self._expand_attrs(['install_purelib', 'install_platlib', 'install_lib', 'install_headers', 'install_scripts', 'install_data',]) 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: pid = random.randint(0, 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 PYTHONPATH = os.environ.get('PYTHONPATH','').split(os.pathsep) if instdir not in map(normalize_path, [_f for _f in PYTHONPATH if _f]): # 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 def cant_write_to_target(self): template = """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 """ msg = template % (sys.exc_info()[1], self.install_dir,) if not os.path.exists(self.install_dir): msg += """ 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). """ else: msg += """ 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://pythonhosted.org/setuptools/easy_install.html Please make the appropriate changes for your system and try again. """ 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) try: if ok_exists: os.unlink(ok_file) dirname = os.path.dirname(ok_file) if not os.path.exists(dirname): os.makedirs(dirname) f = open(pth_file,'w') except (OSError,IOError): self.cant_write_to_target() else: try: f.write("import os; f = open(%r, 'w'); f.write('OK'); f.close()\n" % (ok_file,)) f.close() f=None executable = sys.executable if os.name=='nt': dirname,basename = os.path.split(executable) alt = os.path.join(dirname,'pythonw.exe') if basename.lower()=='python.exe' and os.path.exists(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) ) def easy_install(self, spec, deps=False): tmpdir = tempfile.mkdtemp(prefix="easy_install-") download = None if not self.editable: self.install_site_py() try: if not isinstance(spec,Requirement): if URL_SCHEME(spec): # It's a url, download it to tmpdir and process self.not_editable(spec) download = self.package_index.download(spec, tmpdir) return self.install_item(None, download, 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) finally: if os.path.exists(tmpdir): rmtree(tmpdir) 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) # First remove the dist from self.local_index, to avoid problems using # old cached data in case its underlying file has been replaced. # # This is a quick-fix for a zipimporter caching issue in case the dist # has been implemented as and already loaded from a zip file that got # replaced later on. For more detailed information see setuptools issue # #168 at 'http://bitbucket.org/pypa/setuptools/issue/168'. 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 or distreq requirement = Requirement( distreq.project_name, distreq.specs, requirement.extras ) log.info("Processing dependencies for %s", requirement) try: distros = WorkingSet([]).resolve( [requirement], self.local_index, self.easy_install ) except DistributionNotFound: e = sys.exc_info()[1] raise DistutilsError( "Could not find required distribution %s" % e.args ) except VersionConflict: e = sys.exc_info()[1] raise DistutilsError( "Installed distribution %s conflicts with requirement %s" % e.args ) 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 not self.exclude_scripts: for args in get_script_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) def get_template(filename): """ There are a couple of template scripts in the package. This function loads one of them and prepares it for use. These templates use triple-quotes to escape variable substitutions so the scripts get the 2to3 treatment when build on Python 3. The templates cannot use triple-quotes naturally. """ raw_bytes = resource_string('setuptools', template_name) template_str = raw_bytes.decode('utf-8') clean_template = template_str.replace('"""', '') return clean_template if is_script: # See https://bitbucket.org/pypa/setuptools/issue/134 for info # on script file naming and downstream issues with SVR4 template_name = 'script template.py' if dev_path: template_name = template_name.replace('.py', ' (dev).py') script_text = (get_script_header(script_text) + get_template(template_name) % locals()) self.write_script(script_name, _to_ascii(script_text), 'b') 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) f = open(target,"w"+mode) f.write(contents) f.close() 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) uncache_zipdir(destination) 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" elif 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))) 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 = dist.location = os.path.join(tmpdir, dist.egg_name()+'.egg') 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') self.delete_blockers( # delete entry-point scripts to avoid duping [os.path.join(script_dir,args[0]) for args in get_script_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() 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 += """ 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 """ if self.install_dir not in map(normalize_path,sys.path): msg += """ 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.) """ eggloc = dist.location name = dist.project_name version = dist.version extras = '' # TODO: self.report_extras(req, dist) return msg % locals() def report_editable(self, spec, setup_script): dirname = os.path.dirname(setup_script) python = sys.executable return """\nExtracted 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. """ % 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: v = sys.exc_info()[1] 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 _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 def no_default_version_msg(self): template = """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://pythonhosted.org/setuptools/easy_install.html#custom-installation-locations Please make the appropriate changes for your system and try again.""" 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") current = "" if os.path.exists(sitepy): log.debug("Checking existing site.py in %s", self.install_dir) f = open(sitepy,'rb') current = f.read() # we want str, not bytes if sys.version_info >= (3,): current = current.decode() f.close() 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) f = open(sitepy,'wb') f.write(source) f.close() 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 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 get_site_dirs(): # return a list of 'site' dirs sitedirs = [_f for _f in os.environ.get('PYTHONPATH', '').split(os.pathsep) if _f] 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: sitedirs.append( os.path.join(home, 'Library', 'Python', sys.version[:3], 'site-packages')) 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) 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) from setuptools.compat import StringIO, ConfigParser import struct 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)) cfg = ConfigParser.RawConfigParser({'version':'','target_version':''}) try: part = f.read(cfglen) # part is in bytes, but we need to read up to the first null # byte. if sys.version_info >= (2,6): null_byte = bytes([0]) else: null_byte = chr(0) config = part.split(null_byte, 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(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 sys.version_info >= (3,): 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 def parse_requirement_arg(spec): try: return Requirement.parse(spec) except ValueError: raise DistutilsError( "Not a URL, existing file, or requirement spec: %r" % (spec,) ) 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 data = '\n'.join(map(self.make_relative,self.paths)) if data: log.debug("Saving %s", self.filename) data = ( "import sys; sys.__plen = len(sys.path)\n" "%s\n" "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)\n" ) % data if os.path.islink(self.filename): os.unlink(self.filename) f = open(self.filename,'wt') f.write(data) f.close() elif os.path.exists(self.filename): log.debug("Deleting empty %s", self.filename) os.unlink(self.filename) self.dirty = False def add(self, dist): """Add `dist` to the distribution map""" if (dist.location not in self.paths and ( dist.location not in self.sitedirs or dist.location == os.getcwd() # account for '.' being in PYTHONPATH )): 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 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 get_script_header(script_text, executable=sys_executable, wininst=False): """Create a #! line, getting options (if any) from script_text""" first = (script_text+'\n').splitlines()[0] match = _first_line_re().match(first) options = '' if match: options = match.group(1) or '' if options: options = ' '+options if wininst: executable = "python.exe" else: executable = nt_quote_arg(executable) hdr = "#!%(executable)s%(options)s\n" % locals() if not isascii(hdr): # Non-ascii path to sys.executable, use -x to prevent warnings if options: if options.strip().startswith('-'): options = ' -x'+options.strip()[1:] # else: punt, we can't do it, let the warning happen anyway else: options = ' -x' executable = fix_jython_executable(executable, options) hdr = "#!%(executable)s%(options)s\n" % locals() return hdr def auto_chmod(func, arg, exc): if func is os.remove and os.name=='nt': chmod(arg, stat.S_IWRITE) return func(arg) et, ev, _ = sys.exc_info() reraise(et, (ev[0], ev[1] + (" %s %s" % (func,arg)))) def uncache_zipdir(path): """ Remove any globally cached zip file related data for `path` Stale zipimport.zipimporter objects need to be removed when a zip file is replaced as they contain cached zip file directory information. If they are asked to get data from their zip file, they will use that cached information to calculate the data location in the zip file. This calculated location may be incorrect for the replaced zip file, which may in turn cause the read operation to either fail or return incorrect data. Note we have no way to clear any local caches from here. That is left up to whomever is in charge of maintaining that cache. """ normalized_path = normalize_path(path) _uncache(normalized_path, zipimport._zip_directory_cache) _uncache(normalized_path, sys.path_importer_cache) def _uncache(normalized_path, cache): to_remove = [] 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, '')): to_remove.append(p) for p in to_remove: del cache[p] 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: fp = open(executable) magic = fp.read(2) fp.close() except (OSError,IOError): return executable return magic == '#!' def nt_quote_arg(arg): """Quote a command line argument according to Windows parsing rules""" result = [] needquote = False nb = 0 needquote = (" " in arg) or ("\t" in arg) if needquote: result.append('"') for c in arg: if c == '\\': nb += 1 elif c == '"': # double preceding backslashes, then add a \" result.append('\\' * (nb*2) + '\\"') nb = 0 else: if nb: result.append('\\' * nb) nb = 0 result.append(c) if nb: result.append('\\' * nb) if needquote: result.append('\\' * nb) # double the trailing backslashes result.append('"') return ''.join(result) 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: e = sys.exc_info()[1] log.debug("chmod failed: %s", e) def fix_jython_executable(executable, options): if sys.platform.startswith('java') and is_sh(executable): # Workaround for Jython is not needed on Linux systems. import java if java.lang.System.getProperty("os.name") == "Linux": return executable # Workaround Jython's sys.executable being a .sh (an invalid # shebang line interpreter) if options: # Can't apply the workaround, leave it broken log.warn( "WARNING: Unable to adapt shebang line for Jython," " the following script is NOT executable\n" " see http://bugs.jython.org/issue1112 for" " more information.") else: return '/usr/bin/env %s' % executable return executable class ScriptWriter(object): """ Encapsulates behavior around writing entry point scripts for console and gui apps. """ template = textwrap.dedent(""" # EASY-INSTALL-ENTRY-SCRIPT: %(spec)r,%(group)r,%(name)r __requires__ = %(spec)r import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.exit( load_entry_point(%(spec)r, %(group)r, %(name)r)() ) """).lstrip() @classmethod def get_script_args(cls, dist, executable=sys_executable, wininst=False): """ Yield write_script() argument tuples for a distribution's entrypoints """ gen_class = cls.get_writer(wininst) spec = str(dist.as_requirement()) header = get_script_header("", executable, wininst) for type_ in 'console', 'gui': group = type_ + '_scripts' for name, ep in dist.get_entry_map(group).items(): script_text = gen_class.template % locals() for res in gen_class._get_script_args(type_, name, header, script_text): yield res @classmethod def get_writer(cls, force_windows): if force_windows or sys.platform=='win32': return WindowsScriptWriter.get_writer() 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) class WindowsScriptWriter(ScriptWriter): @classmethod def get_writer(cls): """ Get a script writer 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(';'): warnings.warn("%s not listed in PATHEXT; scripts will not be " "recognized as executables." % ext, 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 @staticmethod def _adjust_header(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) clean_header = new_header[2:-1].strip('"') if sys.platform == 'win32' and not os.path.exists(clean_header): # the adjusted version doesn't exist, so return the original return orig_header return new_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 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 platform.machine().lower()=='arm': launcher_fn = launcher_fn.replace(".", "-arm.") 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 sys.version_info[0] < 3: return manifest % vars() else: return manifest.decode('utf-8') % vars() def rmtree(path, ignore_errors=False, onerror=auto_chmod): """Recursively delete a directory tree. This code is taken from the Python 2.4 version of 'shutil', because the 2.3 version doesn't really work right. """ if ignore_errors: def onerror(*args): pass elif onerror is None: def onerror(*args): raise names = [] try: names = os.listdir(path) except os.error: onerror(os.listdir, path, sys.exc_info()) for name in names: fullname = os.path.join(path, name) try: mode = os.lstat(fullname).st_mode except os.error: mode = 0 if stat.S_ISDIR(mode): rmtree(fullname, ignore_errors, onerror) else: try: os.remove(fullname) except os.error: onerror(os.remove, fullname, sys.exc_info()) try: os.rmdir(path) except os.error: onerror(os.rmdir, path, sys.exc_info()) 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 import distutils.core USAGE = """\ usage: %(script)s [options] requirement_or_url ... or: %(script)s --help """ def gen_usage(script_name): return USAGE % dict( script=os.path.basename(script_name), ) def with_ei_usage(f): old_gen_usage = distutils.core.gen_usage try: distutils.core.gen_usage = gen_usage return f() finally: distutils.core.gen_usage = old_gen_usage class DistributionWithoutHelpCommands(Distribution): common_usage = "" def _show_help(self,*args,**kw): with_ei_usage(lambda: Distribution._show_help(self,*args,**kw)) if argv is None: argv = sys.argv[1:] with_ei_usage(lambda: setup( script_args = ['-q','easy_install', '-v']+argv, script_name = sys.argv[0] or 'easy_install', distclass=DistributionWithoutHelpCommands, **kw ) )
cortext/crawtextV2
~/venvs/crawler/lib/python2.7/site-packages/setuptools/command/easy_install.py
Python
mit
74,243
# -*- coding: utf-8 -*- from . import project
sergiocorato/project-service
service_desk_issue/__init__.py
Python
agpl-3.0
46
# -*- coding: utf-8 -*- """ Test for matlab problems """ import time from ...pages.lms.matlab_problem import MatlabProblemPage from ...fixtures.course import XBlockFixtureDesc from ...fixtures.xqueue import XQueueResponseFixture from .test_lms_problems import ProblemsTest from textwrap import dedent class MatlabProblemTest(ProblemsTest): """ Tests that verify matlab problem "Run Code". """ def get_problem(self): """ Create a matlab problem for the test. """ problem_data = dedent(""" <problem markdown="null"> <text> <p> Write MATLAB code to create the following row vector and store it in a variable named <code>V</code>. </p> <table id="a0000000466" class="equation" width="100%" cellspacing="0" cellpadding="7" style="table-layout:auto"> <tr> <td class="equation">[1 1 2 3 5 8 13]</td> </tr> </table> <p> <coderesponse queuename="matlab"> <matlabinput rows="10" cols="40" mode="" tabsize="4"> <plot_payload> </plot_payload> </matlabinput> <codeparam> <initial_display/> <answer_display> </answer_display> <grader_payload> </grader_payload> </codeparam> </coderesponse> </p> </text> </problem> """) return XBlockFixtureDesc('problem', 'Test Matlab Problem', data=problem_data) def _goto_matlab_problem_page(self): """ Open matlab problem page with assertion. """ self.courseware_page.visit() matlab_problem_page = MatlabProblemPage(self.browser) self.assertEqual(matlab_problem_page.problem_name, 'TEST MATLAB PROBLEM') return matlab_problem_page def test_run_code(self): """ Test "Run Code" button functionality. """ # Enter a submission, which will trigger a pre-defined response from the XQueue stub. self.submission = "a=1" + self.unique_id[0:5] self.xqueue_grade_response = {'msg': self.submission} matlab_problem_page = self._goto_matlab_problem_page() # Configure the XQueue stub's response for the text we will submit if self.xqueue_grade_response is not None: XQueueResponseFixture(self.submission, self.xqueue_grade_response).install() matlab_problem_page.set_response(self.submission) matlab_problem_page.click_run_code() self.assertEqual( u'Submitted. As soon as a response is returned, this message will be replaced by that feedback.', matlab_problem_page.get_grader_msg(".external-grader-message")[0] ) # Wait 5 seconds for xqueue stub server grader response sent back to lms. time.sleep(5) self.assertEqual(u'', matlab_problem_page.get_grader_msg(".external-grader-message")[0]) self.assertEqual( self.xqueue_grade_response.get("msg"), matlab_problem_page.get_grader_msg(".ungraded-matlab-result")[0] )
MakeHer/edx-platform
common/test/acceptance/tests/lms/test_lms_matlab_problem.py
Python
agpl-3.0
3,475
import re import json import logging import random import venusian from collections import namedtuple from collections import OrderedDict from zope.interface import providedBy, Interface from pyramid.compat import string_types from pyramid.config.views import DefaultViewMapper from pyramid.location import lineage from pyramid.registry import Introspectable from pyramid.renderers import RendererHelper from pyramid.interfaces import IRequest, IRouteRequest from pyramid.tweens import EXCVIEW log = logging.getLogger('djed.layout') LAYOUT_ID = 'djed:layout' LayoutInfo = namedtuple( 'LayoutInfo', 'name layout view original renderer intr') CodeInfo = namedtuple( 'Codeinfo', 'filename lineno function source module') class ILayout(Interface): """ marker interface """ def query_layout(root, context, request, name=''): """ query named layout for context """ assert IRequest.providedBy(request), "must pass in a request object" try: iface = request.request_iface except AttributeError: iface = IRequest root = providedBy(root) adapters = request.registry.adapters for context in lineage(context): layout_factory = adapters.lookup( (root, iface, providedBy(context)), ILayout, name=name) if layout_factory is not None: return layout_factory, context return None, None def query_layout_chain(root, context, request, layoutname=''): chain = [] layout, layoutcontext = query_layout(root, context, request, layoutname) if layout is None: return chain chain.append((layout, layoutcontext)) contexts = {layoutname: layoutcontext} while layout is not None and layout.layout is not None: if layout.layout in contexts: l_context = contexts[layout.layout].__parent__ else: l_context = context layout, layoutcontext = query_layout( root, l_context, request, layout.layout) if layout is not None: chain.append((layout, layoutcontext)) contexts[layout.name] = layoutcontext if layout.layout is None: break return chain def add_layout(cfg, name='', context=None, root=None, parent=None, renderer=None, route_name=None, use_global_views=True, view=None): """Registers a layout. :param name: Layout name :param context: Specific context for this layout. :param root: Root object :param parent: A parent layout. None means no parent layout. :param renderer: A pyramid renderer :param route_name: A pyramid route_name. Apply layout only for specific route :param use_global_views: Apply layout to all routes. even is route doesnt use use_global_views. :param view: View callable """ discr = (LAYOUT_ID, name, context, route_name) intr = Introspectable(LAYOUT_ID, discr, name, 'djed:layout') intr['name'] = name intr['context'] = context intr['root'] = root intr['renderer'] = renderer intr['route_name'] = route_name intr['parent'] = parent intr['use_global_views'] = use_global_views intr['view'] = view if not parent: parent = None elif parent == '.': parent = '' if isinstance(renderer, string_types): renderer = RendererHelper(name=renderer, registry=cfg.registry) if context is None: context = Interface def register(): request_iface = IRequest if route_name is not None: request_iface = cfg.registry.getUtility( IRouteRequest, name=route_name) if use_global_views: request_iface = Interface mapper = getattr(view, '__view_mapper__', DefaultViewMapper) mapped_view = mapper()(view) info = LayoutInfo(name, parent, mapped_view, view, renderer, intr) cfg.registry.registerAdapter( info, (root, request_iface, context), ILayout, name) cfg.action(discr, register, introspectables=(intr,)) class LayoutRenderer(object): def __init__(self, layout): self.layout = layout def layout_info(self, layout, context, request, content): intr = layout.intr view = intr['view'] if view is not None: layout_factory = '%s.%s'%(view.__module__, view.__name__) else: layout_factory = 'None' data = OrderedDict( (('name', intr['name']), ('parent-layout', intr['parent']), ('layout-factory', layout_factory), ('renderer', intr['renderer']), ('context', '%s.%s'%(context.__class__.__module__, context.__class__.__name__)), ('context-path', request.resource_url(context)), )) html = re.search('<html\.*>', content) color = random.randint(0,0xFFFFFF) if html: pos = html.end() - 1 content = ('{0} style="border: 2px solid #{1:06x}" title="{2}"' '{3}').format(content[:pos], color, data['name'], content[pos:]) else: content = ('<div style="border: 2px solid #{0:06x}" title="{1}">' '{2}</div>').format(color, data['name'], content) content = '\n<!-- layout:\n{0} \n-->\n{1}'.format( json.dumps(data, indent=2), content) return content def __call__(self, content, context, request): chain = query_layout_chain(request.root, context, request, self.layout) if not chain: log.warning( "Can't find layout '%s' for context '%s'", self.layout, context) return content value = request.layout_data for layout, layoutcontext in chain: if layout.view is not None: vdata = layout.view(layoutcontext, request) if vdata is not None: value.update(vdata) system = {'view': getattr(request, '__view__', None), 'renderer_info': layout.renderer, 'context': layoutcontext, 'request': request, 'content': content, 'wrapped_content': content} content = layout.renderer.render(value, system, request) if request.registry.settings.get('djed.layout.debug'): content = self.layout_info( layout, layoutcontext, request, content) return content def set_layout_data(request, **kw): request.layout_data.update(kw) class layout_config(object): def __init__(self, name='', context=None, root=None, parent=None, renderer=None, route_name=None, use_global_views=True): self.name = name self.context = context self.root = root self.parent = parent self.renderer = renderer self.route_name = route_name self.use_global_views = use_global_views def __call__(self, wrapped): def callback(context, name, ob): cfg = context.config.with_package(info.module) add_layout(cfg, self.name, self.context, self.root, self.parent, self.renderer, self.route_name, self.use_global_views, ob) info = venusian.attach(wrapped, callback, category='djed:layout') return wrapped class layout_tween_factory(object): def __init__(self, handler, registry): self.handler = handler self.registry = registry def __call__(self, request): response = self.handler(request) layout_name = getattr(request, 'layout', None) if layout_name: layout = LayoutRenderer(layout_name) response.text = layout(response.text, request.context, request) return response class layout_predicate_factory(object): def __init__(self, val, config): self.val = val def text(self): return 'layout = %s' % (self.val,) phash = text def __call__(self, context, request): request.layout = self.val return True def includeme(config): from pyramid.settings import asbool settings = config.registry.settings settings['djed.layout.debug'] = asbool(settings.get( 'djed.layout.debug', 'f')) config.add_tween('djed.layout.layout_tween_factory', over=EXCVIEW) config.add_view_predicate('layout', layout_predicate_factory) config.add_directive('add_layout', add_layout) config.add_request_method(set_layout_data, 'set_layout_data') def get_layout_data(request): return {} config.add_request_method(get_layout_data, 'layout_data', True, True)
djedproject/djed.layout
djed/layout/__init__.py
Python
isc
8,833
import pytest from tests.utils.targetdriver import TargetDriver, if_feature from tests.utils.testdriver import TestDriver def get_services(): return TargetDriver('rep1'), TestDriver('rep2') @pytest.fixture(autouse=True) def _(module_launcher_launch): pass @if_feature.copy_file_from_onitu def test_driver_copy_from_onitu(module_launcher): d_target, d_test = module_launcher.get_services('rep1', 'rep2') module_launcher.copy_file('default', 'copy1', 100, d_test, d_target) @if_feature.copy_file_to_onitu def test_driver_copy_to_onitu(module_launcher): d_target, d_test = module_launcher.get_services('rep1', 'rep2') module_launcher.copy_file('default', 'copy2', 100, d_target, d_test)
onitu/onitu
tests/functional/driver/test_driver_copy.py
Python
mit
717
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-07-03 13:45 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('frontend', '0001_initial'), ] operations = [ migrations.AlterField( model_name='frontenddeployment', name='deployed_at', field=models.DateTimeField(auto_now=True), ), ]
sussexstudent/falmer
falmer/frontend/migrations/0002_auto_20170703_1345.py
Python
mit
462
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import itertools import os import sys try: from urllib import quote_plus, urlencode from urlparse import parse_qsl, urlparse, urlunparse except ImportError: from urllib.parse import parse_qsl, quote_plus, urlencode, urlparse, urlunparse ERR_INVALID_PAIR = 3 def parse(args, data): url = urlparse(data) query = url.query if not args.no_query_params: query = parse_qsl(url.query) return url, query def build_authority(username, password, hostname, port): netloc = hostname if username or password: auth = username + ':' + password netloc = auth + '@' + netloc if port: netloc += ':' + port return netloc def process(args, url, query): scheme = args.scheme or url.scheme username = args.username or (url.username or '') password = args.password or (url.password or '') hostname = args.hostname or (url.hostname or '') port = str(args.port or (url.port or '')) params = args.params or url.params fragment = args.fragment or url.fragment authority = build_authority(username, password, hostname, port) path = url.path if args.path: if args.path.startswith('/'): path = args.path else: path = os.path.join(url.path, args.path) path = os.path.normpath(path) if args.no_query_params: if args.query: query = args.query if args.queries: query += ''.join(args.queries) if args.no_url_encoding: encoded_query = query else: encoded_query = quote_plus(query) else: if args.query: query = parse_qsl(args.query) if args.queries: query.extend(p.split('=', 2) for p in args.queries) query = [(q, v) for q, v in query if q not in args.ignored_queries] if args.sort_query: query = sorted(query, key=lambda p: p[0]) if args.no_url_encoding: encoded_query = '&'.join('='.join(p) for p in query) else: encoded_query = urlencode(query) suppress_default = False if args.print_scheme: suppress_default = True yield scheme if args.print_username: suppress_default = True yield username if args.print_password: suppress_default = True yield password if args.print_hostname: suppress_default = True yield hostname if args.print_port: suppress_default = True yield port if args.print_authority: suppress_default = True yield authority if args.print_path: suppress_default = True yield path if args.print_params: suppress_default = True yield params if args.print_query: suppress_default = True yield encoded_query if args.query_value and not args.no_query_params: suppress_default = True # Would be nice to make `query_map` a defaultdict, but that would # restrict this program to newer Python versions. query_map = {} for q, v in query: if q not in query_map: query_map[q] = [] query_map[q].append(v) for q in args.query_value: for v in query_map.get(q, ['']): yield v if args.print_query_names and not args.no_query_params: suppress_default = True for q in query: yield q[0] if args.print_query_values and not args.no_query_params: suppress_default = True for q in query: yield q[1] if args.print_fragment: suppress_default = True yield fragment if not suppress_default: yield urlunparse((scheme, authority, path, params, encoded_query, fragment)) def main(): ap = argparse.ArgumentParser(description='extract and modify URL features') # URL-printing options ap.add_argument('-s', '--print-scheme', action='store_true', dest='print_scheme', help="print scheme") ap.add_argument('-u', '--print-username', action='store_true', dest='print_username', help="print username") ap.add_argument('-w', '--print-password', action='store_true', dest='print_password', help="print password") ap.add_argument('-o', '--print-hostname', action='store_true', dest='print_hostname', help="print hostname") ap.add_argument('-p', '--print-port', action='store_true', dest='print_port', help="print port") ap.add_argument('-a', '--print-authority', action='store_true', dest='print_authority', help="print authority") ap.add_argument('-d', '--print-path', action='store_true', dest='print_path', help="print path") ap.add_argument( '--print-params', action='store_true', dest='print_params', help="print params") ap.add_argument('-q', '--print-query', action='store_true', dest='print_query', help="print query string") ap.add_argument( '--print-query-names', action='store_true', dest='print_query_names', help="print only query parameter names") ap.add_argument( '--print-query-values', action='store_true', dest='print_query_values', help="print only query parameter values") ap.add_argument('-f', '--print-fragment', action='store_true', dest='print_fragment', help="print fragment") ap.add_argument('-g', '--print-query-value', action='append', metavar='QUERY', dest='query_value', help="print value of query parameter") # URL-mutating options ap.add_argument('-S', '--scheme', action='store', dest='scheme', help="set scheme") ap.add_argument('-U', '--username', action='store', dest='username', help="set username") ap.add_argument('-W', '--password', action='store', dest='password', help="set password") ap.add_argument('-O', '--hostname', action='store', dest='hostname', help="set hostname") ap.add_argument('-P', '--port', action='store', dest='port', help="set port") ap.add_argument('-D', '--path', action='store', dest='path', help="set or append path") ap.add_argument( '--params', action='store', dest='params', help="set params") ap.add_argument( '--query', action='store', dest='query', help="set query") ap.add_argument('-Q', '--append-query', metavar='NAME=VALUE', action='append', dest='queries', default=[], help="append query parameter") ap.add_argument('-F', '--fragment', action='store', dest='fragment', help="set fragment") # Behavior-modifying options ap.add_argument( '--no-url-encoding', action='store_true', help="disable URL encoding") ap.add_argument( '--no-query-params', action='store_true', help="disable query parameter parsing") ap.add_argument( '--sort-query', action='store_true', help="sort printed query parameters by name") ap.add_argument('-x', '--ignore-query', action='append', dest='ignored_queries', metavar='QUERY', default=[], help="ignore query parameter") ap.add_argument( '--version', action='version', version='%(prog)s 0.1.1') # Positional arguments ap.add_argument('urls', nargs='*', metavar='URL') args = ap.parse_args() for pair in args.queries: if '=' not in pair: sys.stderr.write("invalid name=value pair: {}\n".format(pair)) sys.exit(ERR_INVALID_PAIR) # Use the field and record separators from the environment ofs = os.environ.get('OFS', ' ') rs = os.environ.get('RS', '\n') inputs = [] if not sys.stdin.isatty(): inputs.append(sys.stdin) inputs.append(args.urls) for line in itertools.chain(*inputs): url, query = parse(args, line.strip()) output = process(args, url, query) sys.stdout.write(ofs.join(output)) sys.stdout.write(rs) if __name__ == '__main__': main()
jdp/urp
urp.py
Python
mit
7,836
#!/usr/bin/python # -*- coding: utf-8 -*- from DataApi_32 import CDataProcess #from DataApi_Linux import CDataApi import datetime def main(): #HOST = '192.168.1.186' HOST = '180.166.168.126' #公网ip PORT = 18201 subStock = ["999999"] ApiInstance = CDataProcess(HOST,PORT, False, subStock, 0,1,datetime.datetime(2012,1,1,0,0,0),datetime.datetime(2012,01,1,0,0,0) ) ApiInstance.run() pass if __name__ == '__main__': main()
sharmaking/DataApi
demo_32.py
Python
mit
439
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class SecurityRuleAssociations(Model): """All security rules associated with the network interface. :param network_interface_association: :type network_interface_association: ~azure.mgmt.network.v2016_09_01.models.NetworkInterfaceAssociation :param subnet_association: :type subnet_association: ~azure.mgmt.network.v2016_09_01.models.SubnetAssociation :param default_security_rules: Collection of default security rules of the network security group. :type default_security_rules: list[~azure.mgmt.network.v2016_09_01.models.SecurityRule] :param effective_security_rules: Collection of effective security rules. :type effective_security_rules: list[~azure.mgmt.network.v2016_09_01.models.EffectiveNetworkSecurityRule] """ _attribute_map = { 'network_interface_association': {'key': 'networkInterfaceAssociation', 'type': 'NetworkInterfaceAssociation'}, 'subnet_association': {'key': 'subnetAssociation', 'type': 'SubnetAssociation'}, 'default_security_rules': {'key': 'defaultSecurityRules', 'type': '[SecurityRule]'}, 'effective_security_rules': {'key': 'effectiveSecurityRules', 'type': '[EffectiveNetworkSecurityRule]'}, } def __init__(self, **kwargs): super(SecurityRuleAssociations, self).__init__(**kwargs) self.network_interface_association = kwargs.get('network_interface_association', None) self.subnet_association = kwargs.get('subnet_association', None) self.default_security_rules = kwargs.get('default_security_rules', None) self.effective_security_rules = kwargs.get('effective_security_rules', None)
lmazuel/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2016_09_01/models/security_rule_associations.py
Python
mit
2,182
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "devproject.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django # noqa: F401 except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
philgyford/django-spectator
devproject/manage.py
Python
mit
822
from amon.apps.core.basemodel import BaseModel class BaseDeviceModel(BaseModel): def __init__(self): super(BaseDeviceModel, self).__init__() self.collection = self.mongo.get_collection(self.collection_name) # Pylint displays errors for undefined self, it actually works fine def get_by_name(self, server=None, name=None): server_id = server['_id'] params = {'name': name, 'server_id': server_id} result = self.collection.find_one(params) return result def get_or_create(self, server_id=None, name=None): params = {"server_id": server_id, "name": name} result = super(BaseDeviceModel, self).get_or_create(params) self.collection.ensure_index([('server_id', self.desc)], background=True) return result def get_data_collection(self, server_id=None): data_collection_name = "{0}_data".format(self.device_type) collection = self.mongo.get_collection(data_collection_name) return collection def get_all_for_servers_list(self, servers=None): server_ids_list = [self.object_id(x.get('_id')) for x in servers] result = self.collection.find({"server_id": {"$in": server_ids_list}}) return result def get_all_for_server(self, server_id=None): result = None server_id = self.object_id(server_id) if server_id: result = self.collection.find({"server_id": server_id}) return result def get_check_for_timestamp(self, server, timestamp): result_dict = {} server_id = server['_id'] devices = self.get_all_for_server(server_id=server_id) data_collection = self.get_data_collection(server_id=server_id) if devices: for device in devices: params = {'device_id':device['_id'], 't': timestamp} result_dict[device.get('name')] = data_collection.find_one(params) return result_dict def save_data(self, server=None, data=None, time=None, expires_at=None): server_id = server['_id'] valid_devices = [] # New golang agent if type(data) == list: formated_data = {} for d in data: name = d.get('name') valid_devices.append(name) formated_data[name] = d # Legacy agent else: formated_data = data try: device_list = formated_data.keys() except: device_list = [] valid_devices = filter(lambda x: x not in ['time','last','lo'], device_list) for device in valid_devices: device_object = self.get_or_create(server_id=server_id, name=device) device_id = device_object.get('_id') try: device_data = formated_data[device] except: device_data = None if device_data: device_data['t'] = time device_data["expires_at"] = expires_at device_data['device_id'] = device_id device_data['server_id'] = server_id if hasattr(self, "compressed_keys"): device_data = self.rename_keys(device_data, self.compressed_keys) try: del device_data['_id'] except: pass self.update({'last_update': time}, device_id) collection = self.get_data_collection(server_id=server_id) collection.insert(device_data) collection.ensure_index([('t', self.desc)], background=True) collection.ensure_index([('device_id', self.desc)], background=True) collection.ensure_index([('server_id', self.desc)], background=True) collection.ensure_index([('expires_at', 1)], expireAfterSeconds=0) class InterfacesModel(BaseDeviceModel): def __init__(self): self.device_type = 'interface' self.collection_name = 'interfaces' self.compressed_keys = {'inbound': 'i', 'outbound': 'o'} super(InterfacesModel, self).__init__() class VolumesModel(BaseDeviceModel): def __init__(self): self.device_type = 'volume' self.collection_name = 'volumes' super(VolumesModel, self).__init__() volumes_model = VolumesModel() interfaces_model = InterfacesModel()
martinrusev/amonone
amon/apps/devices/models.py
Python
mit
4,472
"""LegacyFileDiffData model defitnition.""" from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from djblets.db.fields import Base64Field, JSONField class LegacyFileDiffData(models.Model): """Deprecated, legacy class for base64-encoded diff data. This is no longer populated, and exists solely to store legacy data that has not been migrated to :py:class:`RawFileDiffData`. """ binary_hash = models.CharField(_('hash'), max_length=40, primary_key=True) binary = Base64Field(_('base64')) extra_data = JSONField(null=True) class Meta: app_label = 'diffviewer' db_table = 'diffviewer_filediffdata' verbose_name = _('Legacy File Diff Data') verbose_name_plural = _('Legacy File Diff Data Blobs')
chipx86/reviewboard
reviewboard/diffviewer/models/legacy_file_diff_data.py
Python
mit
837
from distutils.core import setup import pygiphy VERSION = pygiphy.__version__ AUTHOR = pygiphy.__author__ setup_kwargs = { 'name': 'pygiphy', 'version': VERSION, 'url': 'https://github.com/MichaelYusko/PyGiphy', 'license': 'MIT', 'author': AUTHOR, 'author_email': 'freshjelly12@yahoo.com', 'description': 'Python interface for the Giphy API', 'packages': ['pygiphy'], 'classifiers': [ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Web Environment', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'License :: OSI Approved :: MIT License' ], } requirements = ['requests>=2.13.0'] setup_kwargs['install_requires'] = requirements setup(**setup_kwargs) print(u"\n\n\t\t " "PyGiphy version {} installation succeeded.\n".format(VERSION))
MichaelYusko/PyGiphy
setup.py
Python
mit
871
# coding=utf-8 from ..packet import Packet from ..proto import Proto from ..flags import Flags class Refresh(Packet): __slots__ = ('flags', ) + Packet.__slots__ def __init__(self): super(Refresh, self).__init__() self.flags = 0x00 def getPayload(self): payload = bytearray() payload.extend(Proto.build_byte(Flags.COM_REFRESH)) payload.extend(Proto.build_fixed_int(1, self.flags)) return payload @staticmethod def loadFromPacket(packet): obj = Refresh() proto = Proto(packet, 3) obj.sequenceId = proto.get_fixed_int(1) proto.get_filler(1) obj.flags = proto.get_fixed_int(1) return obj
MPjct/PyMP
mysql_proto/com/refresh.py
Python
mit
710
import logging import requests import socket import sys import threading import time from concurrent.futures import ThreadPoolExecutor from .configs import defaults from .utils import sanitize_meta, get_ip, normalize_list_option class LogDNAHandler(logging.Handler): def __init__(self, key, options={}): # Setup Handler logging.Handler.__init__(self) # Set Internal Logger self.internal_handler = logging.StreamHandler(sys.stdout) self.internal_handler.setLevel(logging.DEBUG) self.internalLogger = logging.getLogger('internal') self.internalLogger.addHandler(self.internal_handler) self.internalLogger.setLevel(logging.DEBUG) # Set the Custom Variables self.key = key self.hostname = options.get('hostname', socket.gethostname()) self.ip = options.get('ip', get_ip()) self.mac = options.get('mac', None) self.loglevel = options.get('level', 'info') self.app = options.get('app', '') self.env = options.get('env', '') self.tags = normalize_list_option(options, 'tags') self.custom_fields = normalize_list_option(options, 'custom_fields') self.custom_fields += defaults['META_FIELDS'] # Set the Connection Variables self.url = options.get('url', defaults['LOGDNA_URL']) self.request_timeout = options.get('request_timeout', defaults['DEFAULT_REQUEST_TIMEOUT']) self.user_agent = options.get('user_agent', defaults['USER_AGENT']) self.max_retry_attempts = options.get('max_retry_attempts', defaults['MAX_RETRY_ATTEMPTS']) self.max_retry_jitter = options.get('max_retry_jitter', defaults['MAX_RETRY_JITTER']) self.max_concurrent_requests = options.get( 'max_concurrent_requests', defaults['MAX_CONCURRENT_REQUESTS']) self.retry_interval_secs = options.get('retry_interval_secs', defaults['RETRY_INTERVAL_SECS']) # Set the Flush-related Variables self.buf = [] self.buf_size = 0 self.secondary = [] self.exception_flag = False self.flusher = None self.include_standard_meta = options.get('include_standard_meta', None) if self.include_standard_meta is not None: self.internalLogger.debug( '"include_standard_meta" option will be deprecated ' + 'removed in the upcoming major release') self.index_meta = options.get('index_meta', False) self.flush_limit = options.get('flush_limit', defaults['FLUSH_LIMIT']) self.flush_interval_secs = options.get('flush_interval', defaults['FLUSH_INTERVAL_SECS']) self.buf_retention_limit = options.get('buf_retention_limit', defaults['BUF_RETENTION_LIMIT']) # Set up the Thread Pools self.worker_thread_pool = ThreadPoolExecutor() self.request_thread_pool = ThreadPoolExecutor( max_workers=self.max_concurrent_requests) self.setLevel(logging.DEBUG) self.lock = threading.RLock() def start_flusher(self): if not self.flusher: self.flusher = threading.Timer(self.flush_interval_secs, self.flush) self.flusher.start() def close_flusher(self): if self.flusher: self.flusher.cancel() self.flusher = None def buffer_log(self, message): if self.worker_thread_pool: try: self.worker_thread_pool.submit(self.buffer_log_sync, message) except RuntimeError: self.buffer_log_sync(message) except Exception as e: self.internalLogger.debug('Error in calling buffer_log: %s', e) def buffer_log_sync(self, message): # Attempt to acquire lock to write to buf # otherwise write to secondary as flush occurs if self.lock.acquire(blocking=False): msglen = len(message['line']) if self.buf_size + msglen < self.buf_retention_limit: self.buf.append(message) self.buf_size += msglen else: self.internalLogger.debug( 'The buffer size exceeded the limit: %s', self.buf_retention_limit) if self.buf_size >= self.flush_limit and not self.exception_flag: self.close_flusher() self.flush() else: self.start_flusher() self.lock.release() else: self.secondary.append(message) def clean_after_success(self): self.close_flusher() self.buf.clear() self.buf_size = 0 self.exception_flag = False def flush(self): if self.worker_thread_pool: try: self.worker_thread_pool.submit(self.flush_sync) except RuntimeError: self.flush_sync() except Exception as e: self.internalLogger.debug('Error in calling flush: %s', e) def flush_sync(self): if self.buf_size == 0 and len(self.secondary) == 0: return if self.lock.acquire(blocking=False): if self.request_thread_pool: try: self.request_thread_pool.submit(self.try_request) except RuntimeError: self.try_request() except Exception as e: self.internalLogger.debug( 'Error in calling try_request: %s', e) finally: self.lock.release() else: self.lock.release() else: self.close_flusher() self.start_flusher() def try_request(self): self.buf.extend(self.secondary) self.secondary = [] data = {'e': 'ls', 'ls': self.buf} retries = 0 while retries < self.max_retry_attempts: retries += 1 if self.send_request(data): self.clean_after_success() break sleep_time = self.retry_interval_secs * (1 << (retries - 1)) sleep_time += self.max_retry_jitter time.sleep(sleep_time) if retries >= self.max_retry_attempts: self.internalLogger.debug( 'Flush exceeded %s tries. Discarding flush buffer', self.max_retry_attempts) self.close_flusher() self.exception_flag = True def send_request(self, data): try: response = requests.post(url=self.url, json=data, auth=('user', self.key), params={ 'hostname': self.hostname, 'ip': self.ip, 'mac': self.mac, 'tags': self.tags, 'now': int(time.time() * 1000) }, stream=True, timeout=self.request_timeout, headers={'user-agent': self.user_agent}) response.raise_for_status() status_code = response.status_code if status_code in [401, 403]: self.internalLogger.debug( 'Please provide a valid ingestion key.' + ' Discarding flush buffer') return True if status_code == 200: return True if status_code in [400, 500, 504]: self.internalLogger.debug('The request failed %s. Retrying...', response.reason) return True else: self.internalLogger.debug( 'The request failed: %s. Retrying...', response.reason) except requests.exceptions.Timeout as timeout: self.internalLogger.debug('Timeout error occurred %s. Retrying...', timeout) except requests.exceptions.RequestException as exception: self.internalLogger.debug( 'Error sending logs %s. Discarding flush buffer', exception) return True return False def emit(self, record): msg = self.format(record) record = record.__dict__ message = { 'hostname': self.hostname, 'timestamp': int(time.time() * 1000), 'line': msg, 'level': record['levelname'] or self.loglevel, 'app': self.app or record['module'], 'env': self.env } message['meta'] = {} for key in self.custom_fields: if key in record: if isinstance(record[key], tuple): message['meta'][key] = list(record[key]) elif record[key] is not None: message['meta'][key] = record[key] message['meta'] = sanitize_meta(message['meta'], self.index_meta) opts = {} if 'args' in record and not isinstance(record['args'], tuple): opts = record['args'] for key in ['app', 'env', 'hostname', 'level', 'timestamp']: if key in opts: message[key] = opts[key] self.buffer_log(message) def close(self): self.close_flusher() self.flush_sync() if self.worker_thread_pool: self.worker_thread_pool.shutdown(wait=True) self.worker_thread_pool = None if self.request_thread_pool: self.request_thread_pool.shutdown(wait=True) self.request_thread_pool = None logging.Handler.close(self)
logdna/python
logdna/logdna.py
Python
mit
10,185
#!/usr/bin/env python import os, sys def touch(path): with open(path, 'a'): os.utime(path, None) fout = open('sample.fileids', 'wb') fout2 = open('sample.transcription', 'wb') for fn in sorted(os.listdir('.')): if not fn.endswith('.wav'): continue base_fn = os.path.splitext(fn)[0] txt_fn = base_fn + '.txt' touch(txt_fn) text = open(txt_fn).read().strip() if text and not text.startswith('#'): fout.write('samples/%s\n' % base_fn) fout2.write('<s> %s <s> (%s)\n' % (text, base_fn)) print 'Done.'
chrisspen/homebot
src/test/detect_voice/sphinxtrain_test/samples/make_fileids.py
Python
mit
559
# 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, Callable, Dict, Generic, Optional, TypeVar, Union import warnings 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.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class ReferenceDataSetsOperations: """ReferenceDataSetsOperations 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.timeseriesinsights.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 create_or_update( self, resource_group_name: str, environment_name: str, reference_data_set_name: str, parameters: "_models.ReferenceDataSetCreateOrUpdateParameters", **kwargs ) -> "_models.ReferenceDataSetResource": """Create or update a reference data set in the specified environment. :param resource_group_name: Name of an Azure Resource group. :type resource_group_name: str :param environment_name: The name of the Time Series Insights environment associated with the specified resource group. :type environment_name: str :param reference_data_set_name: Name of the reference data set. :type reference_data_set_name: str :param parameters: Parameters for creating a reference data set. :type parameters: ~azure.mgmt.timeseriesinsights.models.ReferenceDataSetCreateOrUpdateParameters :keyword callable cls: A custom type or function that will be passed the direct response :return: ReferenceDataSetResource, or the result of cls(response) :rtype: ~azure.mgmt.timeseriesinsights.models.ReferenceDataSetResource :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ReferenceDataSetResource"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-05-15" 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 = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'environmentName': self._serialize.url("environment_name", environment_name, 'str'), 'referenceDataSetName': self._serialize.url("reference_data_set_name", reference_data_set_name, 'str', max_length=63, min_length=3, pattern=r'^[A-Za-z0-9]'), } 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, 'ReferenceDataSetCreateOrUpdateParameters') 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('ReferenceDataSetResource', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('ReferenceDataSetResource', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.TimeSeriesInsights/environments/{environmentName}/referenceDataSets/{referenceDataSetName}'} # type: ignore async def get( self, resource_group_name: str, environment_name: str, reference_data_set_name: str, **kwargs ) -> "_models.ReferenceDataSetResource": """Gets the reference data set with the specified name in the specified environment. :param resource_group_name: Name of an Azure Resource group. :type resource_group_name: str :param environment_name: The name of the Time Series Insights environment associated with the specified resource group. :type environment_name: str :param reference_data_set_name: The name of the Time Series Insights reference data set associated with the specified environment. :type reference_data_set_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ReferenceDataSetResource, or the result of cls(response) :rtype: ~azure.mgmt.timeseriesinsights.models.ReferenceDataSetResource :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ReferenceDataSetResource"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-05-15" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'environmentName': self._serialize.url("environment_name", environment_name, 'str'), 'referenceDataSetName': self._serialize.url("reference_data_set_name", reference_data_set_name, '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['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('ReferenceDataSetResource', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.TimeSeriesInsights/environments/{environmentName}/referenceDataSets/{referenceDataSetName}'} # type: ignore async def update( self, resource_group_name: str, environment_name: str, reference_data_set_name: str, reference_data_set_update_parameters: "_models.ReferenceDataSetUpdateParameters", **kwargs ) -> "_models.ReferenceDataSetResource": """Updates the reference data set with the specified name in the specified subscription, resource group, and environment. :param resource_group_name: Name of an Azure Resource group. :type resource_group_name: str :param environment_name: The name of the Time Series Insights environment associated with the specified resource group. :type environment_name: str :param reference_data_set_name: The name of the Time Series Insights reference data set associated with the specified environment. :type reference_data_set_name: str :param reference_data_set_update_parameters: Request object that contains the updated information for the reference data set. :type reference_data_set_update_parameters: ~azure.mgmt.timeseriesinsights.models.ReferenceDataSetUpdateParameters :keyword callable cls: A custom type or function that will be passed the direct response :return: ReferenceDataSetResource, or the result of cls(response) :rtype: ~azure.mgmt.timeseriesinsights.models.ReferenceDataSetResource :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ReferenceDataSetResource"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-05-15" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.update.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'environmentName': self._serialize.url("environment_name", environment_name, 'str'), 'referenceDataSetName': self._serialize.url("reference_data_set_name", reference_data_set_name, '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(reference_data_set_update_parameters, 'ReferenceDataSetUpdateParameters') 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('ReferenceDataSetResource', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.TimeSeriesInsights/environments/{environmentName}/referenceDataSets/{referenceDataSetName}'} # type: ignore async def delete( self, resource_group_name: str, environment_name: str, reference_data_set_name: str, **kwargs ) -> None: """Deletes the reference data set with the specified name in the specified subscription, resource group, and environment. :param resource_group_name: Name of an Azure Resource group. :type resource_group_name: str :param environment_name: The name of the Time Series Insights environment associated with the specified resource group. :type environment_name: str :param reference_data_set_name: The name of the Time Series Insights reference data set associated with the specified environment. :type reference_data_set_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None, or the result of cls(response) :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ 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 = "2020-05-15" accept = "application/json" # Construct URL url = self.delete.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'environmentName': self._serialize.url("environment_name", environment_name, 'str'), 'referenceDataSetName': self._serialize.url("reference_data_set_name", reference_data_set_name, '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['Accept'] = self._serialize.header("accept", accept, 'str') 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, 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.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.TimeSeriesInsights/environments/{environmentName}/referenceDataSets/{referenceDataSetName}'} # type: ignore async def list_by_environment( self, resource_group_name: str, environment_name: str, **kwargs ) -> "_models.ReferenceDataSetListResponse": """Lists all the available reference data sets associated with the subscription and within the specified resource group and environment. :param resource_group_name: Name of an Azure Resource group. :type resource_group_name: str :param environment_name: The name of the Time Series Insights environment associated with the specified resource group. :type environment_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ReferenceDataSetListResponse, or the result of cls(response) :rtype: ~azure.mgmt.timeseriesinsights.models.ReferenceDataSetListResponse :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ReferenceDataSetListResponse"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-05-15" accept = "application/json" # Construct URL url = self.list_by_environment.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'environmentName': self._serialize.url("environment_name", environment_name, '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['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('ReferenceDataSetListResponse', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized list_by_environment.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.TimeSeriesInsights/environments/{environmentName}/referenceDataSets'} # type: ignore
Azure/azure-sdk-for-python
sdk/timeseriesinsights/azure-mgmt-timeseriesinsights/azure/mgmt/timeseriesinsights/aio/operations/_reference_data_sets_operations.py
Python
mit
19,516
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- # pylint: disable=line-too-long from knack.arguments import CLIArgumentType from azure.cli.core.commands.validators import get_default_location_from_resource_group from azure.cli.core.commands.parameters import (get_location_type, get_enum_type, tags_type, get_three_state_flag) from azure.cli.command_modules.ams._completers import (get_role_definition_name_completion_list, get_cdn_provider_completion_list, get_default_streaming_policies_completion_list, get_presets_definition_name_completion_list, get_allowed_languages_for_preset_completion_list, get_protocols_completion_list, get_token_type_completion_list, get_fairplay_rentalandlease_completion_list, get_token_completion_list, get_mru_type_completion_list, get_encoding_types_list, get_allowed_resolutions_completion_list, get_allowed_transcription_languages, get_allowed_analysis_modes, get_stretch_mode_types_list, get_storage_authentication_allowed_values_list) from azure.cli.command_modules.ams._validators import (validate_storage_account_id, datetime_format, validate_correlation_data, validate_token_claim, validate_output_assets, validate_archive_window_length, validate_key_frame_interval_duration) from azure.mgmt.media.models import (Priority, AssetContainerPermission, LiveEventInputProtocol, StreamOptionsFlag, OnErrorType, InsightsType) def load_arguments(self, _): # pylint: disable=too-many-locals, too-many-statements name_arg_type = CLIArgumentType(options_list=['--name', '-n'], id_part='name', help='The name of the Azure Media Services account.', metavar='NAME') account_name_arg_type = CLIArgumentType(options_list=['--account-name', '-a'], id_part='name', help='The name of the Azure Media Services account.', metavar='ACCOUNT_NAME') storage_account_arg_type = CLIArgumentType(options_list=['--storage-account'], validator=validate_storage_account_id, metavar='STORAGE_NAME') password_arg_type = CLIArgumentType(options_list=['--password', '-p'], metavar='PASSWORD_NAME') transform_name_arg_type = CLIArgumentType(options_list=['--transform-name', '-t'], metavar='TRANSFORM_NAME') expiry_arg_type = CLIArgumentType(options_list=['--expiry'], type=datetime_format, metavar='EXPIRY_TIME') default_policy_name_arg_type = CLIArgumentType(options_list=['--content-key-policy-name'], help='The default content key policy name used by the streaming locator.', metavar='DEFAULT_CONTENT_KEY_POLICY_NAME') archive_window_length_arg_type = CLIArgumentType(options_list=['--archive-window-length'], validator=validate_archive_window_length, metavar='ARCHIVE_WINDOW_LENGTH') key_frame_interval_duration_arg_type = CLIArgumentType(options_list=['--key-frame-interval-duration'], validator=validate_archive_window_length, metavar='ARCHIVE_WINDOW_LENGTH') correlation_data_type = CLIArgumentType(validator=validate_correlation_data, help="Space-separated correlation data in 'key[=value]' format. This customer provided data will be returned in Job and JobOutput state events.", nargs='*', metavar='CORRELATION_DATA') token_claim_type = CLIArgumentType(validator=validate_token_claim, help="Space-separated required token claims in '[key=value]' format.", nargs='*', metavar='ASYMMETRIC TOKEN CLAIMS') output_assets_type = CLIArgumentType(validator=validate_output_assets, nargs='*', help="Space-separated assets in 'assetName=label' format. An asset without label can be sent like this: 'assetName='", metavar='OUTPUT_ASSETS') with self.argument_context('ams') as c: c.argument('account_name', name_arg_type) with self.argument_context('ams account') as c: c.argument('location', arg_type=get_location_type(self.cli_ctx), validator=get_default_location_from_resource_group, required=False) c.argument('tags', arg_type=tags_type) with self.argument_context('ams account create') as c: c.argument('storage_account', storage_account_arg_type, help='The name or resource ID of the primary storage account to attach to the Azure Media Services account. The storage account MUST be in the same Azure subscription as the Media Services account. It is strongly recommended that the storage account be in the same resource group as the Media Services account. Blob only accounts are not allowed as primary.') c.argument('assign_identity', options_list=['--mi-system-assigned'], action='store_true', help='Set the system managed identity on the media services account.') with self.argument_context('ams account check-name') as c: c.argument('account_name', options_list=['--name', '-n'], id_part=None, help='The name of the Azure Media Services account.') c.argument('location', arg_type=get_location_type(self.cli_ctx)) with self.argument_context('ams account mru') as c: c.argument('type', help='Speed of reserved processing units. The cost of media encoding depends on the pricing tier you choose. See https://azure.microsoft.com/pricing/details/media-services/ for further details. Allowed values: {}.'.format(", ".join(get_mru_type_completion_list()))) c.argument('count', type=int, help='The number of the encoding reserved units that you want to be provisioned for this account for concurrent tasks (one unit equals one task).') with self.argument_context('ams account storage') as c: c.argument('account_name', account_name_arg_type) c.argument('storage_account', name_arg_type, help='The name or resource ID of the secondary storage account to detach from the Azure Media Services account.', validator=validate_storage_account_id) with self.argument_context('ams account storage sync-storage-keys') as c: c.argument('storage_account_id', required=True, help="The storage account Id.") with self.argument_context('ams account storage set-authentication') as c: c.argument('storage_auth', arg_type=get_enum_type(get_storage_authentication_allowed_values_list()), help='The type of authentication for the storage account associated with the media services account.') with self.argument_context('ams account sp') as c: c.argument('account_name', account_name_arg_type) c.argument('sp_name', name_arg_type, help="The app name or app URI to associate the RBAC with. If not present, a default name like '{amsaccountname}-access-sp' will be generated.") c.argument('new_sp_name', help="The new app name or app URI to update the RBAC with.") c.argument('sp_password', password_arg_type, help="The password used to log in. Also known as 'Client Secret'. If not present, a random secret will be generated.") c.argument('role', help='The role of the service principal.', completer=get_role_definition_name_completion_list) c.argument('xml', action='store_true', help='Enables xml output format.') c.argument('years', help='Number of years for which the secret will be valid. Default: 1 year.', type=int, default=None) with self.argument_context('ams account encryption') as c: c.argument('account_name', account_name_arg_type) c.argument('key_type', help='The encryption key source (provider). Allowed values: SystemKey, CustomerKey.', required=True) c.argument('key_identifier', help='The URL of the Key Vault key used to encrypt the account. The key may either be versioned (for example https://vault/keys/mykey/version1) or reference a key without a version (for example https://vault/keys/mykey).') c.argument('current_key_id', help='The current key used to encrypt the Media Services account, including the key version.') with self.argument_context('ams transform') as c: c.argument('account_name', account_name_arg_type) c.argument('transform_name', name_arg_type, id_part='child_name_1', help='The name of the transform.') c.argument('preset', help='Preset that describes the operations that will be used to modify, transcode, or extract insights from the source file to generate the transform output. Allowed values: {}. In addition to the allowed values, you can also pass a path to a custom Standard Encoder preset JSON file. See https://docs.microsoft.com/rest/api/media/transforms/createorupdate#standardencoderpreset for further details on the settings to use to build a custom preset.' .format(", ".join(get_presets_definition_name_completion_list()))) c.argument('insights_to_extract', arg_group='Video Analyzer', arg_type=get_enum_type(InsightsType), help='The type of insights to be extracted. If not set then the type will be selected based on the content type. If the content is audio only then only audio insights will be extracted and if it is video only video insights will be extracted.') c.argument('video_analysis_mode', arg_group='Video Analyzer', help='Determines the set of audio analysis operations to be performed. If unspecified, the Standard AudioAnalysisMode would be chosen. Allowed values: {}'.format(", ".join(get_allowed_analysis_modes()))) c.argument('audio_language', arg_group='Audio/Video Analyzer', help='The language for the audio payload in the input using the BCP-47 format of \"language tag-region\" (e.g: en-US). If not specified, automatic language detection would be employed. This feature currently supports English, Chinese, French, German, Italian, Japanese, Spanish, Russian, and Portuguese. The automatic detection works best with audio recordings with clearly discernable speech. If automatic detection fails to find the language, transcription would fallback to English. Allowed values: {}.' .format(", ".join(get_allowed_languages_for_preset_completion_list()))) c.argument('audio_analysis_mode', arg_group='Audio/Video Analyzer', help='Determines the set of audio analysis operations to be performed. If unspecified, the Standard AudioAnalysisMode would be chosen. Allowed values: {}.'.format(", ".join(get_allowed_analysis_modes()))) c.argument('resolution', arg_group='Face Detector', help='Specifies the maximum resolution at which your video is analyzed. The default behavior is "SourceResolution," which will keep the input video at its original resolution when analyzed. Using StandardDefinition will resize input videos to standard definition while preserving the appropriate aspect ratio. It will only resize if the video is of higher resolution. For example, a 1920x1080 input would be scaled to 640x360 before processing. Switching to "StandardDefinition" will reduce the time it takes to process high resolution video. It may also reduce the cost of using this component (see https://azure.microsoft.com/pricing/details/media-services/#analytics for details). However, faces that end up being too small in the resized video may not be detected. Allowed values: {}.' .format(", ".join(get_allowed_resolutions_completion_list()))) c.argument('relative_priority', arg_type=get_enum_type(Priority), help='Sets the relative priority of the transform outputs within a transform. This sets the priority that the service uses for processing TransformOutputs. The default priority is Normal.') c.argument('on_error', arg_type=get_enum_type(OnErrorType), help="A Transform can define more than one output. This property defines what the service should do when one output fails - either continue to produce other outputs, or, stop the other outputs. The overall Job state will not reflect failures of outputs that are specified with 'ContinueJob'. The default is 'StopProcessingJob'.") c.argument('description', help='The description of the transform.') with self.argument_context('ams transform output remove') as c: c.argument('output_index', help='The element index of the output to remove.', type=int, default=None) with self.argument_context('ams transform list') as c: c.argument('account_name', id_part=None) with self.argument_context('ams asset') as c: c.argument('account_name', account_name_arg_type) c.argument('asset_name', name_arg_type, id_part='child_name_1', help='The name of the asset.') with self.argument_context('ams asset list') as c: c.argument('account_name', id_part=None) with self.argument_context('ams asset create') as c: c.argument('alternate_id', help='The alternate id of the asset.') c.argument('description', help='The asset description.') c.argument('asset_name', name_arg_type, help='The name of the asset.') c.argument('storage_account', help='The name of the storage account.') c.argument('container', help='The name of the asset blob container.') with self.argument_context('ams asset update') as c: c.argument('alternate_id', help='The alternate id of the asset.') c.argument('description', help='The asset description.') with self.argument_context('ams asset get-sas-urls') as c: c.argument('permissions', arg_type=get_enum_type(AssetContainerPermission), help='The permissions to set on the SAS URL.') c.argument('expiry_time', expiry_arg_type, help="Specifies the UTC datetime (Y-m-d'T'H:M:S'Z') at which the SAS becomes invalid. This must be less than 24 hours from the current time.") with self.argument_context('ams asset-filter') as c: c.argument('account_name', account_name_arg_type) c.argument('asset_name', help='The name of the asset.', id_part='child_name_1') c.argument('filter_name', name_arg_type, id_part='child_name_2', help='The name of the asset filter.') c.argument('start_timestamp', arg_group='Presentation Time Range', help='Applies to Video on Demand (VoD) or Live Streaming. This is a long value that represents an absolute start point of the stream. The value gets rounded to the closest next GOP start. The unit is the timescale, so a startTimestamp of 150000000 would be for 15 seconds. Use startTimestamp and endTimestampp to trim the fragments that will be in the playlist (manifest). For example, startTimestamp=40000000 and endTimestamp=100000000 using the default timescale will generate a playlist that contains fragments from between 4 seconds and 10 seconds of the VoD presentation. If a fragment straddles the boundary, the entire fragment will be included in the manifest.') c.argument('end_timestamp', arg_group='Presentation Time Range', help='Applies to Video on Demand (VoD).For the Live Streaming presentation, it is silently ignored and applied when the presentation ends and the stream becomes VoD.This is a long value that represents an absolute end point of the presentation, rounded to the closest next GOP start. The unit is the timescale, so an endTimestamp of 1800000000 would be for 3 minutes.Use startTimestamp and endTimestamp to trim the fragments that will be in the playlist (manifest).For example, startTimestamp=40000000 and endTimestamp=100000000 using the default timescale will generate a playlist that contains fragments from between 4 seconds and 10 seconds of the VoD presentation. If a fragment straddles the boundary, the entire fragment will be included in the manifest.') c.argument('presentation_window_duration', arg_group='Presentation Time Range', help='Applies to Live Streaming only.Use presentationWindowDuration to apply a sliding window of fragments to include in a playlist.The unit for this property is timescale (see below).For example, set presentationWindowDuration=1200000000 to apply a two-minute sliding window. Media within 2 minutes of the live edge will be included in the playlist. If a fragment straddles the boundary, the entire fragment will be included in the playlist. The minimum presentation window duration is 60 seconds.') c.argument('live_backoff_duration', arg_group='Presentation Time Range', help='Applies to Live Streaming only. This value defines the latest live position that a client can seek to. Using this property, you can delay live playback position and create a server-side buffer for players. The unit for this property is timescale (see below). The maximum live back off duration is 300 seconds (3000000000). For example, a value of 2000000000 means that the latest available content is 20 seconds delayed from the real live edge.') c.argument('timescale', arg_group='Presentation Time Range', help='Applies to all timestamps and durations in a Presentation Time Range, specified as the number of increments in one second.Default is 10000000 - ten million increments in one second, where each increment would be 100 nanoseconds long. For example, if you want to set a startTimestamp at 30 seconds, you would use a value of 300000000 when using the default timescale.') c.argument('force_end_timestamp', arg_group='Presentation Time Range', arg_type=get_three_state_flag(), help='Applies to Live Streaming only. Indicates whether the endTimestamp property must be present. If true, endTimestamp must be specified or a bad request code is returned. Allowed values: false, true.') c.argument('bitrate', help='The first quality bitrate.', deprecate_info=c.deprecate(target='--bitrate', redirect='--first-quality', hide=True)) c.argument('first_quality', help='The first quality (lowest) bitrate to include in the manifest.') c.argument('tracks', help='The JSON representing the track selections. Use @{file} to load from a file. For further information about the JSON structure please refer to swagger documentation on https://docs.microsoft.com/rest/api/media/assetfilters/createorupdate#filtertrackselection') with self.argument_context('ams asset-filter list') as c: c.argument('account_name', id_part=None) with self.argument_context('ams job') as c: c.argument('account_name', account_name_arg_type) c.argument('transform_name', transform_name_arg_type, id_part='child_name_1', help='The name of the transform.') c.argument('job_name', name_arg_type, id_part='child_name_2', help='The name of the job.') c.argument('description', help='The job description.') c.argument('priority', arg_type=get_enum_type(Priority), help='The priority with which the job should be processed.') with self.argument_context('ams job list') as c: c.argument('account_name', id_part=None) with self.argument_context('ams job start') as c: c.argument('correlation_data', arg_type=correlation_data_type) c.argument('input_asset_name', arg_group='Asset Job Input', help='The name of the input asset.') c.argument('output_assets', arg_type=output_assets_type) c.argument('base_uri', arg_group='Http Job Input', help='Base uri for http job input. It will be concatenated with provided file names. If no base uri is given, then the provided file list is assumed to be fully qualified uris.') c.argument('files', nargs='+', help='Space-separated list of files. It can be used to tell the service to only use the files specified from the input asset.') c.argument('label', help="A label that is assigned to a Job Input that is used to satisfy a reference used in the Transform. For example, a Transform can be authored to take an image file with the label 'xyz' and apply it as an overlay onto the input video before it is encoded. When submitting a Job, exactly one of the JobInputs should be the image file, and it should have the label 'xyz'.") c.argument('correlation_data', arg_type=correlation_data_type) with self.argument_context('ams job cancel') as c: c.argument('delete', action='store_true', help='Delete the job being cancelled.') with self.argument_context('ams content-key-policy') as c: c.argument('account_name', account_name_arg_type) c.argument('content_key_policy_name', name_arg_type, id_part='child_name_1', help='The content key policy name.') c.argument('description', help='The content key policy description.') c.argument('clear_key_configuration', action='store_true', arg_group='Clear Key Configuration (AES Encryption)', help='Use Clear Key configuration, a.k.a AES encryption. It\'s intended for non-DRM keys.') c.argument('open_restriction', action='store_true', arg_group='Open Restriction', help='Use open restriction. License or key will be delivered on every request. Not recommended for production environments.') c.argument('policy_option_name', help='The content key policy option name.') c.argument('policy_option_id', help='The content key policy option identifier. This value can be obtained from "policyOptionId" property by running a show operation on a content key policy resource.') c.argument('issuer', arg_group='Token Restriction', help='The token issuer.') c.argument('audience', arg_group='Token Restriction', help='The audience for the token.') c.argument('token_key', arg_group='Token Restriction', help='Either a string (for symmetric key) or a filepath to a certificate (x509) or public key (rsa). Must be used in conjunction with --token-key-type.') c.argument('token_key_type', arg_group='Token Restriction', help='The type of the token key to be used for the primary verification key. Allowed values: {}'.format(", ".join(get_token_completion_list()))) c.argument('add_alt_token_key', arg_group='Token Restriction', help='Creates an alternate token key with either a string (for symmetric key) or a filepath to a certificate (x509) or public key (rsa). Must be used in conjunction with --add-alt-token-key-type.') c.argument('add_alt_token_key_type', arg_group='Token Restriction', help='The type of the token key to be used for the alternate verification key. Allowed values: {}'.format(", ".join(get_token_completion_list()))) c.argument('alt_symmetric_token_keys', nargs='+', arg_group='Token Restriction', help='Space-separated list of alternate symmetric token keys.') c.argument('alt_rsa_token_keys', nargs='+', arg_group='Token Restriction', help='Space-separated list of alternate rsa token keys.') c.argument('alt_x509_token_keys', nargs='+', arg_group='Token Restriction', help='Space-separated list of alternate x509 certificate token keys.') c.argument('token_claims', arg_group='Token Restriction', arg_type=token_claim_type) c.argument('token_type', arg_group='Token Restriction', help='The type of token. Allowed values: {}.'.format(", ".join(get_token_type_completion_list()))) c.argument('open_id_connect_discovery_document', arg_group='Token Restriction', help='The OpenID connect discovery document.') c.argument('widevine_template', arg_group='Widevine Configuration', help='JSON Widevine license template. Use @{file} to load from a file.') c.argument('fp_playback_duration_seconds', arg_group='FairPlay Configuration', help='Playback duration') c.argument('fp_storage_duration_seconds', arg_group='FairPlay Configuration', help='Storage duration') c.argument('ask', arg_group='FairPlay Configuration', help='The key that must be used as FairPlay Application Secret Key, which is a 32 character hex string.') c.argument('fair_play_pfx_password', arg_group='FairPlay Configuration', help='The password encrypting FairPlay certificate in PKCS 12 (pfx) format.') c.argument('fair_play_pfx', arg_group='FairPlay Configuration', help='The filepath to a FairPlay certificate file in PKCS 12 (pfx) format (including private key).') c.argument('rental_and_lease_key_type', arg_group='FairPlay Configuration', help='The rental and lease key type. Available values: {}.'.format(", ".join(get_fairplay_rentalandlease_completion_list()))) c.argument('rental_duration', arg_group='FairPlay Configuration', help='The rental duration. Must be greater than or equal to 0.') c.argument('play_ready_template', arg_group='PlayReady Configuration', help='JSON PlayReady license template. Use @{file} to load from a file.') with self.argument_context('ams content-key-policy list') as c: c.argument('account_name', id_part=None) with self.argument_context('ams content-key-policy show') as c: c.argument('with_secrets', action='store_true', help='Include secret values of the content key policy.') with self.argument_context('ams streaming-locator') as c: c.argument('account_name', account_name_arg_type) c.argument('default_content_key_policy_name', default_policy_name_arg_type) c.argument('streaming_locator_name', name_arg_type, id_part='child_name_1', help='The name of the streaming locator.') c.argument('asset_name', help='The name of the asset used by the streaming locator.') c.argument('streaming_policy_name', help='The name of the streaming policy used by the streaming locator. You can either create one with `az ams streaming policy create` or use any of the predefined policies: {}'.format(", ".join(get_default_streaming_policies_completion_list()))) c.argument('start_time', type=datetime_format, help="The ISO 8601 DateTime start time (Y-m-d'T'H:M:S'Z') of the streaming locator.") c.argument('end_time', type=datetime_format, help="The ISO 8601 DateTime end time (Y-m-d'T'H:M:S'Z') of the streaming locator.") c.argument('streaming_locator_id', help='The identifier of the streaming locator.') c.argument('alternative_media_id', help='An alternative media identifier associated with the streaming locator.') c.argument('content_keys', help='JSON string with the content keys to be used by the streaming locator. Use @{file} to load from a file. For further information about the JSON structure please refer to swagger documentation on https://docs.microsoft.com/rest/api/media/streaminglocators/create#streaminglocatorcontentkey') c.argument('filters', nargs='+', help='A space-separated list of asset filter names and/or account filter names.') with self.argument_context('ams streaming-locator list') as c: c.argument('account_name', id_part=None) with self.argument_context('ams streaming-policy') as c: c.argument('account_name', account_name_arg_type) c.argument('streaming_policy_name', name_arg_type, id_part='child_name_1', help='The name of the streaming policy.') c.argument('default_content_key_policy_name', help='Default Content Key used by current streaming policy.') c.argument('no_encryption_protocols', nargs='+', help='Space-separated list of enabled protocols for NoEncryption. Allowed values: {}.'.format(", ".join(get_protocols_completion_list()))) c.argument('envelope_protocols', nargs='+', arg_group='Envelope Encryption', help='Space-separated list of enabled protocols for Envelope Encryption. Allowed values: {}.'.format(", ".join(get_protocols_completion_list()))) c.argument('envelope_clear_tracks', arg_group='Envelope Encryption', help='The JSON representing which tracks should not be encrypted. Use @{file} to load from a file. For further information about the JSON structure please refer to swagger documentation on https://docs.microsoft.com/rest/api/media/streamingpolicies/create#trackselection') c.argument('envelope_key_to_track_mappings', arg_group='Envelope Encryption', help='The JSON representing a list of StreamingPolicyContentKey. Use @{file} to load from a file. For further information about the JSON structure please refer to swagger documentation on https://docs.microsoft.com/rest/api/media/streamingpolicies/create#streamingpolicycontentkey') c.argument('envelope_default_key_label', arg_group='Envelope Encryption', help='Label used to specify Content Key when creating a streaming locator.') c.argument('envelope_default_key_policy_name', arg_group='Envelope Encryption', help='Policy used by Default Key.') c.argument('envelope_template', arg_group='Envelope Encryption', help='The KeyAcquistionUrlTemplate is used to point to user specified service to delivery content keys.') c.argument('cenc_protocols', nargs='+', arg_group='Common Encryption CENC', help='Space-separated list of enabled protocols for Common Encryption CENC. Allowed values: {}.'.format(", ".join(get_protocols_completion_list()))) c.argument('cenc_default_key_label', arg_group='Common Encryption CENC', help='Label to specify Default Content Key for an encryption scheme.') c.argument('cenc_default_key_policy_name', arg_group='Common Encryption CENC', help='Policy used by Default Content Key.') c.argument('cenc_clear_tracks', arg_group='Common Encryption CENC', help='The JSON representing which tracks should not be encrypted. Use @{file} to load from a file. For further information about the JSON structure please refer to swagger documentation on https://docs.microsoft.com/rest/api/media/streamingpolicies/create#trackselection') c.argument('cenc_key_to_track_mappings', arg_group='Common Encryption CENC', help='The JSON representing a list of StreamingPolicyContentKey. Use @{file} to load from a file. For further information about the JSON structure please refer to swagger documentation on https://docs.microsoft.com/rest/api/media/streamingpolicies/create#streamingpolicycontentkey') c.argument('cenc_play_ready_attributes', arg_group='Common Encryption CENC', help='Custom attributes for PlayReady.') c.argument('cenc_widevine_template', arg_group='Common Encryption CENC', help='The custom license acquisition URL template for a customer service to deliver keys to end users. Not needed when using Azure Media Services for issuing keys.') c.argument('cenc_play_ready_template', arg_group='Common Encryption CENC', help='The custom license acquisition URL template for a customer service to deliver keys to end users. Not needed when using Azure Media Services for issuing keys.') c.argument('cenc_disable_widevine', arg_group='Common Encryption CENC', arg_type=get_three_state_flag(), help='If specified, no Widevine cenc DRM will be configured. If --cenc-disable-widevine is set, --cenc-disable-play-ready cannot also be set.') c.argument('cenc_disable_play_ready', arg_group='Common Encryption CENC', arg_type=get_three_state_flag(), help='If specified, no PlayReady cenc DRM will be configured. If --cenc-disable-play-ready is set, --cenc-disable-widevine cannot also be set.') c.argument('cbcs_protocols', nargs='+', arg_group='Common Encryption CBCS', help='Space-separated list of enabled protocols for Common Encryption CBCS. Allowed values: {}.'.format(", ".join(get_protocols_completion_list()))) c.argument('cbcs_default_key_label', arg_group='Common Encryption CBCS', help='Label to specify Default Content Key for an encryption scheme.') c.argument('cbcs_default_key_policy_name', arg_group='Common Encryption CBCS', help='Policy used by Default Content Key.') c.argument('cbcs_clear_tracks', arg_group='Common Encryption CBCS', help='The JSON representing which tracks should not be encrypted. Use @{file} to load from a file. For further information about the JSON structure please refer to swagger documentation on https://docs.microsoft.com/rest/api/media/streamingpolicies/create#trackselection') c.argument('cbcs_key_to_track_mappings', arg_group='Common Encryption CBCS', help='The JSON representing a list of StreamingPolicyContentKey. Use @{file} to load from a file. For further information about the JSON structure please refer to swagger documentation on https://docs.microsoft.com/rest/api/media/streamingpolicies/create#streamingpolicycontentkey') c.argument('cbcs_play_ready_attributes', arg_group='Common Encryption CBCS', help='Custom attributes for PlayReady.', deprecate_info=c.deprecate(hide=True)) c.argument('cbcs_play_ready_template', arg_group='Common Encryption CBCS', help='The custom license acquisition URL template for a customer service to deliver keys to end users. Not needed when using Azure Media Services for issuing keys.', deprecate_info=c.deprecate(hide=True)) c.argument('cbcs_widevine_template', arg_group='Common Encryption CBCS', help='The custom license acquisition URL template for a customer service to deliver keys to end users. Not needed when using Azure Media Services for issuing keys.', deprecate_info=c.deprecate(hide=True)) c.argument('cbcs_fair_play_template', arg_group='Common Encryption CBCS', help='The custom license acquisition URL template for a customer service to deliver keys to end users. Not needed when using Azure Media Services for issuing keys.') c.argument('cbcs_fair_play_allow_persistent_license', arg_group='Common Encryption CBCS', arg_type=get_three_state_flag(), help='Allows the license to be persistent or not.') with self.argument_context('ams streaming-policy list') as c: c.argument('account_name', id_part=None) with self.argument_context('ams streaming-endpoint') as c: c.argument('streaming_endpoint_name', name_arg_type, id_part='child_name_1', help='The name of the streaming endpoint.') c.argument('account_name', account_name_arg_type) c.argument('tags', arg_type=tags_type) c.argument('description', help='The streaming endpoint description.') c.argument('scale_units', help='The number of scale units for Premium StreamingEndpoints. For Standard StreamingEndpoints, set this value to 0. Use the Scale operation to adjust this value for Premium StreamingEndpoints.') c.argument('availability_set_name', help='The name of the AvailabilitySet used with this StreamingEndpoint for high availability streaming. This value can only be set at creation time.') c.argument('max_cache_age', help='Max cache age.') c.argument('custom_host_names', nargs='+', help='Space-separated list of custom host names for the streaming endpoint. Use "" to clear existing list.') c.argument('cdn_provider', arg_group='CDN Support', help='The CDN provider name. Allowed values: {}.'.format(", ".join(get_cdn_provider_completion_list()))) c.argument('cdn_profile', arg_group='CDN Support', help='The CDN profile name.') c.argument('client_access_policy', arg_group='Cross Site Access Policies', help='The XML representing the clientaccesspolicy data used by Microsoft Silverlight and Adobe Flash. Use @{file} to load from a file. For further information about the XML structure please refer to documentation on https://docs.microsoft.com/rest/api/media/operations/crosssiteaccesspolicies') c.argument('cross_domain_policy', arg_group='Cross Site Access Policies', help='The XML representing the crossdomain data used by Silverlight. Use @{file} to load from a file. For further information about the XML structure please refer to documentation on https://docs.microsoft.com/rest/api/media/operations/crosssiteaccesspolicies') c.argument('auto_start', action='store_true', help='The flag indicates if the resource should be automatically started on creation.') c.argument('ips', nargs='+', arg_group='Access Control Support', help='Space-separated IP addresses for access control. Allowed IP addresses can be specified as either a single IP address (e.g. "10.0.0.1") or as an IP range using an IP address and a CIDR subnet mask (e.g. "10.0.0.1/22"). Use "" to clear existing list. If no IP addresses are specified any IP address will be allowed.') c.argument('disable_cdn', arg_group='CDN Support', action='store_true', help='Use this flag to disable CDN for the streaming endpoint.') with self.argument_context('ams streaming-endpoint list') as c: c.argument('account_name', id_part=None) with self.argument_context('ams streaming-endpoint scale') as c: c.argument('scale_unit', options_list=['--scale-units'], help='The number of scale units for Premium StreamingEndpoints.') with self.argument_context('ams streaming-endpoint akamai') as c: c.argument('identifier', help='The identifier for the authentication key. This is the nonce provided by Akamai.') c.argument('base64_key', help='Base64-encoded authentication key that will be used by the CDN. The authentication key provided by Akamai is an ASCII encoded string, and must be converted to bytes and then base64 encoded.') c.argument('expiration', type=datetime_format, help='The ISO 8601 DateTime value that specifies when the Akamai authentication expires.') with self.argument_context('ams streaming-endpoint list') as c: c.argument('account_name', id_part=None) with self.argument_context('ams live-event') as c: c.argument('account_name', account_name_arg_type) c.argument('live_event_name', name_arg_type, id_part='child_name_1', help='The name of the live event.') c.argument('streaming_protocol', arg_type=get_enum_type(LiveEventInputProtocol), arg_group='Input', help='The streaming protocol for the live event. This value is specified at creation time and cannot be updated.') c.argument('auto_start', action='store_true', help='The flag indicates if the resource should be automatically started on creation.') c.argument('encoding_type', arg_group='Encoding', help='The encoding type for live event. This value is specified at creation time and cannot be updated. Allowed values: {}.'.format(", ".join(get_encoding_types_list()))) c.argument('preset_name', arg_group='Encoding', help='The encoding preset name. This value is specified at creation time and cannot be updated.') c.argument('stretch_mode', arg_group='Encoding', help='Specifies how the input video will be resized to fit the desired output resolution(s). Default is None. Allowed values: {}.'.format(", ".join(get_stretch_mode_types_list()))) c.argument('key_frame_interval', arg_group='Encoding', help='Use an ISO 8601 time value between 0.5 to 20 seconds to specify the output fragment length for the video and audiotracks of an encoding live event. For example, use PT2S to indicate 2 seconds. For the video track it also defines the key frame interval, or the length of a GoP (group of pictures). If this value is not set for anencoding live event, the fragment duration defaults to 2 seconds. The value cannot be set for pass-through live events.') c.argument('tags', arg_type=tags_type) c.argument('key_frame_interval_duration', key_frame_interval_duration_arg_type, arg_group='Input', validator=validate_key_frame_interval_duration, help='ISO 8601 timespan duration of the key frame interval duration in seconds. The value should be an interger in the range of 1 (PT1S or 00:00:01) to 30 (PT30S or 00:00:30) seconds.') c.argument('access_token', arg_group='Input', help='A unique identifier for a stream. This can be specified at creation time but cannot be updated. If omitted, the service will generate a unique value.') c.argument('description', help='The live event description.') c.argument('ips', nargs='+', arg_group='Input', help='Space-separated IP addresses for access control. Allowed IP addresses can be specified as either a single IP address (e.g. "10.0.0.1") or as an IP range using an IP address and a CIDR subnet mask (e.g. "10.0.0.1/22"). Use "" to clear existing list. Use "AllowAll" to allow all IP addresses. Allowing all IPs is not recommended for production environments.') c.argument('preview_ips', nargs='+', arg_group='Preview', help='Space-separated IP addresses for access control. Allowed IP addresses can be specified as either a single IP address (e.g. "10.0.0.1") or as an IP range using an IP address and a CIDR subnet mask (e.g. "10.0.0.1/22"). Use "" to clear existing list. Use "AllowAll" to allow all IP addresses. Allowing all IPs is not recommended for production environments.') c.argument('preview_locator', arg_group='Preview', help='The identifier of the preview locator in Guid format. Specifying this at creation time allows the caller to know the preview locator url before the event is created. If omitted, the service will generate a random identifier. This value cannot be updated once the live event is created.') c.argument('streaming_policy_name', arg_group='Preview', help='The name of streaming policy used for the live event preview. This can be specified at creation time but cannot be updated.') c.argument('alternative_media_id', arg_group='Preview', help='An Alternative Media Identifier associated with the StreamingLocator created for the preview. This value is specified at creation time and cannot be updated. The identifier can be used in the CustomLicenseAcquisitionUrlTemplate or the CustomKeyAcquisitionUrlTemplate of the StreamingPolicy specified in the StreamingPolicyName field.') c.argument('client_access_policy', arg_group='Cross Site Access Policies', help='Filepath to the clientaccesspolicy.xml used by Microsoft Silverlight and Adobe Flash. Use @{file} to load from a file.') c.argument('cross_domain_policy', arg_group='Cross Site Access Policies', help='Filepath to the crossdomain.xml used by Microsoft Silverlight and Adobe Flash. Use @{file} to load from a file.') c.argument('stream_options', nargs='+', arg_type=get_enum_type(StreamOptionsFlag), help='The options to use for the LiveEvent. This value is specified at creation time and cannot be updated.') c.argument('transcription_lang', help='Live transcription language for the live event. Allowed values: {} See https://go.microsoft.com/fwlink/?linkid=2133742 for more information about the live transcription feature.'.format(", ".join(get_allowed_transcription_languages()))) c.argument('use_static_hostname', help='Specifies whether a static hostname would be assigned to the live event preview and ingest endpoints. This value can only be updated if the live event is in Standby state. If hostname_prefix is not specified, the live event name will be used as the hostname prefix.') c.argument('hostname_prefix', help='When useStaticHostname is set to true, hostname_prefix specifies the first part of the hostname assigned to the live event preview and ingest endpoints. The final hostname would be a combination of this prefix, the media service account name and a short code for the Azure Media Services data center.') c.argument('remove_outputs_on_stop', action='store_true', help='Remove live outputs on stop.') with self.argument_context('ams live-event list') as c: c.argument('account_name', id_part=None) with self.argument_context('ams live-output') as c: c.argument('account_name', account_name_arg_type) c.argument('live_event_name', id_part='child_name_1', help='The name of the live event.') c.argument('live_output_name', name_arg_type, id_part='child_name_2', help='The name of the live output.') with self.argument_context('ams live-output list') as c: c.argument('account_name', id_part=None) with self.argument_context('ams live-output create') as c: c.argument('asset_name', help='The name of the asset.') c.argument('archive_window_length', archive_window_length_arg_type, validator=validate_archive_window_length, help="ISO 8601 timespan duration of the archive window length. This is the duration that customer want to retain the recorded content. Minimum window is 5 minutes (PT5M or 00:05:00). Maximum window is 25 hours (PT25H or 25:00:00). For example, to retain the output for 10 minutes, use PT10M or 00:10:00") c.argument('manifest_name', help='The manifest file name. If not provided, the service will generate one automatically.') c.argument('description', help='The live output description.') c.argument('fragments_per_ts_segment', help='The number of fragments per HLS segment.') c.argument('output_snap_time', help='The output snapshot time.') with self.argument_context('ams account-filter') as c: c.argument('account_name', account_name_arg_type) c.argument('filter_name', name_arg_type, id_part='child_name_1', help='The name of the account filter.') c.argument('start_timestamp', arg_group='Presentation Time Range', help='Applies to Video on Demand (VoD) or Live Streaming. This is a long value that represents an absolute start point of the stream. The value gets rounded to the closest next GOP start. The unit is the timescale, so a startTimestamp of 150000000 would be for 15 seconds. Use startTimestamp and endTimestampp to trim the fragments that will be in the playlist (manifest). For example, startTimestamp=40000000 and endTimestamp=100000000 using the default timescale will generate a playlist that contains fragments from between 4 seconds and 10 seconds of the VoD presentation. If a fragment straddles the boundary, the entire fragment will be included in the manifest.') c.argument('end_timestamp', arg_group='Presentation Time Range', help='Applies to Video on Demand (VoD). For the Live Streaming presentation, it is silently ignored and applied when the presentation ends and the stream becomes VoD. This is a long value that represents an absolute end point of the presentation, rounded to the closest next GOP start. The unit is the timescale, so an endTimestamp of 1800000000 would be for 3 minutes. Use startTimestamp and endTimestamp to trim the fragments that will be in the playlist (manifest). For example, startTimestamp=40000000 and endTimestamp=100000000 using the default timescale will generate a playlist that contains fragments from between 4 seconds and 10 seconds of the VoD presentation. If a fragment straddles the boundary, the entire fragment will be included in the manifest.') c.argument('presentation_window_duration', arg_group='Presentation Time Range', help='Applies to Live Streaming only. Use presentationWindowDuration to apply a sliding window of fragments to include in a playlist. The unit for this property is timescale (see below). For example, set presentationWindowDuration=1200000000 to apply a two-minute sliding window. Media within 2 minutes of the live edge will be included in the playlist. If a fragment straddles the boundary, the entire fragment will be included in the playlist. The minimum presentation window duration is 60 seconds.') c.argument('live_backoff_duration', arg_group='Presentation Time Range', help='Applies to Live Streaming only. This value defines the latest live position that a client can seek to. Using this property, you can delay live playback position and create a server-side buffer for players. The unit for this property is timescale (see below). The maximum live back off duration is 300 seconds (3000000000). For example, a value of 2000000000 means that the latest available content is 20 seconds delayed from the real live edge.') c.argument('timescale', arg_group='Presentation Time Range', help='Applies to all timestamps and durations in a Presentation Time Range, specified as the number of increments in one second. Default is 10000000 - ten million increments in one second, where each increment would be 100 nanoseconds long. For example, if you want to set a startTimestamp at 30 seconds, you would use a value of 300000000 when using the default timescale.') c.argument('force_end_timestamp', arg_group='Presentation Time Range', arg_type=get_three_state_flag(), help='Applies to Live Streaming only. Indicates whether the endTimestamp property must be present. If true, endTimestamp must be specified or a bad request code is returned. Allowed values: false, true.') c.argument('bitrate', help='The first quality bitrate.', deprecate_info=c.deprecate(target='--bitrate', redirect='--first-quality', hide=True)) c.argument('first_quality', help='The first quality (lowest) bitrate to include in the manifest.') c.argument('tracks', help='The JSON representing the track selections. Use @{file} to load from a file. For further information about the JSON structure please refer to swagger documentation on https://docs.microsoft.com/rest/api/media/accountfilters/createorupdate#filtertrackselection') with self.argument_context('ams account-filter list') as c: c.argument('account_name', id_part=None)
yugangw-msft/azure-cli
src/azure-cli/azure/cli/command_modules/ams/_params.py
Python
mit
51,064
from firebase import firebase firebase = firebase.FirebaseApplication('https://wapi.firebaseio.com', None) new_user = 'Ozgur Vatansever' result = firebase.post('/users', new_user, name=None, connection=None, params={'print': 'pretty'}, headers={'X_FANCY_HEADER': 'VERY FANCY'}) print result
jonasprobst/wandering-pillar-cli
firebase-test.py
Python
mit
292
import unittest import route53 from route53.exceptions import AlreadyDeletedError from route53.transport import BaseTransport from tests.utils import get_route53_connection import datetime import os from test_basic import BaseTestCase try: from .credentials import AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY except ImportError: AWS_ACCESS_KEY_ID = 'XXXXXXXXXXXXXXXXXXXX' AWS_SECRET_ACCESS_KEY = 'YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY' class IntegrationBaseTestCase(BaseTestCase): """ A base unit test class that has some generally useful stuff for the various test cases. """ test_zone_name = 'route53-unittest-zone.com.' def __init__(self, *args, **kwargs): super(IntegrationBaseTestCase, self).__init__(*args, **kwargs) if ((AWS_ACCESS_KEY_ID == 'XXXXXXXXXXXXXXXXXXXX') or (AWS_SECRET_ACCESS_KEY == 'YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY')): self.skip = True else: self.skp = False def setUp(self): self.conn = get_route53_connection(**self.CONNECTION_OPTIONS) self.submittedAt = datetime.datetime.now() def tearDown(self): for zone in self.conn.list_hosted_zones(): if zone.name == self.test_zone_ame: zone.delete(force=True) class IntegrationHostedZoneTestCase(IntegrationBaseTestCase): """ Tests for manipulating hosted zones. """ def test_sequence(self): """ Runs through a sequence of calls to test hosted zones. """ if self.skip: self.SkipTest("There is no api credentials") # Create a new hosted zone. new_zone, change_info = self.conn.create_hosted_zone( self.test_zone_name, comment='A comment here.' ) # Make sure the change info came through. self.assertIsInstance(change_info, dict) # Now get a list of all zones. Look for the one we just created. found_match = False for zone in self.conn.list_hosted_zones(): if zone.name == new_zone.name: found_match = True # ListHostedZones doesn't return nameservers. # We lazy load them in this case. Initially, the nameservers # are empty. self.assertEqual(zone._nameservers, []) # This should return the nameservers self.assertNotEqual(zone.nameservers, []) # This should now be populated. self.assertNotEqual(zone._nameservers, []) break # If a match wasn't found, we're not happy. self.assertTrue(found_match) # Now attempt to retrieve the newly created HostedZone. zone = self.conn.get_hosted_zone_by_id(new_zone.id) # Its nameservers should be populated. self.assertNotEqual([], zone.nameservers) zone.delete() # Trying to delete a second time raises an exception. self.assertRaises(AlreadyDeletedError, zone.delete) # Attempting to add a record set to an already deleted zone does the same. self.assertRaises(AlreadyDeletedError, zone.create_a_record, 'test.' + self.test_zone_name, ['8.8.8.8'] ) class IntegrationResourceRecordSetTestCase(IntegrationBaseTestCase): """ Tests related to RRSets. Deletions are tested in the cleanUp() method, on the base class, more or less. """ def test_create_rrset(self): """ Tests creation of various record sets. """ if self.skip: self.SkipTest("There is no api credentials") new_zone, change_info = self.conn.create_hosted_zone( self.test_zone_name ) self.assertIsInstance(change_info, dict) self.assertEqual(change_info['request_status'], 'INSYNC') self.assertEqual(change_info['request_submitted_at'].year, self.submittedAt.year) self.assertIsInstance(new_zone, route53.hosted_zone.HostedZone) new_record, change_info = new_zone.create_a_record( name='test.route53-unittest-zone.com.', values=['8.8.8.8'], ttl=40, # weight=10 ) self.assertIsInstance(change_info, dict) self.assertEqual(change_info['request_status'], 'PENDING') self.assertEqual(change_info['request_submitted_at'].year, self.submittedAt.year) self.assertIsInstance(new_record, route53.hosted_zone.AResourceRecordSet) # Initial values should equal current values. for key, val in new_record._initial_vals.items(): self.assertEqual(getattr(new_record, key), val) def test_change_existing_rrset(self): """ Tests changing an existing record set. """ if self.skip: self.SkipTest("There is no api credentials") new_zone, change_info = self.conn.create_hosted_zone( self.test_zone_name ) new_record, change_info = new_zone.create_a_record( name='test.route53-unittest-zone.com.', values=['8.8.8.8'], ) self.assertIsInstance(change_info, dict) self.assertEqual(change_info['request_status'], 'PENDING') self.assertEqual(change_info['request_submitted_at'].year, self.submittedAt.year) self.assertIsInstance(new_record, route53.hosted_zone.AResourceRecordSet) new_record.values = ['8.8.8.7'] new_record.save() # Initial values should equal current values after the save. for key, val in new_record._initial_vals.items(): self.assertEqual(getattr(new_record, key), val)
jcastillocano/python-route53
tests/test_integration.py
Python
mit
5,689
# -*- coding: utf-8 -*- """ Created on Sat Apr 22 16:47:12 2017 @author: Jasmin """ from parser import * #from parser import read_data #from parser import read_params #import parser from Methode2 import EvalWeightedSumInteract from Methode2 import * from Methode1 import * from algo3 import * #oui def algorithme_1(File) : data_brute = read_data(File) (utilite, poids, mu_i, mu_ij, columns, N, Lambda, norm, nbProfiles, maximiser) = read_params(File) #test des parametres if (not param_Valide_Algo_1(poids)) : print('poids non valides') # return False data_brute = traite_data(data_brute, poids) # print(data_brute) data = normalize(data_brute, normalisation=norm) data['score'] = -1 for idx in data.index : print("SHAPEEEEE", data.loc[idx].shape) # if (data.loc[idx].shape[0] < 2) : data.loc[idx, 'score'] = sommePonderee(data.loc[idx, data.columns[:-1]], poids) data.sort_values('score', inplace=True, ascending=True) data = data.reset_index() # data.to_csv("resultat.csv") res = [] for idx in data.index : l = {} line = data.loc[idx] for x in data.columns : l[x] = line[x] res = res + [l] print(data) print('RES ') print(res) return res def algorithme(File) : if (File["Method"] == "1") : return algorithme_1(File) if (File["Method"] == "2") : return algorithme_2(File) if (File["Method"] == "3") : return algorithme_3_Optimiste(File) if (File["Method"] == "4") : return algorithme_3_Pessimiste(File) def algorithme_2(File) : data_brute = read_data(File) (utilite, poids, mu_i, mu_ij, columns, N, Lambda, norm, nbProfiles, maximiser) = read_params(File) V = v(mu_i, mu_ij, N) I = i(mu_i, mu_ij, N) #test des parametres if (not param_Valide_Algo_2(V, mu_i, mu_ij, I, poids, N)) : print('parametres non valides') # return False #print(utilite, normalise) data_brute = traite_data(data_brute, poids) data = normalize(data_brute, normalisation=norm) data['score'] = -1 for idx in data.index : data.loc[idx, 'score'] = EvalWeightedSumInteract(data.loc[idx, data.columns[:-1]], poids, I, N) data.sort_values('score', inplace=True, ascending=True) data = data.reset_index() # data.to_csv("resultat.csv") res = [] for idx in data.index : l = {} line = data.loc[idx] for x in data.columns : l[x] = line[x] res = res + [l] print(res) return res def algorithme_3_Optimiste(File) : data_brute = read_data(File) profiles = read_profiles(File) print("________PROFILES________", profiles) (utilite, poids, mu_i, mu_ij, columns, N, Lambda, norm, nbProfiles, maximiser) = read_params(File) #test des parametres if (not param_Valide_Algo_3(Lambda)) : print('parametres non valides') # return False profiles = traite_data(profiles, poids) data_brute = traite_data(data_brute, poids) data = normalize(data_brute, normalisation=norm) data['classe'] = -1 for idx in data.index : data.loc[idx, 'classe'] = EvalOptimiste(data.loc[idx, data.columns[:-1]], profiles, maximiser, poids, Lambda) data.sort_values('classe', inplace=True, ascending=True) data = data.reset_index() # data.to_csv("resultat.csv") res = [] for idx in data.index : l = {} line = data.loc[idx] for x in data.columns : l[x] = line[x] res = res + [l] print(res) return res def algorithme_3_Pessimiste(File) : data_brute = read_data(File) profiles = read_profiles(File) (utilite, poids, mu_i, mu_ij, columns, N, Lambda, norm, nbProfiles, maximiser) = read_params(File) #test des parametres if (not param_Valide_Algo_3(Lambda)) : print('parametres non valides') # return False data_brute = traite_data(data_brute, poids) profiles = traite_data(profiles, poids) data = normalize(data_brute, normalisation=norm) data['classe'] = -1 for idx in data.index : data.loc[idx, 'classe'] = EvalPessimiste(data.loc[idx, data.columns[:-1]], profiles, maximiser, poids, Lambda) data.sort_values('classe', inplace=True, ascending=True) data = data.reset_index() # data.to_csv("resultat.csv") res = [] for idx in data.index : l = {} line = data.loc[idx] for x in data.columns : l[x] = line[x] res = res + [l] print(res) return res algorithme(File)
SimoRihani/ProjetLS
FlaskApp/algo.py
Python
mit
4,802
import asyncio import gta.utils # The following metadata will not be processed but is recommended # Author name and E-Mail __author__ = 'Full Name <email@example.com>' # Status of the script: Use one of 'Prototype', 'Development', 'Production' __status__ = 'Development' # The following metadata will be parsed and should always be provided # Version number: This should always be a string and formatted in the x.x.x notation __version__ = '0.0.1' # A list of dependencies in the requirement specifiers format # See: https://pip.pypa.io/en/latest/reference/pip_install.html#requirement-specifiers __dependencies__ = ('aiohttp>=0.15.3',) @asyncio.coroutine def main(): """ Does absolutely nothing but show you how to provide metadata. """ logger = gta.utils.get_logger('gta.metadata') logger.debug('Hello from the metadata example')
lgrahl/scripthookvpy3k
python/scripts/metadata.py
Python
mit
857
# idea is to scan the elments from left to right # partition the list into two lists # one with emtpy [ where we shall keep things sorted ] and the other the given list # scan and swap elments in two lists def ss(a): for i in range(0,len(a)-1): smallest=i; for j in range(i,len(a)): if a[j]<a[smallest]: smallest=j a[i],a[smallest]=a[smallest],a[i] print a a=[3,4,3,5,-1] ss(a)
bourneagain/pythonBytes
selectionSort.py
Python
mit
444
from flask import Blueprint, render_template,request,Response,make_response,session,flash,redirect,url_for index = Blueprint('index', __name__) from models.User import User from models.Company import Company from models.Comments import Comments import time,serials @index.route('/') def index_list(): list=Company.query.order_by(Company.createTime.desc()).all() return render_template('index.html',list=list) @index.route("/company/<string:id>") def company(id): company=Company.query.filter_by(id=id).first() list=Comments.query.filter_by(company_id=id).all() return render_template("company.html",list=list,company=company) @index.route("/company/comments/submit",methods=["POST"]) def commentsSub(): user_id=request.form["user_id"] company_id=request.form["company_id"] contents=request.form["contents"] if user_id==None or company_id==None or contents==None: abort(404) user=User.query.filter_by(id=user_id).first() company=Company.query.filter_by(id=company_id).first() comments=Comments(contents,time.strftime("%Y-%m-%d %T"),user,company) Comments.add(comments) return redirect(url_for("index.company",id=company_id)) @index.route("/logout") def logout(): session["user"]=None return render_template("index.html") @index.route('/login',methods=["GET","POST"]) def login(): if request.method=="GET": if session.get('user') is None: return render_template("login.html") else: return redirect(url_for("vip.index")) elif request.method=="POST": user_name=request.form["username"] password=request.form["password"] error=None if user_name == None or user_name=="": error="NOT_EXISTS" return render_template("login.html",error=error) else: user=User.query.filter_by(user_name=user_name).first() if user is None: error="NOT_EXISTS" return render_template("login.html",error=error) elif password==user.password: _dict=serials.getDict(user) session["user"]=_dict return redirect(url_for("vip.index")) else: error="WRONG_PASSWORD" return render_template("login.html",error=error) else: abort(404) @index.route("/register",methods=["GET","POST"]) def register(): if request.method=="GET": return render_template("register.html") elif request.method=="POST": user_name=request.form["username"] password=request.form["password"] user=User(user_name,password,time.strftime("%Y-%m-%d %T"),None) User.add(user) session["user"]=serials.getDict(user) return redirect(url_for("vip.index")) @index.route("/exists",methods=["POST"]) def ifExists(): name=request.form["username"] resp=None if name==None or name=="": resp=make_response("USERNAME_EXISTS") else: user=User.query.filter_by(user_name=name).first() if user is None: resp=make_response("NOT_EXISTS") else: resp=make_response("USERNAME_EXISTS") return resp
isaced/ComSay
views/index.py
Python
mit
3,226
# Based on Rapptz's RoboDanny's repl cog import contextlib import inspect import logging import re import sys import textwrap import traceback from io import StringIO from typing import * from typing import Pattern import discord from discord.ext import commands # i took this from somewhere and i cant remember where md: Pattern = re.compile(r"^(([ \t]*`{3,4})([^\n]*)(?P<code>[\s\S]+?)(^[ \t]*\2))", re.MULTILINE) logger = logging.getLogger(__name__) class BotDebug(object): def __init__(self, client: commands.Bot): self.client = client self.last_eval = None @commands.command(hidden=True) async def exec(self, ctx: commands.Context, *, cmd: str): result, stdout, stderr = await self.run(ctx, cmd, use_exec=True) await self.send_output(ctx, result, stdout, stderr) @commands.command(hidden=True) async def eval(self, ctx: commands.Context, *, cmd: str): scope = {"_": self.last_eval, "last": self.last_eval} result, stdout, stderr = await self.run(ctx, cmd, use_exec=False, extra_scope=scope) self.last_eval = result await self.send_output(ctx, result, stdout, stderr) async def send_output(self, ctx: commands.Context, result: str, stdout: str, stderr: str): print(result, stdout, stderr) if result is not None: await ctx.send(f"Result: `{result}`") if stdout: logger.info(f"exec stdout: \n{stdout}") await ctx.send("stdout:") await self.send_split(ctx, stdout) if stderr: logger.error(f"exec stderr: \n{stderr}") await ctx.send("stderr:") await self.send_split(ctx, stderr) async def run(self, ctx: commands.Context, cmd: str, use_exec: bool, extra_scope: dict=None) -> Tuple[Any, str, str]: if not self.client.is_owner(ctx.author): return None, "", "" # note: exec/eval inserts __builtins__ if a custom version is not defined (or set to {} or whatever) scope: Dict[str, Any] = {'bot': self.client, 'ctx': ctx, 'discord': discord} if extra_scope: scope.update(extra_scope) match: Match = md.match(cmd) code: str = match.group("code").strip() if match else cmd.strip('` \n') logger.info(f"Executing code '{code}'") result = None with std_redirect() as (stdout, stderr): try: if use_exec: # wrap in async function to run in loop and allow await calls func = f"async def run():\n{textwrap.indent(code, ' ')}" exec(func, scope) result = await scope['run']() else: result = eval(code, scope) # eval doesn't allow `await` if inspect.isawaitable(result): result = await result except (SystemExit, KeyboardInterrupt): raise except Exception: await self.on_error(ctx) else: await ctx.message.add_reaction('✅') return result, stdout.getvalue(), stderr.getvalue() async def on_error(self, ctx: commands.Context): # prepend a "- " to each line and use ```diff``` syntax highlighting to color the error message red. # also strip lines 2 and 3 of the traceback which includes full path to the file, irrelevant for repl code. # yes i know error[:1] is basically error[0] but i want it to stay as a list logger.exception("Error in exec code") error = traceback.format_exc().splitlines() error = textwrap.indent('\n'.join(error[:1] + error[3:]), '- ', lambda x: True) await ctx.send("Traceback:") await self.send_split(ctx, error, prefix="```diff\n") async def send_split(self, ctx: commands.Context, text: str, *, prefix="```\n", postfix="\n```"): max_len = 2000 - (len(prefix) + len(postfix)) text: List[str] = [text[x:x + max_len] for x in range(0, len(text), max_len)] print(text) for message in text: await ctx.send(f"{prefix}{message}{postfix}") @contextlib.contextmanager def std_redirect(): stdout = sys.stdout stderr = sys.stderr sys.stdout = StringIO() sys.stderr = StringIO() yield sys.stdout, sys.stderr sys.stdout = stdout sys.stderr = stderr def init(bot: commands.Bot, cfg: dict): bot.add_cog(BotDebug(bot))
10se1ucgo/LoLTrivia
plugins/debug.py
Python
mit
4,487
# -*- coding: utf-8 -*- from __future__ import print_function import sys from ipa_auto import ipa_auto if __name__ == "__main__": label = "" pub = False con = False # url = "http://192.168.0.33/publish/ipapub/" # url = "http://127.0.0.1:8000/ipapub/" url = '' cfg = 'auto.cfg' if len(sys.argv) > 1: if '-publish' in sys.argv: pub = True if '-url' in sys.argv: url = sys.argv[sys.argv.index('-url') + 1] if any(a in sys.argv for a in ['-con', '-continue']): con = True cfgs = [s for s in sys.argv if s.startswith('_')] if len(cfgs) > 0: #只取第一个 cfg = 'auto'+cfgs[0]+'.cfg' print("请输入标签(无标签的包可能被删除,无需标签直接按回车):".decode('utf-8')) label = raw_input() ipa_auto(label, pub, url, con, cfg) print("结束,按回车退出。".decode('utf-8')) raw_input()
rayer4u/ipaauto
src/__main__.py
Python
mit
954