hexsha
stringlengths
40
40
size
int64
4
1.02M
ext
stringclasses
8 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
209
max_stars_repo_name
stringlengths
5
121
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
209
max_issues_repo_name
stringlengths
5
121
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
209
max_forks_repo_name
stringlengths
5
121
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
4
1.02M
avg_line_length
float64
1.07
66.1k
max_line_length
int64
4
266k
alphanum_fraction
float64
0.01
1
302eecf90fe5fc460ada70d4c54a49c6462ba961
996
py
Python
bin/prep-data.py
aranjbar1313/PassGAN
bdc7a9b311c03e53cb8fa4c35f1c918045c539f5
[ "MIT" ]
819
2017-12-20T02:04:08.000Z
2022-03-25T08:38:53.000Z
bin/prep-data.py
aranjbar1313/PassGAN
bdc7a9b311c03e53cb8fa4c35f1c918045c539f5
[ "MIT" ]
16
2017-12-25T23:05:21.000Z
2022-01-05T06:53:33.000Z
bin/prep-data.py
aranjbar1313/PassGAN
bdc7a9b311c03e53cb8fa4c35f1c918045c539f5
[ "MIT" ]
190
2017-12-20T04:36:34.000Z
2022-03-25T21:50:36.000Z
import sys import random random.seed(1337) # run "python make-rockyou-full.py > data/rockyou-full.txt" to create this file # if it doesn't already exist with open('../data/rockyou-full.txt', 'r') as f: # we can't line buffer because we need everything to randomize lines = f.readlines() # filter only passwords with 10 characters or fewer print('[info] filtering rockyou to include only 10 character or less passwords') lines = filter(lambda x: len(x) <= 10, lines) # randomize order print('[info] shuffling rockyou') random.shuffle(lines) split = int(len(lines) * 0.80) with open('../data/train.txt', 'w') as f: print('[info] saving 80% ({}) of dataset for training in ../data/train.txt'.format(split)) f.write(''.join(lines[0:split])) with open('../data/test.txt', 'w') as f: print('[info] saving 20% ({}) of dataset for testing in ../data/test.txt'.format(len(lines) - split)) f.write(''.join(lines[split:]))
33.2
109
0.643574
f3996a6ee11ca10b0c97ca4ea7e53bf4995fad30
54
py
Python
src/models/_imports.py
SamuelSchmidgall/RodentNavigation
2ec49c5f43aa456ba648d1117a1b76241ad7a946
[ "MIT" ]
2
2021-01-03T17:41:02.000Z
2022-02-28T22:37:48.000Z
solver/utils.py
JackFram/Neural-Flow
83cea7aa933fa9650b42271ba4205208814d047b
[ "Apache-2.0" ]
null
null
null
solver/utils.py
JackFram/Neural-Flow
83cea7aa933fa9650b42271ba4205208814d047b
[ "Apache-2.0" ]
1
2022-02-28T22:37:48.000Z
2022-02-28T22:37:48.000Z
import numpy as np import torch import torch.nn as nn
13.5
21
0.796296
8ed44341439cc4a4aaecf06a89192b810f1f5c73
9,734
py
Python
contrib/devtools/symbol-check.py
shaavan/gui-qml
bbb3112dcd456c0ce920e3cc44c4b163fe7fdc1d
[ "MIT" ]
32
2021-06-03T14:45:26.000Z
2022-02-28T09:36:24.000Z
contrib/devtools/symbol-check.py
shaavan/gui-qml
bbb3112dcd456c0ce920e3cc44c4b163fe7fdc1d
[ "MIT" ]
63
2021-06-03T15:56:41.000Z
2022-01-23T13:34:25.000Z
contrib/devtools/symbol-check.py
shaavan/gui-qml
bbb3112dcd456c0ce920e3cc44c4b163fe7fdc1d
[ "MIT" ]
19
2021-06-03T14:40:39.000Z
2022-03-28T19:27:11.000Z
#!/usr/bin/env python3 # Copyright (c) 2014 Wladimir J. van der Laan # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' A script to check that release executables only contain certain symbols and are only linked against allowed libraries. Example usage: find ../path/to/binaries -type f -executable | xargs python3 contrib/devtools/symbol-check.py ''' import sys from typing import List, Dict import lief #type:ignore # temporary constant, to be replaced with lief.ELF.ARCH.RISCV # https://github.com/lief-project/LIEF/pull/562 LIEF_ELF_ARCH_RISCV = lief.ELF.ARCH(243) # Debian 9 (Stretch) EOL: 2022. https://wiki.debian.org/DebianReleases#Production_Releases # # - g++ version 6.3.0 (https://packages.debian.org/search?suite=stretch&arch=any&searchon=names&keywords=g%2B%2B) # - libc version 2.24 (https://packages.debian.org/search?suite=stretch&arch=any&searchon=names&keywords=libc6) # # Ubuntu 16.04 (Xenial) EOL: 2026. https://wiki.ubuntu.com/Releases # # - g++ version 5.3.1 # - libc version 2.23 # # CentOS Stream 8 EOL: 2024. https://wiki.centos.org/About/Product # # - g++ version 8.5.0 (http://mirror.centos.org/centos/8-stream/AppStream/x86_64/os/Packages/) # - libc version 2.28 (http://mirror.centos.org/centos/8-stream/AppStream/x86_64/os/Packages/) # # See https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html for more info. MAX_VERSIONS = { 'GCC': (4,8,0), 'GLIBC': { lief.ELF.ARCH.i386: (2,18), lief.ELF.ARCH.x86_64: (2,18), lief.ELF.ARCH.ARM: (2,18), lief.ELF.ARCH.AARCH64:(2,18), lief.ELF.ARCH.PPC64: (2,18), LIEF_ELF_ARCH_RISCV: (2,27), }, 'LIBATOMIC': (1,0), 'V': (0,5,0), # xkb (bitcoin-qt only) } # See here for a description of _IO_stdin_used: # https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=634261#109 # Ignore symbols that are exported as part of every executable IGNORE_EXPORTS = { '_edata', '_end', '__end__', '_init', '__bss_start', '__bss_start__', '_bss_end__', '__bss_end__', '_fini', '_IO_stdin_used', 'stdin', 'stdout', 'stderr', 'environ', '_environ', '__environ', } # Expected linker-loader names can be found here: # https://sourceware.org/glibc/wiki/ABIList?action=recall&rev=16 ELF_INTERPRETER_NAMES: Dict[lief.ELF.ARCH, Dict[lief.ENDIANNESS, str]] = { lief.ELF.ARCH.i386: { lief.ENDIANNESS.LITTLE: "/lib/ld-linux.so.2", }, lief.ELF.ARCH.x86_64: { lief.ENDIANNESS.LITTLE: "/lib64/ld-linux-x86-64.so.2", }, lief.ELF.ARCH.ARM: { lief.ENDIANNESS.LITTLE: "/lib/ld-linux-armhf.so.3", }, lief.ELF.ARCH.AARCH64: { lief.ENDIANNESS.LITTLE: "/lib/ld-linux-aarch64.so.1", }, lief.ELF.ARCH.PPC64: { lief.ENDIANNESS.BIG: "/lib64/ld64.so.1", lief.ENDIANNESS.LITTLE: "/lib64/ld64.so.2", }, LIEF_ELF_ARCH_RISCV: { lief.ENDIANNESS.LITTLE: "/lib/ld-linux-riscv64-lp64d.so.1", }, } # Allowed NEEDED libraries ELF_ALLOWED_LIBRARIES = { # bitcoind and bitcoin-qt 'libgcc_s.so.1', # GCC base support 'libc.so.6', # C library 'libpthread.so.0', # threading 'libm.so.6', # math library 'librt.so.1', # real-time (clock) 'libatomic.so.1', 'ld-linux-x86-64.so.2', # 64-bit dynamic linker 'ld-linux.so.2', # 32-bit dynamic linker 'ld-linux-aarch64.so.1', # 64-bit ARM dynamic linker 'ld-linux-armhf.so.3', # 32-bit ARM dynamic linker 'ld64.so.1', # POWER64 ABIv1 dynamic linker 'ld64.so.2', # POWER64 ABIv2 dynamic linker 'ld-linux-riscv64-lp64d.so.1', # 64-bit RISC-V dynamic linker # bitcoin-qt only 'libxcb.so.1', # part of X11 'libxkbcommon.so.0', # keyboard keymapping 'libxkbcommon-x11.so.0', # keyboard keymapping 'libfontconfig.so.1', # font support 'libfreetype.so.6', # font parsing 'libdl.so.2', # programming interface to dynamic linker 'libxcb-icccm.so.4', 'libxcb-image.so.0', 'libxcb-shm.so.0', 'libxcb-keysyms.so.1', 'libxcb-randr.so.0', 'libxcb-render-util.so.0', 'libxcb-render.so.0', 'libxcb-shape.so.0', 'libxcb-sync.so.1', 'libxcb-xfixes.so.0', 'libxcb-xinerama.so.0', 'libxcb-xkb.so.1', } MACHO_ALLOWED_LIBRARIES = { # bitcoind and bitcoin-qt 'libc++.1.dylib', # C++ Standard Library 'libSystem.B.dylib', # libc, libm, libpthread, libinfo # bitcoin-qt only 'AppKit', # user interface 'ApplicationServices', # common application tasks. 'Carbon', # deprecated c back-compat API 'ColorSync', 'CoreFoundation', # low level func, data types 'CoreGraphics', # 2D rendering 'CoreServices', # operating system services 'CoreText', # interface for laying out text and handling fonts. 'CoreVideo', # video processing 'Foundation', # base layer functionality for apps/frameworks 'ImageIO', # read and write image file formats. 'IOKit', # user-space access to hardware devices and drivers. 'IOSurface', # cross process image/drawing buffers 'libobjc.A.dylib', # Objective-C runtime library 'Metal', # 3D graphics 'Security', # access control and authentication 'QuartzCore', # animation } PE_ALLOWED_LIBRARIES = { 'ADVAPI32.dll', # security & registry 'IPHLPAPI.DLL', # IP helper API 'KERNEL32.dll', # win32 base APIs 'msvcrt.dll', # C standard library for MSVC 'SHELL32.dll', # shell API 'USER32.dll', # user interface 'WS2_32.dll', # sockets # bitcoin-qt only 'dwmapi.dll', # desktop window manager 'GDI32.dll', # graphics device interface 'IMM32.dll', # input method editor 'NETAPI32.dll', 'ole32.dll', # component object model 'OLEAUT32.dll', # OLE Automation API 'SHLWAPI.dll', # light weight shell API 'USERENV.dll', 'UxTheme.dll', 'VERSION.dll', # version checking 'WINMM.dll', # WinMM audio API 'WTSAPI32.dll', 'd3d11.dll', 'dxgi.dll', } def check_version(max_versions, version, arch) -> bool: (lib, _, ver) = version.rpartition('_') ver = tuple([int(x) for x in ver.split('.')]) if not lib in max_versions: return False if isinstance(max_versions[lib], tuple): return ver <= max_versions[lib] else: return ver <= max_versions[lib][arch] def check_imported_symbols(binary) -> bool: ok: bool = True for symbol in binary.imported_symbols: if not symbol.imported: continue version = symbol.symbol_version if symbol.has_version else None if version: aux_version = version.symbol_version_auxiliary.name if version.has_auxiliary_version else None if aux_version and not check_version(MAX_VERSIONS, aux_version, binary.header.machine_type): print(f'{filename}: symbol {symbol.name} from unsupported version {version}') ok = False return ok def check_exported_symbols(binary) -> bool: ok: bool = True for symbol in binary.dynamic_symbols: if not symbol.exported: continue name = symbol.name if binary.header.machine_type == LIEF_ELF_ARCH_RISCV or name in IGNORE_EXPORTS: continue print(f'{binary.name}: export of symbol {name} not allowed!') ok = False return ok def check_ELF_libraries(binary) -> bool: ok: bool = True for library in binary.libraries: if library not in ELF_ALLOWED_LIBRARIES: print(f'{filename}: {library} is not in ALLOWED_LIBRARIES!') ok = False return ok def check_MACHO_libraries(binary) -> bool: ok: bool = True for dylib in binary.libraries: split = dylib.name.split('/') if split[-1] not in MACHO_ALLOWED_LIBRARIES: print(f'{split[-1]} is not in ALLOWED_LIBRARIES!') ok = False return ok def check_MACHO_min_os(binary) -> bool: if binary.build_version.minos == [10,15,0]: return True return False def check_MACHO_sdk(binary) -> bool: if binary.build_version.sdk == [10, 15, 6]: return True return False def check_PE_libraries(binary) -> bool: ok: bool = True for dylib in binary.libraries: if dylib not in PE_ALLOWED_LIBRARIES: print(f'{dylib} is not in ALLOWED_LIBRARIES!') ok = False return ok def check_PE_subsystem_version(binary) -> bool: major: int = binary.optional_header.major_subsystem_version minor: int = binary.optional_header.minor_subsystem_version if major == 6 and minor == 1: return True return False def check_ELF_interpreter(binary) -> bool: expected_interpreter = ELF_INTERPRETER_NAMES[binary.header.machine_type][binary.abstract.header.endianness] return binary.concrete.interpreter == expected_interpreter CHECKS = { lief.EXE_FORMATS.ELF: [ ('IMPORTED_SYMBOLS', check_imported_symbols), ('EXPORTED_SYMBOLS', check_exported_symbols), ('LIBRARY_DEPENDENCIES', check_ELF_libraries), ('INTERPRETER_NAME', check_ELF_interpreter), ], lief.EXE_FORMATS.MACHO: [ ('DYNAMIC_LIBRARIES', check_MACHO_libraries), ('MIN_OS', check_MACHO_min_os), ('SDK', check_MACHO_sdk), ], lief.EXE_FORMATS.PE: [ ('DYNAMIC_LIBRARIES', check_PE_libraries), ('SUBSYSTEM_VERSION', check_PE_subsystem_version), ] } if __name__ == '__main__': retval: int = 0 for filename in sys.argv[1:]: try: binary = lief.parse(filename) etype = binary.format if etype == lief.EXE_FORMATS.UNKNOWN: print(f'{filename}: unknown executable format') retval = 1 continue failed: List[str] = [] for (name, func) in CHECKS[etype]: if not func(binary): failed.append(name) if failed: print(f'{filename}: failed {" ".join(failed)}') retval = 1 except IOError: print(f'{filename}: cannot open') retval = 1 sys.exit(retval)
32.66443
113
0.672694
dc006ce91a5aa814b32dbd6370ccc8031dea840e
1,115
py
Python
scripts/AlignOrientedReads.py
jeizenga/shasta
0948628124ba5c3dd9dcd071e88017ee453b4c54
[ "MIT" ]
null
null
null
scripts/AlignOrientedReads.py
jeizenga/shasta
0948628124ba5c3dd9dcd071e88017ee453b4c54
[ "MIT" ]
null
null
null
scripts/AlignOrientedReads.py
jeizenga/shasta
0948628124ba5c3dd9dcd071e88017ee453b4c54
[ "MIT" ]
null
null
null
#!/usr/bin/python3 import shasta import GetConfig import sys helpMessage = """ This computes a marker alignment of two oriented reads. Invoke with four arguments: readId0, strand0, readId1, strand1. """ # Get the arguments. if not len(sys.argv) == 5: print(helpMessage) exit(1) readId0 = int(sys.argv[1]); strand0 = int(sys.argv[2]); readId1 = int(sys.argv[3]); strand1 = int(sys.argv[4]); # Read the config file. config = GetConfig.getConfig() # Initialize the assembler and access what we need. a = shasta.Assembler() a.accessKmers() a.accessReadsReadOnly() a.accessReadNamesReadOnly() a.accessMarkers() # For convenience, write the markers sorted by position. a.writeMarkers(readId=readId0, strand=strand0, fileName = 'Markers-ByPosition-0.csv') a.writeMarkers(readId=readId1, strand=strand1, fileName = 'Markers-ByPosition-1.csv') # Compute the alignment. a.alignOrientedReads( readId0 = readId0, strand0 = strand0, readId1 = readId1, strand1 = strand1, maxSkip = int(config['Align']['maxSkip']), maxVertexCountPerKmer = int(config['Align']['maxVertexCountPerKmer']))
24.777778
74
0.724664
47d35052049f0c94aeaba81bf4b40b2d0493a73c
2,234
py
Python
fuzzinator/call/regex_filter.py
akosthekiss/fuzzinator
194e199bb0efea26b857ad05f381f72e7a9b8f66
[ "BSD-3-Clause" ]
null
null
null
fuzzinator/call/regex_filter.py
akosthekiss/fuzzinator
194e199bb0efea26b857ad05f381f72e7a9b8f66
[ "BSD-3-Clause" ]
null
null
null
fuzzinator/call/regex_filter.py
akosthekiss/fuzzinator
194e199bb0efea26b857ad05f381f72e7a9b8f66
[ "BSD-3-Clause" ]
1
2018-06-28T05:21:21.000Z
2018-06-28T05:21:21.000Z
# Copyright (c) 2016-2021 Renata Hodovan, Akos Kiss. # # Licensed under the BSD 3-Clause License # <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>. # This file may not be copied, modified, or distributed except # according to those terms. import re from ..config import as_list from .call_decorator import CallDecorator from .non_issue import NonIssue class RegexFilter(CallDecorator): """ Decorator filter for SUT calls to recognise patterns in the returned issue dictionaries. **Optional parameters of the decorator:** - key: array of patterns to match against ``issue[key]`` (note that 'key' can be arbitrary, and multiple different keys can be given to the decorator). If none of the patterns matches on any of the fields, the issue is filtered out. The issues that are not filtered out are extended with keys-values from the named groups of the matching regex pattern. **Example configuration snippet:** .. code-block:: ini [sut.foo] call=fuzzinator.call.StdinSubprocessCall call.decorate(0)=fuzzinator.call.RegexFilter [sut.foo.call] command=/home/alice/foo/bin/foo - [sut.foo.call.decorate(0)] stderr=["(?P<file>[^:]+):(?P<line>[0-9]+): (?P<func>[^:]+): (?P<msg>Assertion `.*' failed)"] backtrace=["#[0-9]+ +0x[0-9a-f]+ in (?P<path>[^ ]+) .*? at (?P<file>[^:]+):(?P<line>[0-9]+)"] """ def __init__(self, **kwargs): self.patterns = {} for field, patterns_str in kwargs.items(): self.patterns[field] = [re.compile(pattern, flags=re.MULTILINE | re.DOTALL) for pattern in as_list(patterns_str)] def call(self, cls, obj, *, test, **kwargs): issue = super(cls, obj).__call__(test=test, **kwargs) if not issue: return issue updated = False for field, field_patterns in self.patterns.items(): for pattern in field_patterns: match = pattern.search(issue.get(field, '')) if match is not None: issue.update(match.groupdict()) updated = True return issue if updated else NonIssue(issue)
35.460317
125
0.621307
8e80130dcbb531c16a5b1a0fad5b7db6b1d3fc8e
6,970
py
Python
entities/test_parsers.py
acdh-oeaw/apisbaseproject
bb3a6ec280cb431e6252c4595f425261b6c551c9
[ "MIT" ]
null
null
null
entities/test_parsers.py
acdh-oeaw/apisbaseproject
bb3a6ec280cb431e6252c4595f425261b6c551c9
[ "MIT" ]
6
2018-06-13T15:05:30.000Z
2021-06-10T20:15:37.000Z
entities/test_parsers.py
acdh-oeaw/metarita
de7484adc689fcb461cbe0abe40672e05e78e37e
[ "MIT" ]
null
null
null
from django.test import TestCase from django.contrib.auth.models import User, Group from .models import Person, Place, Institution, Work, Event from metainfo.models import Text, Collection, Source, Uri, UriCandidate from vocabularies.models import PersonPlaceRelation from labels.models import Label from relations.models import PersonPlace, PlacePlace from reversion.models import Version from reversion import revisions as reversion from helper_functions.RDFparsers import GenericRDFParser from datetime import datetime from guardian.shortcuts import assign_perm, remove_perm, get_objects_for_user from rest_framework.authtoken.models import Token from rest_framework.test import APIClient from django.contrib.auth.models import Permission from django.db.models import Q class RDFPersonParserTestCase(TestCase): #fixtures = ['fixtures_3_5_17.json'] uriP = 'http://d-nb.info/gnd/11868499X' kindP = 'Person' uriGeon = 'http://sws.geonames.org/2761369/' def test_parse_person(self): print('Number of Persons: {}'.format(Person.objects.all().count())) o = GenericRDFParser(self.uriP, self.kindP) o2 = o.save() print('got following person: {}'.format(o2)) self.assertEqual(o.objct.name, 'Eosander') self.assertEqual(o.objct.first_name, 'Johann Friedrich') def test_place_of_birth_death(self): o = GenericRDFParser(self.uriP, self.kindP) p2 = o.save() print(p2.start_date) print(p2.end_date) rel_type_birth = PersonPlaceRelation.objects.get(name='place of birth') rel_type_death = PersonPlaceRelation.objects.get(name='place of death') rel_birth = PersonPlace.objects.get(related_person=o.objct, relation_type=rel_type_birth) rel_death = PersonPlace.objects.get(related_person=o.objct, relation_type=rel_type_death) self.assertEqual(rel_birth.related_place.name, 'Stralsund') self.assertEqual(rel_death.related_place.name, 'Dresden') plc_list = Label.objects.filter(temp_entity=rel_death.related_place).values_list('label',flat=True) print(plc_list) self.assertTrue('Dressden' in plc_list) self.assertEqual(rel_death.related_place.lat, 13.738319) print('lat: {}, lng: {}'.format(rel_death.related_place.lat, rel_death.related_place.lng)) def test_merge_places(self): txt = Text.objects.create(text='test text') src = Source.objects.create(orig_id=24, pubinfo='test pub') pp = Place(name="Wien") pp.source = src pp.save() pp.text.add(txt) rel_type_birth = PersonPlaceRelation.objects.create(name='place of birth') pers = Person.objects.create(name="tesdt", first_name="test3") rel_1 = PersonPlace.objects.create(related_person=pers, relation_type=rel_type_birth, related_place=pp) ow = GenericRDFParser(self.uriGeon, 'Place') print('name: {}, lat: {}, long: {}, labels: {}'.format(ow.objct.name, ow.objct.lat, ow.objct.lng, ' / '.join( Label.objects.filter(temp_entity=ow.objct).values_list('label', flat=True)))) if ow.created: print('created triggered') ow.save() ow2 = ow.merge(pp) print(ow) print(ow2) self.assertEqual(pp.source.pubinfo, ow.objct.source.pubinfo) self.assertEqual(txt.text, ow.objct.text.all()[0].text) for x in PersonPlace.objects.all(): self.assertEqual(x.related_place.pk, ow.objct.pk) class RDFPlaceParserTestCase(TestCase): #fixtures = ['fixtures_3_5_17.json'] kindP = 'Place' uriGeon = 'http://sws.geonames.org/2761369/' uri_gnd_geo = 'http://d-nb.info/gnd/4023118-5' def test_parse_place(self): o = GenericRDFParser(self.uriGeon, self.kindP) o2 = o.save() print('name: {}, lat: {}, long: {}, labels: {}, kind: {}'.format(o2.place.name, o2.place.lat, o2.place.lng, ' / '.join(Label.objects.filter(temp_entity=o2.place).values_list('label', flat=True)), o2.kind.name)) t = GenericRDFParser(self.uri_gnd_geo, self.kindP) t2 = t.save() print('name: {}, lat: {}, long: {}, labels: {}'.format(t2.name, t2.lat, t2.lng, ' / '.join( Label.objects.filter(temp_entity=t2).values_list('label', flat=True)))) self.assertEqual(o2.lat, '48.20849') self.assertEqual(t2.lat, '053.583329') def test_merge_place(self): col = Collection.objects.create(name='test coll one') col2 = Collection.objects.create(name='test coll 2') w1 = Place.objects.create(name='Wien 21 test') w1.collection.add(col) w1.collection.add(col2) w1_label = Label.objects.create(label='Wien label 1', temp_entity=w1) w1_uri = Uri.objects.create(uri='http://test.uri.ac.at/orig:id', entity=w1) o = GenericRDFParser(self.uriGeon, self.kindP) o2 = o.save() o.merge(w1) for col in o2.collection.all(): print('collection: {}'.format(col.name)) self.assertEqual(Label.objects.filter(temp_entity=o2, label='Wien label 1').count(), 1) self.assertEqual(Uri.objects.filter(entity=o2, uri='http://test.uri.ac.at/orig:id').count(), 1) self.assertEqual( Label.objects.filter(label='Wien 21 test', temp_entity=o2, label_type__name='legacy name').count(), 1) self.assertEqual(o2.collection.all().count(), 3) def test_related_places(self): o = GenericRDFParser(self.uriGeon, self.kindP) o2 = o.save() print(o2) print('related_objects: {}'.format(o.related_objcts)) print('number of placeplace: {}'.format(PlacePlace.objects.all().count())) pp = PlacePlace.objects.filter(Q(related_placeA=o2)|Q(related_placeB=o2)) self.assertEqual(pp.count(), 2) def test_existing_place(self): c = GenericRDFParser('http://sws.geonames.org/2782113/', self.kindP) c.save() o = GenericRDFParser(self.uriGeon, self.kindP) o2 = o.save() Uri.objects.create(uri='http://test.at', entity=o2) pp = PlacePlace.objects.filter(Q(related_placeA=o2) | Q(related_placeB=o2)) self.assertEqual(pp.count(), 2) for p in Place.objects.all(): print('name: {}, uri: {}'.format(p.name, ' / '.join(p.uri_set.all().values_list('uri', flat=True)))) cc = Place.objects.filter(uri__uri__icontains='http://sws.geonames.org/2782113').distinct() self.assertEqual(cc.count(), 1) i = GenericRDFParser(self.uriGeon, self.kindP) i2 = i.save() print(' / '.join(i.objct.uri_set.all().values_list('uri', flat=True))) print(i.objct) cc = Place.objects.filter(uri__uri=self.uriGeon).distinct() self.assertEqual(cc.count(), 1)
48.402778
150
0.646341
be9a888b81c67e05af8f2bd626ac2a130593c429
5,245
py
Python
ChoreographyHive/choreography/choreos/air_show.py
jeroen11dijk/Choreography
aadafb86fb86445489afed4535c852801097168e
[ "MIT" ]
null
null
null
ChoreographyHive/choreography/choreos/air_show.py
jeroen11dijk/Choreography
aadafb86fb86445489afed4535c852801097168e
[ "MIT" ]
null
null
null
ChoreographyHive/choreography/choreos/air_show.py
jeroen11dijk/Choreography
aadafb86fb86445489afed4535c852801097168e
[ "MIT" ]
null
null
null
from typing import List from rlbot.utils.structures.game_data_struct import GameTickPacket from rlbot.utils.structures.game_interface import GameInterface from choreography.choreography_main import Choreography from choreography.drone import Drone from choreography.group_step import BlindBehaviorStep, StateSettingStep, ParallelStep, DroneListStep from choreography.paths.AirShowPath import get_paths from choreography.utils.vector_math import direction from rlutilities.linear_algebra import vec3, look_at, cross, normalize from rlutilities.simulation import Ball, Input, Curve class Pause(BlindBehaviorStep): duration = 8 target_indexes = range(0, 2) def set_controls(self, controls: Input): pass class BlueTouchesTHeBall(StateSettingStep): def set_drone_states(self, drones: List[Drone]): drones[1].position = vec3(0, -5000, 250) drones[1].velocity = vec3(0, 0, 0) drones[1].angular_velocity = vec3(0, 0, 0) def set_ball_state(self, ball: Ball): ball.position = vec3(0, -5000, 100) ball.velocity = vec3(0, 0, 0) ball.angular_velocity = vec3(0, 0, 0) class YeetTheBallOutOfTheUniverse(StateSettingStep): def set_ball_state(self, ball: Ball): ball.position = vec3(0, 0, 3000) ball.velocity = vec3(0, 0, 0) ball.angular_velocity = vec3(0, 0, 0) class Score(StateSettingStep): def set_ball_state(self, ball: Ball): ball.position = vec3(0, 5120, 300) ball.velocity = vec3(0, 5000, 0) ball.angular_velocity = vec3(0, 0, 0) class DoNothing(StateSettingStep): pass class SetupHover(StateSettingStep): def set_drone_states(self, drones: List[Drone]): drone = drones[1] drone.position = vec3(-1500, 500, 800) drone.velocity = vec3(0, 0, 0) drone.angular_velocity = vec3(0, 0, 0) drone.orientation = look_at(vec3(0, 0, 500), vec3(0, 0, 1)) class Fly(StateSettingStep): duration = 5 distance_between_body_parts = 300 curve: Curve = None def set_drone_states(self, drones: List[Drone]): for drone in drones: t = self.time_since_start / self.duration * self.curve.length t -= self.distance_between_body_parts * (drone.id - self.target_indexes[0]) t = self.curve.length - t pos = self.curve.point_at(t) pos_ahead = self.curve.point_at(t - 500) pos_behind = self.curve.point_at(t + 30) facing_direction = direction(pos_behind, pos) target_left = cross(facing_direction, direction(pos, pos_ahead)) target_up = cross(target_left, facing_direction) up = drone.up() + target_up * 0.9 + vec3(0, 0, 0.1) target_orientation = look_at(facing_direction, up) drone.position = pos drone.velocity = facing_direction * (self.curve.length / self.duration) drone.angular_velocity = vec3(0, 0, 0) drone.orientation = target_orientation drone.boost = True class Hover(DroneListStep): def step(self, packet: GameTickPacket, drones: List[Drone]): drone = drones[1] drone.hover.up = normalize(drone.position) drone.hover.target = drone.position drone.hover.step(self.dt) drone.controls = drone.hover.controls class bot0(Fly): curve = Curve(get_paths()[0].to_points(1000)) target_indexes = range(0, 1) class bot1(Fly): curve = Curve(get_paths()[1].to_points(1000)) target_indexes = range(1, 2) class bot2(Fly): curve = Curve(get_paths()[2].to_points(1000)) target_indexes = range(2, 3) class bot3(Fly): curve = Curve(get_paths()[3].to_points(1000)) target_indexes = range(3, 4) class bot4(Fly): curve = Curve(get_paths()[4].to_points(1000)) target_indexes = range(4, 5) class bot5(Fly): curve = Curve(get_paths()[5].to_points(1000)) target_indexes = range(5, 6) class bot6(Fly): curve = Curve(get_paths()[6].to_points(1000)) target_indexes = range(6, 7) class bot7(Fly): curve = Curve(get_paths()[7].to_points(1000)) target_indexes = range(7, 8) class bot8(Fly): curve = Curve(get_paths()[8].to_points(1000)) target_indexes = range(8, 9) class Boost(BlindBehaviorStep): duration = 10 target_indexes = range(0, 10) def set_controls(self, controls: Input): controls.boost = True class AirShow(Choreography): @staticmethod def get_appearances(num_bots: int) -> List[str]: appearances = ['default.cfg'] * num_bots appearances[0] = 'AirShowBlue.cfg' appearances[1] = 'AirShowBlue.cfg' return appearances @staticmethod def get_teams(num_bots: int) -> List[int]: # Every other bot is on the orange team. teams = [0] * num_bots teams[0] = 0 teams[1] = 0 return teams @staticmethod def get_num_bots(): return 2 def __init__(self, game_interface: GameInterface): super().__init__(game_interface) def generate_sequence(self): self.sequence = [ Pause(), BlueTouchesTHeBall(), bot0(), Score(), DoNothing(), ]
28.198925
100
0.648808
7259ec90bc7cfd0ca14b601673312d8dbc8654fc
7,112
py
Python
Course5-Sequence Models/Week1/Jazz Improvisation with LSTM/data_utils.py
savnani5/Deep-Learning-Specialization-Coursera
865469a1f20a1878674f98e0a7043f7c753575df
[ "BSD-Source-Code" ]
15
2021-11-03T04:33:22.000Z
2022-03-30T18:24:57.000Z
Sequence Models/week1/w1a3/data_utils.py
got69/Deep-Learning-Specialization-Coursera
8ae1bc70bda5374facdb91dca62f0258a34c16a6
[ "Apache-2.0" ]
null
null
null
Sequence Models/week1/w1a3/data_utils.py
got69/Deep-Learning-Specialization-Coursera
8ae1bc70bda5374facdb91dca62f0258a34c16a6
[ "Apache-2.0" ]
21
2021-11-03T04:34:11.000Z
2022-03-22T10:17:06.000Z
from music_utils import * from preprocess import * from tensorflow.keras.utils import to_categorical from collections import defaultdict from mido import MidiFile from pydub import AudioSegment from pydub.generators import Sine import math #chords, abstract_grammars = get_musical_data('data/original_metheny.mid') #corpus, tones, tones_indices, indices_tones = get_corpus_data(abstract_grammars) #N_tones = len(set(corpus)) n_a = 64 x_initializer = np.zeros((1, 1, 90)) a_initializer = np.zeros((1, n_a)) c_initializer = np.zeros((1, n_a)) def load_music_utils(file): chords, abstract_grammars = get_musical_data(file) corpus, tones, tones_indices, indices_tones = get_corpus_data(abstract_grammars) N_tones = len(set(corpus)) X, Y, N_tones = data_processing(corpus, tones_indices, 60, 30) return (X, Y, N_tones, indices_tones, chords) def generate_music(inference_model, indices_tones, chords, diversity = 0.5): """ Generates music using a model trained to learn musical patterns of a jazz soloist. Creates an audio stream to save the music and play it. Arguments: model -- Keras model Instance, output of djmodel() indices_tones -- a python dictionary mapping indices (0-77) into their corresponding unique tone (ex: A,0.250,< m2,P-4 >) temperature -- scalar value, defines how conservative/creative the model is when generating music Returns: predicted_tones -- python list containing predicted tones """ # set up audio stream out_stream = stream.Stream() # Initialize chord variables curr_offset = 0.0 # variable used to write sounds to the Stream. num_chords = int(len(chords) / 3) # number of different set of chords print("Predicting new values for different set of chords.") # Loop over all 18 set of chords. At each iteration generate a sequence of tones # and use the current chords to convert it into actual sounds for i in range(1, num_chords): # Retrieve current chord from stream curr_chords = stream.Voice() # Loop over the chords of the current set of chords for j in chords[i]: # Add chord to the current chords with the adequate offset, no need to understand this curr_chords.insert((j.offset % 4), j) # Generate a sequence of tones using the model _, indices = predict_and_sample(inference_model) indices = list(indices.squeeze()) pred = [indices_tones[p] for p in indices] predicted_tones = 'C,0.25 ' for k in range(len(pred) - 1): predicted_tones += pred[k] + ' ' predicted_tones += pred[-1] #### POST PROCESSING OF THE PREDICTED TONES #### # We will consider "A" and "X" as "C" tones. It is a common choice. predicted_tones = predicted_tones.replace(' A',' C').replace(' X',' C') # Pruning #1: smoothing measure predicted_tones = prune_grammar(predicted_tones) # Use predicted tones and current chords to generate sounds sounds = unparse_grammar(predicted_tones, curr_chords) # Pruning #2: removing repeated and too close together sounds sounds = prune_notes(sounds) # Quality assurance: clean up sounds sounds = clean_up_notes(sounds) # Print number of tones/notes in sounds print('Generated %s sounds using the predicted values for the set of chords ("%s") and after pruning' % (len([k for k in sounds if isinstance(k, note.Note)]), i)) # Insert sounds into the output stream for m in sounds: out_stream.insert(curr_offset + m.offset, m) for mc in curr_chords: out_stream.insert(curr_offset + mc.offset, mc) curr_offset += 4.0 # Initialize tempo of the output stream with 130 bit per minute out_stream.insert(0.0, tempo.MetronomeMark(number=130)) # Save audio stream to fine mf = midi.translate.streamToMidiFile(out_stream) mf.open("output/my_music.midi", 'wb') mf.write() print("Your generated music is saved in output/my_music.midi") mf.close() # Play the final stream through output (see 'play' lambda function above) # play = lambda x: midi.realtime.StreamPlayer(x).play() # play(out_stream) return out_stream def predict_and_sample(inference_model, x_initializer = x_initializer, a_initializer = a_initializer, c_initializer = c_initializer): """ Predicts the next value of values using the inference model. Arguments: inference_model -- Keras model instance for inference time x_initializer -- numpy array of shape (1, 1, 78), one-hot vector initializing the values generation a_initializer -- numpy array of shape (1, n_a), initializing the hidden state of the LSTM_cell c_initializer -- numpy array of shape (1, n_a), initializing the cell state of the LSTM_cel Ty -- length of the sequence you'd like to generate. Returns: results -- numpy-array of shape (Ty, 78), matrix of one-hot vectors representing the values generated indices -- numpy-array of shape (Ty, 1), matrix of indices representing the values generated """ ### START CODE HERE ### pred = inference_model.predict([x_initializer, a_initializer, c_initializer]) indices = np.argmax(pred, axis = -1) results = to_categorical(indices, num_classes=90) ### END CODE HERE ### return results, indices def note_to_freq(note, concert_A=440.0): ''' from wikipedia: http://en.wikipedia.org/wiki/MIDI_Tuning_Standard#Frequency_values ''' return (2.0 ** ((note - 69) / 12.0)) * concert_A def ticks_to_ms(ticks, tempo, mid): tick_ms = math.ceil((60000.0 / tempo) / mid.ticks_per_beat) return ticks * tick_ms def mid2wav(file): mid = MidiFile(file) output = AudioSegment.silent(mid.length * 1000.0) tempo = 130 # bpm for track in mid.tracks: # position of rendering in ms current_pos = 0.0 current_notes = defaultdict(dict) for msg in track: current_pos += ticks_to_ms(msg.time, tempo, mid) if msg.type == 'note_on': if msg.note in current_notes[msg.channel]: current_notes[msg.channel][msg.note].append((current_pos, msg)) else: current_notes[msg.channel][msg.note] = [(current_pos, msg)] if msg.type == 'note_off': start_pos, start_msg = current_notes[msg.channel][msg.note].pop() duration = math.ceil(current_pos - start_pos) signal_generator = Sine(note_to_freq(msg.note, 500)) #print(duration) rendered = signal_generator.to_audio_segment(duration=duration-50, volume=-20).fade_out(100).fade_in(30) output = output.overlay(rendered, start_pos) output.export("./output/rendered.wav", format="wav")
39.076923
170
0.655371
542aece556cdb41b231223c47fbb1adc5acea1bd
1,921
py
Python
source/interprocedural_analyses/taint/test/integration/model_query_transitive_extends.py
joehendrix/pyre-check
23693455b1e0b4a7287efba9337be6bbfe23ada4
[ "MIT" ]
1
2022-02-10T10:51:32.000Z
2022-02-10T10:51:32.000Z
source/interprocedural_analyses/taint/test/integration/model_query_transitive_extends.py
joehendrix/pyre-check
23693455b1e0b4a7287efba9337be6bbfe23ada4
[ "MIT" ]
null
null
null
source/interprocedural_analyses/taint/test/integration/model_query_transitive_extends.py
joehendrix/pyre-check
23693455b1e0b4a7287efba9337be6bbfe23ada4
[ "MIT" ]
null
null
null
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from builtins import _test_sink, _test_source class Test1_C: attribute = ... def __init__(self): self.instance = ... class Test1_C1(Test1_C): attribute = ... def __init__(self): self.instance = ... class Test1_C2(Test1_C1): attribute = ... def __init__(self): self.instance = ... class Test1_D: attribute = ... def __init__(self): self.instance = ... class Test2_C: def foo(self, attribute): ... class Test2_C1(Test2_C): def foo(self, attribute): ... class Test2_C2(Test2_C1): def foo(self, attribute): ... class Test2_D: def foo(self, attribute): ... class UnrelatedClass: attribute = ... def __init__(self): self.instance = ... def foo(self, x): ... def test1_alarm1(c: Test1_C1): _test_sink(c.attribute) def test1_alarm2(c: Test1_C1): _test_sink(c.instance) def test1_alarm3(c: Test1_C2): _test_sink(c.attribute) def test1_alarm4(c: Test1_C2): _test_sink(c.instance) def test1_alarm5(c: Test1_C): _test_sink(c.attribute) def test1_alarm6(c: Test1_C): _test_sink(c.instance) def test1_noalarm1(c: Test1_D): _test_sink(c.attribute) def test1_noalarm2(c: Test1_D): _test_sink(c.instance) def test2_alarm1(c: Test2_D): c.foo(_test_source()) def test2_noalarm1(c: Test2_C1): c.foo(_test_source()) def test2_noalarm2(c: Test2_C2): c.foo(_test_source()) def test2_noalarm3(c: Test2_C): c.foo(_test_source()) def misc_noalarm1(c: UnrelatedClass): _test_sink(c.attribute) def misc_noalarm2(c: UnrelatedClass): _test_sink(c.instance) def misc_noalarm3(c: UnrelatedClass): c.foo(_test_source())
15.368
65
0.651744
7aab357b135ead6a16ea11c000719157fb86522b
847
py
Python
examples/example10.py
Freakwill/pyrimidine
ff05998f110a69a002180d0dae2ae514a5807cfb
[ "MIT" ]
1
2021-03-04T17:03:14.000Z
2021-03-04T17:03:14.000Z
examples/example10.py
Freakwill/pyrimidine
ff05998f110a69a002180d0dae2ae514a5807cfb
[ "MIT" ]
null
null
null
examples/example10.py
Freakwill/pyrimidine
ff05998f110a69a002180d0dae2ae514a5807cfb
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from pyrimidine import MonoBinaryIndividual from pyrimidine.population import * from pyrimidine.benchmarks.optimization import * n = 50 _evaluate = Knapsack.random(n) class MyIndividual(MonoBinaryIndividual): def _fitness(self): return _evaluate(self.chromosome) def dual(self): return MyIndividual([c.dual() for c in self]) # MyIndividual = MonoBinaryIndividual.set_fitness(lambda o: _evaluate(o.chromosome)) pop = MyIndividual.random(size=n) * 20 stat={'Mean Fitness':'fitness', 'Best Fitness':'best_fitness'} data = pop.evolve(stat=stat, n_iter=200, history=True) import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) data[['Mean Fitness', 'Best Fitness']].plot(ax=ax) ax.set_xlabel('Generations') ax.set_ylabel('Fitness') plt.show()
23.527778
84
0.726092
3874c2cf95674e03bfd1b00014dfaaf0e0a9a84e
628
py
Python
python/data-wrangling-components/tests/engine/test_difference.py
microsoft/data-wrangling-components
4be99ceb3a0d64ff7cac69d4eb1b7c81b1da9aff
[ "MIT" ]
4
2021-12-16T01:43:36.000Z
2022-03-26T22:28:59.000Z
python/data-wrangling-components/tests/engine/test_difference.py
microsoft/data-wrangling-components
4be99ceb3a0d64ff7cac69d4eb1b7c81b1da9aff
[ "MIT" ]
5
2022-02-08T21:12:44.000Z
2022-03-15T23:42:56.000Z
python/data-wrangling-components/tests/engine/test_difference.py
microsoft/data-wrangling-components
4be99ceb3a0d64ff7cac69d4eb1b7c81b1da9aff
[ "MIT" ]
3
2022-02-14T17:46:25.000Z
2022-03-25T20:38:25.000Z
# # Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE file in the project. # from data_wrangling_components.engine.verbs.difference import difference from data_wrangling_components.types import Step, Verb from tests.engine.test_store import get_test_store def test_difference_no_duplicates(): step = Step( Verb.Difference, "table1", "output", args={"others": ["table2"]}, ) store = get_test_store() result = difference(step, store) assert len(result.table.columns) == 3 assert len(result.table) == 5
25.12
73
0.671975
b18fe412ed939214bb14b30d9a31104389dc68c7
7,533
py
Python
packnet_sfm/utils/image.py
wbkit/packnet-sfm
21e62ed163587f5b1538b8bb4f6e669b9c4e2804
[ "MIT" ]
null
null
null
packnet_sfm/utils/image.py
wbkit/packnet-sfm
21e62ed163587f5b1538b8bb4f6e669b9c4e2804
[ "MIT" ]
null
null
null
packnet_sfm/utils/image.py
wbkit/packnet-sfm
21e62ed163587f5b1538b8bb4f6e669b9c4e2804
[ "MIT" ]
null
null
null
# Copyright 2020 Toyota Research Institute. All rights reserved. import cv2 import torch import torch.nn.functional as funct from functools import lru_cache from PIL import Image from packnet_sfm.utils.misc import same_shape def load_image(path): """ Read an image using PIL Parameters ---------- path : str Path to the image Returns ------- image : PIL.Image Loaded image """ return Image.open(path) def write_image(filename, image): """ Write an image to file. Parameters ---------- filename : str File where image will be saved image : np.array [H,W,3] RGB image """ cv2.imwrite(filename, image[:, :, ::-1]) def flip_lr(image): """ Flip image horizontally Parameters ---------- image : torch.Tensor [B,3,H,W] Image to be flipped Returns ------- image_flipped : torch.Tensor [B,3,H,W] Flipped image """ assert image.dim() == 4, 'You need to provide a [B,C,H,W] image to flip' return torch.flip(image, [3]) def flip_model(model, image, flip): """ Flip input image and flip output inverse depth map Parameters ---------- model : nn.Module Module to be used image : torch.Tensor [B,3,H,W] Input image flip : bool True if the flip is happening Returns ------- inv_depths : list of torch.Tensor [B,1,H,W] List of predicted inverse depth maps """ if flip: return [flip_lr(inv_depth) for inv_depth in model(flip_lr(image))] else: return model(image) ######################################################################################################################## def gradient_x(image): """ Calculates the gradient of an image in the x dimension Parameters ---------- image : torch.Tensor [B,3,H,W] Input image Returns ------- gradient_x : torch.Tensor [B,3,H,W-1] Gradient of image with respect to x """ return image[:, :, :, :-1] - image[:, :, :, 1:] def gradient_y(image): """ Calculates the gradient of an image in the y dimension Parameters ---------- image : torch.Tensor [B,3,H,W] Input image Returns ------- gradient_y : torch.Tensor [B,3,H-1,W] Gradient of image with respect to y """ return image[:, :, :-1, :] - image[:, :, 1:, :] ######################################################################################################################## def interpolate_image(image, shape, mode='bilinear', align_corners=True): """ Interpolate an image to a different resolution Parameters ---------- image : torch.Tensor [B,?,h,w] Image to be interpolated shape : tuple (H, W) Output shape mode : str Interpolation mode align_corners : bool True if corners will be aligned after interpolation Returns ------- image : torch.Tensor [B,?,H,W] Interpolated image """ # Take last two dimensions as shape if len(shape) > 2: shape = shape[-2:] # If the shapes are the same, do nothing if same_shape(image.shape[-2:], shape): return image else: # Interpolate image to match the shape return funct.interpolate(image, size=shape, mode=mode, align_corners=align_corners) def interpolate_scales(images, shape=None, mode='bilinear', align_corners=False): """ Interpolate list of images to the same shape Parameters ---------- images : list of torch.Tensor [B,?,?,?] Images to be interpolated, with different resolutions shape : tuple (H, W) Output shape mode : str Interpolation mode align_corners : bool True if corners will be aligned after interpolation Returns ------- images : list of torch.Tensor [B,?,H,W] Interpolated images, with the same resolution """ # If no shape is provided, interpolate to highest resolution if shape is None: shape = images[0][0].shape # Take last two dimensions as shape if len(shape) > 2: shape = shape[-2:] # Interpolate all images return [funct.interpolate(image, shape, mode=mode, align_corners=align_corners) for image in images] def match_scales(image, targets, num_scales, mode='bilinear', align_corners=True): """ Interpolate one image to produce a list of images with the same shape as targets Parameters ---------- image : torch.Tensor [B,?,h,w] Input image targets : list of torch.Tensor [B,?,?,?] Tensors with the target resolutions num_scales : int Number of considered scales mode : str Interpolation mode align_corners : bool True if corners will be aligned after interpolation Returns ------- images : list of torch.Tensor [B,?,?,?] List of images with the same resolutions as targets """ # For all scales images = [] image_shape = image.shape[-2:] for i in range(num_scales): target_shape = targets[i].shape # If image shape is equal to target shape if same_shape(image_shape, target_shape): images.append(image) else: # Otherwise, interpolate images.append(interpolate_image( image, target_shape, mode=mode, align_corners=align_corners)) # Return scaled images return images ######################################################################################################################## @lru_cache(maxsize=None) def meshgrid(B, H, W, dtype, device, normalized=False): """ Create meshgrid with a specific resolution Parameters ---------- B : int Batch size H : int Height size W : int Width size dtype : torch.dtype Meshgrid type device : torch.device Meshgrid device normalized : bool True if grid is normalized between -1 and 1 Returns ------- xs : torch.Tensor [B,1,W] Meshgrid in dimension x ys : torch.Tensor [B,H,1] Meshgrid in dimension y """ if normalized: xs = torch.linspace(-1, 1, W, device=device, dtype=dtype) ys = torch.linspace(-1, 1, H, device=device, dtype=dtype) else: xs = torch.linspace(0, W-1, W, device=device, dtype=dtype) ys = torch.linspace(0, H-1, H, device=device, dtype=dtype) ys, xs = torch.meshgrid([ys, xs]) return xs.repeat([B, 1, 1]), ys.repeat([B, 1, 1]) @lru_cache(maxsize=None) def image_grid(B, H, W, dtype, device, normalized=False): """ Create an image grid with a specific resolution Parameters ---------- B : int Batch size H : int Height size W : int Width size dtype : torch.dtype Meshgrid type device : torch.device Meshgrid device normalized : bool True if grid is normalized between -1 and 1 Returns ------- grid : torch.Tensor [B,3,H,W] Image grid containing a meshgrid in x, y and 1 """ xs, ys = meshgrid(B, H, W, dtype, device, normalized=normalized) ones = torch.ones_like(xs) grid = torch.stack([xs, ys, ones], dim=1) return grid ########################################################################################################################
26.431579
120
0.550909
c30de5c8fe3bfea15bd9e7d5897b07e64ee9e2dd
3,310
py
Python
watson_developer_cloud/natural_language_understanding_v1.py
anjchatt/Watson1
49836fe537e0437947e00ab9dd824acc1709774f
[ "Apache-2.0" ]
9
2017-05-09T14:22:57.000Z
2018-04-25T11:48:54.000Z
Message_delivery_Kafka/query/virtualenv/lib/python2.7/site-packages/watson_developer_cloud/natural_language_understanding_v1.py
RickeyBoy/HACKxSJTU_ChatAssistant
12768c8b6710adb582aec6c3b40613eedc3dfeb2
[ "Apache-2.0" ]
null
null
null
Message_delivery_Kafka/query/virtualenv/lib/python2.7/site-packages/watson_developer_cloud/natural_language_understanding_v1.py
RickeyBoy/HACKxSJTU_ChatAssistant
12768c8b6710adb582aec6c3b40613eedc3dfeb2
[ "Apache-2.0" ]
null
null
null
# Copyright 2016 IBM 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 watson_developer_cloud.watson_developer_cloud_service import \ WatsonDeveloperCloudService class NaturalLanguageUnderstandingV1(WatsonDeveloperCloudService): """ All methods taking features use the feature classes from watson_developer_cloud/natural_language_understanding/features/v1 """ base_url = 'https://gateway.watsonplatform.net' default_url = '{0}/natural-language-understanding/api'.format(base_url) latest_version = '2017-02-27' def __init__(self, version, url=default_url, username=None, password=None, use_vcap_services=True): WatsonDeveloperCloudService.__init__( self, 'natural-language-understanding', url, username, password, use_vcap_services) self.version = version def analyze(self, features, text=None, url=None, html=None, clean=True, xpath=None, fallback_to_raw=True, return_analyzed_text=False, language=None): """ This is the method to call and analyze text with the supplied features :param features: The list of features :param text: Text to analyze (pick one of text, url, or html) :param url: url to analyze (pick one of text, url, or html) :param html: html to analyze (pick one of text, url, or html) :param clean: should the service clean the text? :param xpath: xpath to use for html or url :param fallback_to_raw: :param return_analyzed_text: should the analyzed text be returned (defaults to false) :param language: what language to use :return: dict of analyzed text """ body = { 'clean': clean, 'fallback_to_raw': fallback_to_raw, 'return_analyzed_text': return_analyzed_text, 'xpath': xpath, 'language': language, 'text': text, 'url': url, 'html': html } feature_dict = {} for feature in features: feature_dict[feature.name()] = feature.toDict() body['features'] = feature_dict if text is None and html is None and url is None: msg = "html, text, or url must have content" raise ValueError(msg) if len(features) < 1: raise ValueError("Must supply at least one feature") return self.request(method='POST', url='/v1/analyze', params={"version": self.version}, headers={'content-type': 'application/json'}, json=body, accept_json=True)
38.941176
78
0.623867
49724d19d8cf285bb5f2b4b1ce285a5cdcea5853
6,026
py
Python
util/command_util.py
CantSayIHave/OllieBotCore_v3
bec7b8bcfbd550bec11a85bfcead8478605998af
[ "MIT" ]
4
2018-01-16T10:08:49.000Z
2019-07-28T07:48:08.000Z
util/command_util.py
CantSayIHave/OllieBotCore
bec7b8bcfbd550bec11a85bfcead8478605998af
[ "MIT" ]
null
null
null
util/command_util.py
CantSayIHave/OllieBotCore
bec7b8bcfbd550bec11a85bfcead8478605998af
[ "MIT" ]
null
null
null
import re from enum import Enum import discord from PIL import Image, ImageDraw, ImageOps from discord.ext import commands from util import global_util class ArgumentType(Enum): MEMBER = USER = 0 CHANNEL = 1 COLOUR = COLOR = 2 ROLE = 3 GAME = 4 INVITE = 5 EMOJI = 6 def get_type(arg): if type(arg) is int: try: return ArgumentType(arg) except ValueError: return None elif type(arg) is str: try: return ArgumentType[arg.upper()] except (ValueError, KeyError): return None def get_converter(type_): c_type = get_type(type_) if not c_type: return None if c_type == ArgumentType.MEMBER or c_type == ArgumentType.USER: return commands.MemberConverter elif c_type == ArgumentType.CHANNEL: return commands.ChannelConverter elif c_type == ArgumentType.COLOUR: return commands.ColourConverter elif c_type == ArgumentType.ROLE: return commands.RoleConverter elif c_type == ArgumentType.GAME: return commands.GameConverter elif c_type == ArgumentType.INVITE: return commands.InviteConverter elif c_type == ArgumentType.EMOJI: return EmojiConverter def find_arg(ctx, arg: str, types: iter): for t in types: converter = get_converter(t) if converter: try: found = converter(ctx, arg).convert() if found: return found except commands.BadArgument: pass return arg async def find_member(ctx, arg: str, percent, return_name=True): if percent > 1: percent = percent / 100 if percent > 1: raise ValueError('`percent` must be <= 1 or <= 100') arg = arg.lower() for m in ctx.message.server.members: if arg in m.name.lower(): if (len(arg) / len(m.name)) >= percent: if return_name: return m.name else: return m elif arg in m.display_name.lower(): if (len(arg) / len(m.display_name)) >= percent: if return_name: return m.display_name else: return m async def find_role(ctx, arg: str, percent) -> discord.Role: if percent > 1: percent = percent / 100 if percent > 1: raise ValueError('`percent` must be <= 1 or <= 100') arg = arg.lower() for role in ctx.message.server.roles: # type: discord.Role if arg in role.name.lower(): if (len(arg) / len(role.name)) >= percent: return role class EmojiConverter: def __init__(self, ctx, arg): self.ctx = ctx self.arg = arg def convert(self): match = re.match(r'<:([a-zA-Z0-9_]+)+:([0-9]+)>$', self.arg) if match: return discord.Emoji(name=match.group(1), id=match.group(2), server='00000000', require_colons=True) # not re.match(r'https?:', self.arg) elif len(self.arg) == 1: emote_uni = hex(ord(self.arg))[2:] return 'https://abs.twimg.com/emoji/v2/72x72/{}.png'.format(emote_uni) async def find_message(bot, channel, message_num: int): m_on = 0 async for m in bot.logs_from(channel, limit=int(message_num + 1)): if m_on == message_num: return m m_on += 1 async def find_image(bot, channel, image_num: int): im_on = 1 async for m in bot.logs_from(channel, limit=100): # type: discord.Message if m.embeds: if im_on == image_num: return m.embeds[0]['url'] im_on += 1 if m.attachments: if im_on == image_num: return m.attachments[0]['url'] im_on += 1 def style_pfp(im: Image): bigsize = (im.size[0] * 3, im.size[1] * 3) mask = Image.new('L', bigsize, 0) draw = ImageDraw.Draw(mask) draw.ellipse((0, 0) + bigsize, fill=255) mask = mask.resize(im.size, Image.ANTIALIAS) im.putalpha(mask) output = ImageOps.fit(im, mask.size, centering=(0.5, 0.5)) output.putalpha(mask) return output async def extract_image(ctx: commands.Context, arg: str = None, member: str = None, in_server = None): base_image = None if arg: converted_arg = find_arg(ctx, arg, ['emoji']) if type(converted_arg) is discord.Emoji: base_image = await global_util.get_image(converted_arg.url) elif type(converted_arg) is str: if converted_arg.startswith('http'): base_image = await global_util.get_image(converted_arg) elif converted_arg in ['pfp', 'avatar']: if member: member = find_arg(ctx, member, ['member']) if type(member) is not discord.Member: member = await find_member(ctx, member, percent=50) if not member: member = ctx.message.author base_image = await global_util.get_image(member.avatar_url) base_image = style_pfp(base_image) elif converted_arg == 'capture' and in_server: if in_server.capture: base_image = await global_util.get_image(in_server.capture) else: if ctx.message.attachments: base_image = await global_util.get_image(ctx.message.attachments[0]['url']) elif ctx.message.embeds: base_image = await global_util.get_image(ctx.message.embeds[0]['url']) return base_image def run_converter(converter_class, ctx, arg, default=None): converter = converter_class(ctx, arg) try: return converter.convert() except: return default def extract_passed(ctx, bot): try: return ctx.message.content.replace('{}{} '.format(bot.command_prefix, ctx.command.name), '') except: return ''
29.684729
112
0.578493
413476790cb586587a12d86bc3701a112205dd15
5,268
py
Python
v0/aia_eis_v0/playground/laiZhaoGui/goa/visualize_res_0.py
DreamBoatOve/aia_eis
458b4d29846669b10db4da1b3e86c0b394614ceb
[ "MIT" ]
1
2022-03-02T12:57:19.000Z
2022-03-02T12:57:19.000Z
v0/aia_eis_v0/playground/laiZhaoGui/goa/visualize_res_0.py
DreamBoatOve/aia_eis
458b4d29846669b10db4da1b3e86c0b394614ceb
[ "MIT" ]
null
null
null
v0/aia_eis_v0/playground/laiZhaoGui/goa/visualize_res_0.py
DreamBoatOve/aia_eis
458b4d29846669b10db4da1b3e86c0b394614ceb
[ "MIT" ]
null
null
null
from utils.file_utils.filename_utils import get_date_prefix from playground.laiZhaoGui.goa.get_lai_manual_fitting_res import read_lai_manual_fitting_res, read_lai_test_coordinate, pack_lai_manual_fitting_res, wrap_lai_data_4_contour from playground.laiZhaoGui.goa.get_GOAs_fitting_res import get_GOAs_best_fitting_res, pack_GOAs_fit_res, wrap_GOAs_data_4_contour """ 模块功能: 集合Lai-EIS 人工处理结果 与 GOA直接处理原始EIS结果 画图 version 0:visualize_res_0.py """ # 1- Get Lai's manual fitting R(RC)_IS_lin-kk_res.txt and GOAs R(RC)_IS_lin-kk_res.txt # 1.1- Get Lai's manual fitting R(RC)_IS_lin-kk_res.txt lai_manual_fit_res_dict_list = read_lai_manual_fitting_res(ex_fp='../../../../datasets/experiement_data/laiZhaoGui/eis/2020-07-22-阻抗类型整理2006.xlsx',\ sheet_name='statistic') coor_dict_list = read_lai_test_coordinate(ex_fp='../../../../datasets/experiement_data/laiZhaoGui/eis/坐标.xlsx',\ sheet_name='Sheet1') lai_manual_fit_res_dict_list = pack_lai_manual_fitting_res(lai_manual_fit_res_dict_list,\ coor_dict_list) lai_x_list, lai_y_list, lai_z_list = wrap_lai_data_4_contour(lai_manual_fit_res_dict_list) # 1.2- Get GOAs R(RC)_IS_lin-kk_res.txt goa_fit_res_dict_list = get_GOAs_best_fitting_res(fp='./R(RC)_IS_lin-kk_res.txt/2nd/magNum=2_res', order_str='2nd') goa_fit_res_dict_list = pack_GOAs_fit_res(goa_fit_res_dict_list, coor_dict_list) goa_x_list, goa_y_list, goa_z_list = wrap_GOAs_data_4_contour(goa_fit_res_dict_list) # 2- Export coordinates of test points and their fitting results (Lai's and GOAs') to txt def export_fit_res(x_list, y_list, z_list, fn): # sort data by y then by x xyz_list = [[x,y,z] for x,y,z in zip(x_list, y_list, z_list)] xyz_list.sort(key= lambda xyz : (xyz[1], xyz[0]), reverse=False) x_list = [xyz[0] for xyz in xyz_list] y_list = [xyz[1] for xyz in xyz_list] z_list = [xyz[2] for xyz in xyz_list] header = ','.join(['x_coor', 'y_coor', 'z_coor(Chi-Square)']) + '\n' with open(fn, 'a+') as file: file.write(header) for x, y, z in zip(x_list, y_list, z_list): line = ','.join(list(map(str, [x,y,z]))) + '\n' file.write(line) # 2.1- Export coordinates of test points and their fitting results Lai's to txt # export_fit_res(x_list=lai_x_list, y_list=lai_y_list, z_list=lai_z_list, fn=get_date_prefix()+'lai_fit_res.txt') # 2.2- Export coordinates of test points and their fitting results GOAs' to txt export_fit_res(x_list=goa_x_list, y_list=goa_y_list, z_list=goa_z_list, fn=get_date_prefix()+'GOA_fit_res.txt') """ 3- Use Origin to plot Chi-Square-Contour 我用各种ECM上最优的前五种GOA拟合的Chi-Squared误差,与赖拟合的误差,分别画在上下两个等高图上 3.1 Delete abnormal data in GOA 's fit R(RC)_IS_lin-kk_res.txt manually Lai Z: Min Max 0.0004402 0.04055 GOA Z: Min Max(1st, too big and weird, delete it) Max(2nd, better and normal) Max(3rd) 0.0033192209598534358 13891082844.471136 54.41158700914487 27.29493804319961 1- Delete the huge abnormal data in z2_list (GOAs' R(RC)_IS_lin-kk_res.txt), (x=1.3,y=0.458,z=13891082844.471136,fn=2-3,ECM-Num=9) 2- Set the value range of colorbar as 1e-4 ~ 1e2, 6 margins 3.2 plot setting 1- 各自 或 一起 拥有colorbar 2- colorbar 上的刻度是对数分布的 3- the range of x-axis is: -0.2 ~ 16.5 mm (Increment 2); the range of y-axis is: -0.1 ~ 2 mm (Increment 0.5). x Range y Range z Range min max min max min(laiZhaoGui) max(laiZhaoGui) 0 16.2 0 1.833 0.0004402 0.04055 z Range min(laiZhaoGui) max(laiZhaoGui) 0.003 54.4 fit-res_contour_plot_details origin导入txt文件 https://jingyan.baidu.com/article/870c6fc3324488b03fe4beca.html origin 画contour https://jingyan.baidu.com/article/72ee561a75b777e16038df68.html origin contour colorbar 设置成 对数 6.9.2 Contour Plots and Color Mapping https://www.originlab.com/doc/Tutorials/Contour-Color-Map origin turn off 'speed mode' 打开在header中的Graph,在下拉菜单的中下部可以找到'Speed Mode' origin 设置x,y轴的坐标范围 https://jingyan.baidu.com/article/e4511cf3185eb56a855eaf05.html origin colorbar两端无用的色块删除掉 在plot details - Colormap/Contours 中 点击欲删除的色块,把颜色设置成None origin colorbar value in log scale 在plot details - Numeric Formats - Format 中选择Scientific origin 设置x,y轴的长宽比例 按照数值大小正常显示 graph -》 layer -》size/speed 中手动调整 origin contour smoothing graph -》 layer -》具体的数据book -》Contouring Info -》Smoothing 有 total points increase factor 和 Smoothing Parameter两个参数可调,但是怎么调都感觉数据失真很严重,所以决定不用平滑功能 Chi-squared Error的图不画成 Colormap Surface彩面图 (https://www.jianshu.com/p/bac08e1dc36a),减轻 GOA的Error 和 Lai的Error 差别的直观视觉体现,可在后续拟合的电路元件的分布上使用 Colormap Surface彩面图 """
56.645161
172
0.654708
390209bad79adc0dc28937438d068518a194cf7a
3,638
py
Python
raw/day22/newpart2.py
aesdeef/advent-of-code-2021
4561bcf12ac03d360f5b28c48ef80134f97613b9
[ "MIT" ]
2
2021-12-03T06:18:27.000Z
2021-12-06T11:28:33.000Z
raw/day22/newpart2.py
aesdeef/advent-of-code-2021
4561bcf12ac03d360f5b28c48ef80134f97613b9
[ "MIT" ]
null
null
null
raw/day22/newpart2.py
aesdeef/advent-of-code-2021
4561bcf12ac03d360f5b28c48ef80134f97613b9
[ "MIT" ]
null
null
null
import re from collections import Counter, defaultdict, deque from functools import cache from itertools import ( chain, combinations, combinations_with_replacement, count, cycle, permutations, product, ) # READ THE ENTIRE DESCRIPTION FIRST INPUT_FILE = "../../input/22.txt" # INPUT_FILE = "test.txt" # INPUT_FILE = "test2.txt" # INPUT_FILE = "test3.txt" Cuboid = tuple[tuple[int, int], tuple[int, int], tuple[int, int]] with open(INPUT_FILE) as f: instr = list() for line in f: cmd, coords = line.strip().split() parts = coords.split(",") coo = [] for part in parts: coo.append(tuple(int(x) for x in part[2:].split(".."))) instr.append((cmd, tuple(coo))) def subtract_axis(a, b): a_min, a_max = a b_min, b_max = b if a_max < b_min or b_max < a_min: return (a,), (True,) if b_min <= a_min < a_max <= b_max: return (a,), (False,) if a_min == a_max: t = not (b_min <= a_min <= b_max) return (a,), (t,) if b_min == b_max: if a_min == b_min: return (b, (a_min + 1, a_max)), (False, True) if a_max == b_min: return ((a_min, a_max - 1), b), (True, False) if a_min < b_min < a_max: return ((a_min, b_min - 1), b, (b_min + 1, a_max)), (True, False, True) else: return (a,), (True,) if a_max == b_min: return ((a_min, b_min - 1), (b_min, a_max)), (True, False) if b_max == a_min: return ((a_min, b_max), (a_min + 1, a_max)), (False, True) if a_min == b_min: if b_max < a_max: return (b, (b_max + 1, a_max)), (False, True) else: raise ValueError if a_max == b_max: if a_min < b_min: return ((a_min, b_min - 1), b), (True, False) else: raise ValueError if a_min < b_min < b_max < a_max: return ((a_min, b_min - 1), b, (b_max + 1, a_max)), (True, False, True) if a_min < b_min < a_max < b_max: return ((a_min, b_min - 1), (b_min, a_max)), (True, False) if b_min < a_min < b_max < a_max: return ((a_min, b_max), (b_max + 1, a_max)), (False, True) def subtract(a: Cuboid, b: Cuboid) -> set[Cuboid]: remaining = set() for x_axis, x_in in zip(*subtract_axis(a[0], b[0])): for y_axis, y_in in zip(*subtract_axis(a[1], b[1])): for z_axis, z_in in zip(*subtract_axis(a[2], b[2])): if any((x_in, y_in, z_in)): remaining.add((x_axis, y_axis, z_axis)) return remaining def size(cuboid): x_len = cuboid[0][1] + 1 - cuboid[0][0] y_len = cuboid[1][1] + 1 - cuboid[1][0] z_len = cuboid[2][1] + 1 - cuboid[2][0] return x_len * y_len * z_len cuboids_on = set() for inst in instr: # print(sorted(cuboids_on)) # print(sum(size(c) for c in cuboids_on)) cmd, cuboid = inst new_cuboids_on = set() for c_on in cuboids_on: result = subtract(c_on, cuboid) """ for c in result: for w in c: if w[0] > w[1]: print("subtracting", c_on, cuboid) print("result", result) print(c, w) raise NotImplementedError """ new_cuboids_on |= result cuboids_on = new_cuboids_on # print(sorted(cuboids_on)) # print(sum(size(c) for c in cuboids_on)) if cmd == "on": cuboids_on.add(cuboid) # print(sum(size(c) for c in cuboids_on)) continue lit = sum(size(cuboid) for cuboid in cuboids_on) print(lit)
26.362319
83
0.538758
db5cf01a71259307e365e8aa9324c3ecb9d95359
4,035
py
Python
build/lib/iemlav/lib/antivirus/scanner/scanner_engine.py
GouravRDutta/IemLabsAV
8d397a3d59e067176269c5e84d73bf53951b7b3f
[ "MIT" ]
null
null
null
build/lib/iemlav/lib/antivirus/scanner/scanner_engine.py
GouravRDutta/IemLabsAV
8d397a3d59e067176269c5e84d73bf53951b7b3f
[ "MIT" ]
null
null
null
build/lib/iemlav/lib/antivirus/scanner/scanner_engine.py
GouravRDutta/IemLabsAV
8d397a3d59e067176269c5e84d73bf53951b7b3f
[ "MIT" ]
1
2021-07-02T12:29:10.000Z
2021-07-02T12:29:10.000Z
from iemlav.lib.antivirus.scanner.hash_scanner import HashScanner from iemlav.lib.antivirus.scanner.yara_scanner import YaraScanner from iemlav.lib.antivirus.scanner.clamav_scanner import ClamAVScanner from iemlav.lib.antivirus.antivirus_logger import AntiVirusLogger import multiprocessing import sys class ScannerEngine(object): """ScannerEngine class.""" def __init__(self, debug=False, config_path=None, vt_api_key=None, file_list=None): # Initialize logger self.logger = AntiVirusLogger( __name__, debug=debug ) if config_path is not None: self._CONFIG_PATH = config_path else: self.logger.log( "Configuration file path not found.", logtype="error" ) sys.exit(0) if file_list: self.file_list = file_list else: # Initialize an empty list self.file_list = [] # Create HashScanner object self.hash_scanner = HashScanner(debug=debug, config_path=self._CONFIG_PATH, file_list=self.file_list, vt_api_key=vt_api_key) # Create YaraScanner object self.yara_scanner = YaraScanner(debug=debug, config_path=self._CONFIG_PATH, file_list=self.file_list, vt_api_key=vt_api_key) # Create ClamAVScanner object self.clamd_scanner = ClamAVScanner(debug=debug, config_path=self._CONFIG_PATH, file_list=self.file_list, vt_api_key=vt_api_key) # List of process in action self.process_pool = [] def start_scanner_engine(self): """ Start the scanner engine and stat scanning the files using three (3) engines in a multi-processing environment. 1. Hash Scanner Engine 2. Yara Scanner Engine 3. Clam AV Scanner Engine """ try: # Create Hash Scanner process hash_scanner_process = multiprocessing.Process(target=self.hash_scanner.start_scan) # Create Yara Scanner process yara_scanner_process = multiprocessing.Process(target=self.yara_scanner.start_scan) # Create Clam AV Scanner process clamd_scanner_process = multiprocessing.Process(target=self.clamd_scanner.start_scan) # Add Hash Scanner process to process list self.process_pool.append(hash_scanner_process) # Add Yara Scanner process to process list self.process_pool.append(yara_scanner_process) # Add Clamd AV process to process list self.process_pool.append(clamd_scanner_process) # Start Hash Scanner process hash_scanner_process.start() self.logger.log( "Hash Scanner engine started", logtype="info" ) # Start Yara Scanner process yara_scanner_process.start() self.logger.log( "Yara Scanner engine started", logtype="info" ) clamd_scanner_process.start() self.logger.log( "Clam AV Scanner engine started", logtype="info" ) # Complete the process for process in self.process_pool: process.join() return True except KeyboardInterrupt: for process in self.process_pool: process.terminate() return True except Exception as e: self.logger.log( "Error occurred: " + str(e), logtype="error" ) return True
34.487179
97
0.55316
18de44d582491e8cd7d0cfe03667fa7d1c996202
1,778
py
Python
liquid_node/jsonapi.py
thifranc/node
ffdd75056ca9d9a6e9b6f3fb4a0b2bda6af11d14
[ "MIT" ]
4
2020-03-18T06:51:52.000Z
2021-08-09T20:17:57.000Z
liquid_node/jsonapi.py
thifranc/node
ffdd75056ca9d9a6e9b6f3fb4a0b2bda6af11d14
[ "MIT" ]
120
2019-02-08T05:55:44.000Z
2021-11-24T09:34:14.000Z
liquid_node/jsonapi.py
thifranc/node
ffdd75056ca9d9a6e9b6f3fb4a0b2bda6af11d14
[ "MIT" ]
9
2019-01-25T12:35:28.000Z
2022-01-11T15:40:05.000Z
import json import logging from urllib.error import HTTPError from urllib.request import Request, urlopen log = logging.getLogger(__name__) class JsonApi: def __init__(self, endpoint): self.endpoint = endpoint def request(self, method, url, data=None, headers=None): """Makes a request against the JSON endpoint :param method: the request method :param url: the path in the JSON API :param data: the request body :type data: bytes|str """ req_url = f'{self.endpoint}{url}' req_headers = dict(headers or {}) req_body = None if data is not None: if isinstance(data, bytes): req_body = data else: req_headers['Content-Type'] = 'application/json' req_body = json.dumps(data).encode('utf8') req = Request( req_url, req_body, req_headers, method=method, ) with urlopen(req) as res: if res.status >= 200 and res.status < 300: content = res.read() content_type = res.headers.get('Content-Type') or "" if content_type.startswith('application/json') and len(content): return json.loads(content) else: return None else: raise HTTPError(url, res.status, res.msg, res.headers, res) def get(self, url, data=None): return self.request('GET', url, data) def post(self, url, data=None): return self.request('POST', url, data) def put(self, url, data): return self.request('PUT', url, data) def delete(self, url): return self.request('DELETE', url)
27.78125
80
0.556805
3804fc638c870d15f64436f4a9fee407822af4b1
8,138
py
Python
dovpanda/base.py
avisherwood/DovPandaDev
fd8f30b6dd243bdc1b3a4f3dbeab2b9f52c4f553
[ "BSD-3-Clause" ]
null
null
null
dovpanda/base.py
avisherwood/DovPandaDev
fd8f30b6dd243bdc1b3a4f3dbeab2b9f52c4f553
[ "BSD-3-Clause" ]
null
null
null
dovpanda/base.py
avisherwood/DovPandaDev
fd8f30b6dd243bdc1b3a4f3dbeab2b9f52c4f553
[ "BSD-3-Clause" ]
null
null
null
import functools import inspect import re import sys from collections import defaultdict, deque from contextlib import contextmanager from dovpanda import config try: # If user runs from notebook they will have this from IPython.display import display except (ModuleNotFoundError, ImportError): pass class Hint: def __init__(self, original, hook_type, replacement, *, stop_nudge=1): accepted_hooks = ['pre', 'post'] assert hook_type in accepted_hooks, f'hook_type must be one of {accepted_hooks}' self.original = original self.hook_type = hook_type self.replacement = replacement self.stop_nudge = stop_nudge def __repr__(self): return (f"[HINT] replaces {self.original} with {self.replacement} " f"at {self.hook_type} but stops after {self.stop_nudge}") class _Teller: def __init__(self): self.message = None self.set_output('display') self.verbose = True self.caller = None def __repr__(self): trace = self.if_verbose(f' (Line {self.caller.lineno})') return self._strip_html(f'===== {self.message} ====={trace}') def __str__(self): trace = self.if_verbose(f' (Line {self.caller.lineno})') return f'{self._strip_html(self.message)}{trace}' def __call__(self, s): self.tell(s) def _repr_html_(self): return self.nice_output() def nice_output(self): code_context = self.caller.code_context[0].strip() trace = f'<div style="font-size:0.7em;">Line {self.caller.lineno}: <code>{code_context}</code> </div>' trace = self.if_verbose(trace) if config.logo is None: logo_tag = '' else: logo_tag = f'<img src="{config.logo}" alt="logo" style="float:left; margin-right:10px">' html = f''' <div class="alert alert-info" role="alert"> {logo_tag} {self.message} <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> {trace} </div> ''' return html @staticmethod def _strip_html(s): s = re.sub(r'<br>', r'\n', s) return re.sub('<[^<]+?>', '', s) @staticmethod def _no_output(*args, **kwargs): return def if_verbose(self, s): if self.verbose: return s else: return '' def set_output(self, output_method): accepted_methods = ['print', 'display', 'debug', 'info', 'warning', 'off'] if type(output_method) is str: assert output_method in accepted_methods, f'output_format must be one of {accepted_methods} or a callable' if output_method == 'print': self.output = print elif output_method in ['debug', 'info', 'warning']: try: from loguru import logger except ModuleNotFoundError: import logging logger = logging.getLogger('dovpanda') self.output = getattr(logger, output_method) elif output_method == 'display': try: self.output = display except NameError: self.set_output('print') elif output_method == 'off': self.output = self._no_output else: self.output = output_method def tell(self, message): self.message = message self.output(self) class Ledger: def __init__(self): self.hints = defaultdict(list) self.teller = _Teller() self.verbose = True self.caller = None # TODO: Memory has a cache only of registered methods. Change to accomodate all pandas self.memory = deque(maxlen=32) self.original_methods = dict() def replace(self, original, func_hooks): g = rgetattr(sys.modules['pandas'], original) self.save_original(original, g) rsetattr(sys.modules['pandas'], original, self.attach_hooks(g, func_hooks)) def add_hint(self, originals, hook_type='pre', stop_nudge=1): def replaces_decorator(replacement): hint = Hint(original=originals, hook_type=hook_type, replacement=replacement, stop_nudge=stop_nudge) for original in listify(originals): self.hints[original].append(hint) return replaces_decorator def register_hints(self): for original, func_hooks in self.hints.items(): self.replace(original, func_hooks) def attach_hooks(self, f, func_hooks): pres = [hook for hook in func_hooks if hook.hook_type == 'pre'] posts = [hook for hook in func_hooks if hook.hook_type == 'post'] @functools.wraps(f) def run(*args, **kwargs): self._set_caller_details(f) arguments = self._get_arguments(f, *args, **kwargs) if self.resticted_dirs(): ret = f(*args, **kwargs) else: for pre in pres: if self.similar <= pre.stop_nudge: pre.replacement(arguments) ret = f(*args, **kwargs) for post in posts: if self.similar <= post.stop_nudge: post.replacement(ret, arguments) return ret return run def _get_arguments(self, f, *args, **kwargs): sig = inspect.signature(f).bind(*args, **kwargs) sig.apply_defaults() return sig.arguments def _set_caller_details(self, f): frame = inspect.currentframe().f_back.f_back self.caller = inspect.getframeinfo(frame) if self.resticted_dirs(): return self._update_memory(f) self.teller.caller = self.caller def _update_memory(self, f): self.memory.append((f, self.caller)) latest = self.memory[-1] similar = [caller for caller in self.memory if caller == latest] similar = len(similar) self.similar = similar def resticted_dirs(self): caller_file = self.caller.filename if any([caller_file.startswith(str(dir_name)) for dir_name in config.RESTRICTED_DIRS]): return True return False # Output def tell(self, *args, **kwargs): self.teller(*args, *kwargs) def set_output(self, output): self.teller.set_output(output) def set_verbose(self, verbose=True): self.teller.verbose = verbose def save_original(self, original_name, original_function): if original_name in self.original_methods: return else: self.original_methods[original_name] = original_function def revert(self): """Revert the ledger. Register original pandas methods back to their namespace""" for original_name, original_func in self.original_methods.items(): rsetattr(sys.modules['pandas'], original_name, original_func) @contextmanager def mute(self): current_output = self.teller.output self.set_output('off') try: yield except Exception as e: raise e finally: self.set_output(current_output) def rgetattr(obj, attr): attributes = attr.strip('.').split('.') for att in attributes: try: obj = getattr(obj, att) except AttributeError as e: raise e return obj def rsetattr(obj, attr, value): pre, _, post = attr.rpartition('.') return setattr(rgetattr(obj, pre) if pre else obj, post, value) def only_print(s, *args, **kwargs): print(s) return lambda x: (args, kwargs) def listify(val): if type(val) is str: return [val] return val def setify(val): return set(listify(val))
31.789063
119
0.577415
409c804f90140534f97c54184d5624c0fb3fb5df
412
py
Python
Desafios/Desafio009.py
AlestanAlves/Curso-Em-Video
0b21b5c6777dfc6c2a559e5a43eedb3813343384
[ "MIT" ]
1
2019-08-16T03:12:21.000Z
2019-08-16T03:12:21.000Z
Desafios/Desafio009.py
AlestanAlves/Curso-Em-Video
0b21b5c6777dfc6c2a559e5a43eedb3813343384
[ "MIT" ]
null
null
null
Desafios/Desafio009.py
AlestanAlves/Curso-Em-Video
0b21b5c6777dfc6c2a559e5a43eedb3813343384
[ "MIT" ]
null
null
null
n = int(input('Insert number: ')) n0 = n * 0 n1 = n * 1 n2 = n * 2 n3 = n * 3 n4 = n * 4 n5 = n * 5 n6 = n * 6 n7 = n * 7 n8 = n * 8 n9 = n * 9 n10 = n * 10 print ('Table of {} \n {} x 0 = {} \n {} x 1 = {} \n {} x 2 = {} \n {} x 3 = {} \n {} x 4 = {} \n {} x 5 = {} \n {} x 6 = {} \n {} x 7 = {} \n {} x 8 = {} \n {} x 9 = {} \n {} x 10 = {}'.format(n,n,n0,n,n1,n,n2,n,n3,n,n4,n,n5,n,n6,n,n7,n,n8,n,n9,n,n10))
27.466667
253
0.373786
7fdbb811e613f212edffc43c00df1d702d175723
7,042
py
Python
ckanext/archiver/model.py
ckan/ckanext-archiver
faf097c58f310b1cd187b2ef1150360d3ab09faf
[ "MIT" ]
16
2016-01-11T14:42:41.000Z
2022-03-18T03:20:15.000Z
ckanext/archiver/model.py
ckan/ckanext-archiver
faf097c58f310b1cd187b2ef1150360d3ab09faf
[ "MIT" ]
49
2015-03-23T14:47:37.000Z
2021-05-27T06:27:55.000Z
ckanext/archiver/model.py
ckan/ckanext-archiver
faf097c58f310b1cd187b2ef1150360d3ab09faf
[ "MIT" ]
30
2015-01-08T09:04:31.000Z
2021-06-22T13:53:21.000Z
import itertools from builtins import str from builtins import object import uuid from datetime import datetime from sqlalchemy import Column, MetaData from sqlalchemy import types from sqlalchemy.ext.declarative import declarative_base import ckan.model as model import ckan.plugins as p from ckan.lib import dictization log = __import__('logging').getLogger(__name__) Base = declarative_base() def make_uuid(): return str(uuid.uuid4()) metadata = MetaData() # enum of all the archival statuses (singleton) # NB Be very careful changing these status strings. They are also used in # ckanext-qa tasks.py. class Status(object): _instance = None def __init__(self): not_broken = { # is_broken = False 0: 'Archived successfully', 1: 'Content has not changed', } broken = { # is_broken = True 10: 'URL invalid', 11: 'URL request failed', 12: 'Download error', } not_sure = { # is_broken = None i.e. not sure 21: 'Chose not to download', 22: 'Download failure', 23: 'System error during archival', } self._by_id = dict(itertools.chain(not_broken.items(), broken.items())) self._by_id.update(not_sure) self._by_text = dict((value, key) for key, value in self._by_id.items()) @classmethod def instance(cls): if not cls._instance: cls._instance = cls() return cls._instance @classmethod def by_text(cls, status_txt): return cls.instance()._by_text[status_txt] @classmethod def by_id(cls, status_id): return cls.instance()._by_id[status_id] @classmethod def is_status_broken(cls, status_id): if status_id < 10: return False elif status_id < 20: return True else: return None # not sure @classmethod def is_ok(cls, status_id): return status_id in [0, 1] broken_enum = {True: 'Broken', None: 'Not sure if broken', False: 'Downloaded OK'} class Archival(Base): """ Details of the archival of resources. Has the filepath for successfully archived resources. Basic error history provided for unsuccessful ones. """ __tablename__ = 'archival' id = Column(types.UnicodeText, primary_key=True, default=make_uuid) package_id = Column(types.UnicodeText, nullable=False, index=True) resource_id = Column(types.UnicodeText, nullable=False, index=True) resource_timestamp = Column(types.DateTime) # key to resource_revision # Details of the latest archival attempt status_id = Column(types.Integer) is_broken = Column(types.Boolean) # Based on status_id. None = not sure reason = Column(types.UnicodeText) # Extra detail explaining the status (cannot be translated) url_redirected_to = Column(types.UnicodeText) # Details of last successful archival cache_filepath = Column(types.UnicodeText) cache_url = Column(types.UnicodeText) size = Column(types.BigInteger, default=0) mimetype = Column(types.UnicodeText) hash = Column(types.UnicodeText) etag = Column(types.UnicodeText) last_modified = Column(types.UnicodeText) # History first_failure = Column(types.DateTime) last_success = Column(types.DateTime) failure_count = Column(types.Integer, default=0) created = Column(types.DateTime, default=datetime.now) updated = Column(types.DateTime) def __repr__(self): broken_details = '' if not self.is_broken else \ ('%d failures' % self.failure_count) package = model.Package.get(self.package_id) package_name = package.name if package else '?%s?' % self.package_id return '<Archival %s /dataset/%s/resource/%s %s>' % \ (broken_enum[self.is_broken], package_name, self.resource_id, broken_details) @classmethod def get_for_resource(cls, resource_id): '''Returns the archival for the given resource, or if it doens't exist, returns None.''' return model.Session.query(cls).filter(cls.resource_id == resource_id).first() @classmethod def get_for_package(cls, package_id): '''Returns the archivals for the given package. May not be any if the package has no resources or has not been archived. It checks the resources are not deleted.''' return model.Session.query(cls) \ .filter(cls.package_id == package_id) \ .join(model.Resource, cls.resource_id == model.Resource.id) \ .filter(model.Resource.state == 'active') \ .all() @classmethod def create(cls, resource_id): c = cls() c.resource_id = resource_id # Find the package_id for the resource. dataset = model.Session.query(model.Package) if p.toolkit.check_ckan_version(max_version='2.2.99'): # earlier CKANs had ResourceGroup dataset = dataset.join(model.ResourceGroup) dataset = dataset \ .join(model.Resource) \ .filter_by(id=resource_id) \ .one() c.package_id = dataset.id return c @property def status(self): if self.status_id is None: return None return Status.by_id(self.status_id) def as_dict(self): context = {'model': model} archival_dict = dictization.table_dictize(self, context) archival_dict['status'] = self.status archival_dict['is_broken_printable'] = broken_enum[self.is_broken] return archival_dict def aggregate_archivals_for_a_dataset(archivals): '''Returns aggregated archival info for a dataset, given the archivals for its resources (returned by get_for_package). :param archivals: A list of the archivals for a dataset's resources :type archivals: A list of Archival objects :returns: Archival dict about the dataset, with keys: status_id status reason is_broken ''' archival_dict = {'status_id': None, 'status': None, 'reason': None, 'is_broken': None} for archival in archivals: # status_id takes the highest id i.e. pessimistic # reason matches the status_id if archival_dict['status_id'] is None or \ archival.status_id > archival_dict['status_id']: archival_dict['status_id'] = archival.status_id archival_dict['reason'] = archival.reason if archivals: archival_dict['status'] = Status.by_id(archival_dict['status_id']) archival_dict['is_broken'] = \ Status.is_status_broken(archival_dict['status_id']) return archival_dict def init_tables(engine): Base.metadata.create_all(engine) log.info('Archiver database tables are set-up')
32.906542
99
0.638313
70b61891ebb868df693b73050c4c07bf5b8b9b2c
7,446
py
Python
source/capacity_quantiles.py
othuxley1/capacity_mismatch_paper
9e2753629d775606966c3b940a37d1b68f2c8851
[ "MIT" ]
null
null
null
source/capacity_quantiles.py
othuxley1/capacity_mismatch_paper
9e2753629d775606966c3b940a37d1b68f2c8851
[ "MIT" ]
null
null
null
source/capacity_quantiles.py
othuxley1/capacity_mismatch_paper
9e2753629d775606966c3b940a37d1b68f2c8851
[ "MIT" ]
null
null
null
""" A script to select boxplot quantile data from the capacity results and re-run the site list variation code to regenerate each site list permutation. - First authored: 2020-04-30 - Owen Huxley <othuxley1@sheffield.ac.uk> """ import pandas as pd from site_list_variation import SiteListVariation from dbconnector import DBConnector from generic_tools import cached class CapacitySitelistUploader: def __init__(self): ### Config ### self.capacity_file = "C:/Users/owenh/Documents/GitRepos/capacity_mismatch_paper/data/MC_results_v2_T0only_no_unreported_20200430_1000N.csv" self.mysql__file = "C:/Users/owenh/Documents/GitRepos/capacity_mismatch_paper/" \ "data/mysql_defaults/" \ "mysql_defaults.ssfdb2.readwrite.capacity_analysis" self.db_tables = { "0.01" : "solarsite_20190205_t0only_no_unreported_0.01pc", "0.25" : "solarsite_20190205_t0only_no_unreported_0.25pc", "0.5" : "solarsite_20190205_t0only_no_unreported_0.5pc", "0.75" : "solarsite_20190205_t0only_no_unreported_0.75pc", "0.99" : "solarsite_20190205_t0only_no_unreported_0.99pc" } ############## def run(self): data = pd.read_csv(self.capacity_file) data.rename({" national_capacity (MW)": "national_capacity_MW"}, inplace=True, axis=1) site_lists = self.get_site_lists(data) return def get_quantile_seeds(self, data): """ Calculate quantiles for capacity data and return corresponcing seed values. Parameter ---------- `data` : pd.DataFrame The capacity data. Returns ------- list A list of dataframes containing the quantiles: .01, .25, .5, .75, .99 """ def idxquantile(s, q=0.5, *args, **kwargs): qv = s.quantile(q, *args, **kwargs) return (s.sort_values(by="national_capacity_MW")[::-1] <= qv).idxmax() q50 = data.loc[idxquantile(data[["national_capacity_MW"]], q=.5)] q75 = data.loc[idxquantile(data[["national_capacity_MW"]], q=.75)] q25 = data.loc[idxquantile(data[["national_capacity_MW"]], q=.25)] q99 = data.loc[idxquantile(data[["national_capacity_MW"]], q=.99)] q01 = data.loc[idxquantile(data[["national_capacity_MW"]], q=.01)] quantiles_dict = { "0.01" : q01, "0.25" : q25, "0.5" : q50, "0.75" : q75, "0.01" : q99, } return quantiles_dict def get_site_lists(self, data): site_lists = {} seed_data = self.get_quantile_seeds(data) # import pdb; pdb.set_trace() for i, quantile in enumerate(seed_data): seed_df = seed_data[quantile] # import pdb; pdb.set_trace() instance = SiteListVariation(1, verbose=True, seed=int(seed_df.values[0][0]), test=False) # instance.unreported_systems() instance.simulate_effective_capacity_site_list() nc = instance.SL.Capacity.sum() if not int(nc) == int(seed_df.values[0][1]): print("50th percentile is: {}, capacity from results is: {}" .format(nc, seed_df.values[0][1])) raise ValueError("National capacity of site list does not national" "capacity from results.") # hanndle missing location data # import pdb; pdb.set_trace() ################################ instance.SL.reset_index(inplace=True) instance.SL.rename({"install_date": "installdate", "Capacity" : "installedcapacity"}, inplace=True, axis=1) instance.SL["latitude_rounded"] = instance.SL["latitude"].round(decimals=1) instance.SL["longitude_rounded"] = instance.SL["longitude"].round(decimals=1) instance.SL["gen_id"] = instance.SL.index + 1 db_SL = instance.SL[["gen_id", "latitude", "longitude", "latitude_rounded", "longitude_rounded", "installdate", "installedcapacity"]].copy() unlocated = db_SL[db_SL.isnull().any(axis=1)][["latitude", "longitude"]] located = db_SL[~db_SL.isnull().any(axis=1)][["latitude", "longitude"]] db_SL.loc[db_SL.isnull().any(axis=1), ["latitude", "longitude"]] = located.sample(unlocated.shape[0]).values db_SL["latitude_rounded"] = db_SL["latitude"].round(decimals=1) db_SL["longitude_rounded"] = db_SL["longitude"].round(decimals=1) site_lists[quantile] = db_SL self.upload_to_db(db_SL.values.tolist(), self.db_tables[quantile], self.mysql__file) self.test_count_in_DB(self.db_tables[quantile], self.mysql__file, db_SL) return db_SL def upload_to_db(self, data, table, mysql_options_file): # data = [row if for row in data] # import pdb; pdb.set_trace() print("\nUploading to database...\n") if type(data) is not list: raise ValueError("Data to upload must be list of lists...") sql = f"INSERT INTO `{table}` (`gen_id`, `latitude`, `longitude`, " \ f"`latitude_rounded`, `longitude_rounded`, `installdate`, " \ f"`installedcapacity`) VALUES (%s,%s,%s,%s,%s,%s,%s)" \ f"ON DUPLICATE KEY UPDATE " \ f"`latitude` = VALUES(`longitude`)," \ f"longitude = VALUES(`longitude`)," \ f"`installedcapacity` = VALUES(`installedcapacity`);" with DBConnector(mysql_options_file, session_tz="UTC") as dbc: dbc.iud_query(sql, data) print("\t--> done.") def test_count_in_DB(self, table, mysql_options_file, data): SL_count = len(data) sql = f"SELECT count(*) FROM `{table}`;" with DBConnector(mysql_options_file, session_tz="UTC") as dbc: DB_count = dbc.query(sql) if int(DB_count[0][0]) != int(SL_count): import pdb; pdb.set_trace() raise Exception("Wrong number of rows inserted into DB...") @staticmethod def system_in_gb(vec): in_gb = vec[0] latitude = vec[1] longitude = vec[2] test1 = (float(49.87) < float(latitude) < float(59.59)) and \ (float(-8.15) < float(longitude) < float(1.94)) test2 = (float(51.35) < float(latitude) < float(55.40)) and \ (float(-8.15) < float(longitude) < float(4.50)) test3 = (float(49.87) < float(latitude) < float(51.09)) and \ (float(1.47) < float(longitude) < float(1.94)) if not int((test1 and not test2 and not test3)) == int(in_gb): import pdb; pdb.set_trace() return int(test1 and not test2 and not test3) @staticmethod def test_system_in_gb(): file = "C:/Users/owenh/Documents/GitRepos/capacity_mismatch_paper/data/solarsite20190205.csv" data = pd.read_csv(file) data["in_gb2"] = data[["in_gb", "latitude", "longitude"]].apply(system_in_gb, axis=1) data.to_csv("../data/solarsite20190205_edited.csv") return if __name__ == "__main__": # test_system_in_gb() instance = CapacitySitelistUploader() instance.run()
43.040462
147
0.585415
fd0b7309f5faf20e8bac7e806d940ca97271e408
26,655
py
Python
venv/lib/python3.6/site-packages/ansible_collections/community/grafana/plugins/modules/grafana_datasource.py
usegalaxy-no/usegalaxy
75dad095769fe918eb39677f2c887e681a747f3a
[ "MIT" ]
1
2020-01-22T13:11:23.000Z
2020-01-22T13:11:23.000Z
venv/lib/python3.6/site-packages/ansible_collections/community/grafana/plugins/modules/grafana_datasource.py
usegalaxy-no/usegalaxy
75dad095769fe918eb39677f2c887e681a747f3a
[ "MIT" ]
12
2020-02-21T07:24:52.000Z
2020-04-14T09:54:32.000Z
venv/lib/python3.6/site-packages/ansible_collections/community/grafana/plugins/modules/grafana_datasource.py
usegalaxy-no/usegalaxy
75dad095769fe918eb39677f2c887e681a747f3a
[ "MIT" ]
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2017, Thierry Sallé (@seuf) # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' module: grafana_datasource author: - Thierry Sallé (@seuf) - Martin Wang (@martinwangjian) - Rémi REY (@rrey) short_description: Manage Grafana datasources description: - Create/update/delete Grafana datasources via API. options: name: description: - The name of the datasource. required: true type: str ds_type: description: - The type of the datasource. required: true choices: - graphite - prometheus - elasticsearch - influxdb - opentsdb - mysql - postgres - cloudwatch - alexanderzobnin-zabbix-datasource - sni-thruk-datasource - camptocamp-prometheus-alertmanager-datasource - loki - redis-datasource type: str ds_url: description: - The URL of the datasource. required: true type: str access: description: - The access mode for this datasource. choices: - direct - proxy default: proxy type: str database: description: - Name of the database for the datasource. - This options is required when the C(ds_type) is C(influxdb), C(elasticsearch) (index name), C(mysql) or C(postgres). required: false type: str user: description: - The datasource login user for influxdb datasources. type: str password: description: - The datasource password. - For encrypted password use C(additional_secure_json_data.password). type: str basic_auth_user: description: - The datasource basic auth user. - Setting this option with basic_auth_password will enable basic auth. type: str basic_auth_password: description: - The datasource basic auth password, when C(basic auth) is C(yes). type: str with_credentials: description: - Whether credentials such as cookies or auth headers should be sent with cross-site requests. type: bool default: 'no' tls_client_cert: description: - The client TLS certificate. - If C(tls_client_cert) and C(tls_client_key) are set, this will enable TLS authentication. - Starts with ----- BEGIN CERTIFICATE ----- - Stored as secure data, see C(enforce_secure_data) and notes! type: str tls_client_key: description: - The client TLS private key - Starts with ----- BEGIN RSA PRIVATE KEY ----- - Stored as secure data, see C(enforce_secure_data) and notes! type: str tls_ca_cert: description: - The TLS CA certificate for self signed certificates. - Only used when C(tls_client_cert) and C(tls_client_key) are set. - Stored as secure data, see C(enforce_secure_data) and notes! type: str tls_skip_verify: description: - Skip the TLS datasource certificate verification. type: bool default: false is_default: description: - Make this datasource the default one. type: bool default: 'no' org_id: description: - Grafana Organisation ID in which the datasource should be created. - Not used when C(grafana_api_key) is set, because the C(grafana_api_key) only belong to one organisation. default: 1 type: int state: description: - Status of the datasource choices: - absent - present default: present type: str es_version: description: - Elasticsearch version (for C(ds_type = elasticsearch) only) - Version 56 is for elasticsearch 5.6+ where you can specify the C(max_concurrent_shard_requests) option. choices: - 2 - 5 - 56 - 60 - 70 default: 5 type: int max_concurrent_shard_requests: description: - Starting with elasticsearch 5.6, you can specify the max concurrent shard per requests. default: 256 type: int time_field: description: - Name of the time field in elasticsearch ds. - For example C(@timestamp). type: str default: '@timestamp' time_interval: description: - Minimum group by interval for C(influxdb) or C(elasticsearch) datasources. - for example C(>10s). type: str interval: description: - For elasticsearch C(ds_type), this is the index pattern used. choices: - '' - Hourly - Daily - Weekly - Monthly - Yearly type: str tsdb_version: description: - The opentsdb version. - Use C(1) for <=2.1, C(2) for ==2.2, C(3) for ==2.3. choices: - 1 - 2 - 3 default: 1 type: int tsdb_resolution: description: - The opentsdb time resolution. choices: - millisecond - second default: second type: str sslmode: description: - SSL mode for C(postgres) datasource type. choices: - disable - require - verify-ca - verify-full type: str default: disable trends: required: false description: - Use trends or not for zabbix datasource type. type: bool default: False aws_auth_type: description: - Type for AWS authentication for CloudWatch datasource type (authType of grafana api) default: keys choices: - keys - credentials - arn type: str aws_default_region: description: - AWS default region for CloudWatch datasource type default: us-east-1 type: str choices: - ap-northeast-1 - ap-northeast-2 - ap-southeast-1 - ap-southeast-2 - ap-south-1 - ca-central-1 - cn-north-1 - cn-northwest-1 - eu-central-1 - eu-west-1 - eu-west-2 - eu-west-3 - sa-east-1 - us-east-1 - us-east-2 - us-gov-west-1 - us-west-1 - us-west-2 aws_credentials_profile: description: - Profile for AWS credentials for CloudWatch datasource type when C(aws_auth_type) is C(credentials) default: '' required: false type: str aws_access_key: description: - AWS access key for CloudWatch datasource type when C(aws_auth_type) is C(keys) default: '' required: false type: str aws_secret_key: description: - AWS secret key for CloudWatch datasource type when C(aws_auth_type) is C(keys) default: '' required: false type: str aws_assume_role_arn: description: - AWS IAM role arn to assume for CloudWatch datasource type when C(aws_auth_type) is C(arn) default: '' required: false type: str aws_custom_metrics_namespaces: description: - Namespaces of Custom Metrics for CloudWatch datasource type default: '' required: false type: str zabbix_user: description: - User for Zabbix API required: false type: str zabbix_password: description: - Password for Zabbix API required: false type: str additional_json_data: description: - Defined data is used for datasource jsonData - Data may be overridden by specifically defined parameters (like zabbix_user) required: false type: dict default: {} additional_secure_json_data: description: - Defined data is used for datasource secureJsonData - Data may be overridden by specifically defined parameters (like tls_client_cert) - Stored as secure data, see C(enforce_secure_data) and notes! required: false type: dict default: {} enforce_secure_data: description: - Secure data is not updated per default (see notes!) - To update secure data you have to enable this option! - Enabling this, the task will always report changed=True required: false type: bool default: false extends_documentation_fragment: - community.grafana.basic_auth - community.grafana.api_key notes: - Secure data will get encrypted by the Grafana API, thus it can not be compared on subsequent runs. To workaround this, secure data will not be updated after initial creation! To force the secure data update you have to set I(enforce_secure_data=True). - Hint, with the C(enforce_secure_data) always reporting changed=True, you might just do one Task updating the datasource without any secure data and make a separate playbook/task also changing the secure data. This way it will not break any workflow. ''' EXAMPLES = ''' --- - name: Create elasticsearch datasource community.grafana.grafana_datasource: name: "datasource-elastic" grafana_url: "https://grafana.company.com" grafana_user: "admin" grafana_password: "xxxxxx" org_id: "1" ds_type: "elasticsearch" ds_url: "https://elastic.company.com:9200" database: "[logstash_]YYYY.MM.DD" basic_auth_user: "grafana" basic_auth_password: "******" time_field: "@timestamp" time_interval: "1m" interval: "Daily" es_version: 56 max_concurrent_shard_requests: 42 tls_ca_cert: "/etc/ssl/certs/ca.pem" - name: Create influxdb datasource community.grafana.grafana_datasource: name: "datasource-influxdb" grafana_url: "https://grafana.company.com" grafana_user: "admin" grafana_password: "xxxxxx" org_id: "1" ds_type: "influxdb" ds_url: "https://influx.company.com:8086" database: "telegraf" time_interval: ">10s" tls_ca_cert: "/etc/ssl/certs/ca.pem" - name: Create postgres datasource community.grafana.grafana_datasource: name: "datasource-postgres" grafana_url: "https://grafana.company.com" grafana_user: "admin" grafana_password: "xxxxxx" org_id: "1" ds_type: "postgres" ds_url: "postgres.company.com:5432" database: "db" user: "postgres" sslmode: "verify-full" additional_json_data: postgresVersion: 12 timescaledb: false additional_secure_json_data: password: "iampgroot" - name: Create cloudwatch datasource community.grafana.grafana_datasource: name: "datasource-cloudwatch" grafana_url: "https://grafana.company.com" grafana_user: "admin" grafana_password: "xxxxxx" org_id: "1" ds_type: "cloudwatch" ds_url: "http://monitoring.us-west-1.amazonaws.com" aws_auth_type: "keys" aws_default_region: "us-west-1" aws_access_key: "speakFriendAndEnter" aws_secret_key: "mel10n" aws_custom_metrics_namespaces: "n1,n2" - name: grafana - add thruk datasource community.grafana.grafana_datasource: name: "datasource-thruk" grafana_url: "https://grafana.company.com" grafana_user: "admin" grafana_password: "xxxxxx" org_id: "1" ds_type: "sni-thruk-datasource" ds_url: "https://thruk.company.com/sitename/thruk" basic_auth_user: "thruk-user" basic_auth_password: "******" # handle secure data - workflow example # this will create/update the datasource but dont update the secure data on updates # so you can assert if all tasks are changed=False - name: create prometheus datasource community.grafana.grafana_datasource: name: openshift_prometheus ds_type: prometheus ds_url: https://openshift-monitoring.company.com access: proxy tls_skip_verify: true additional_json_data: httpHeaderName1: "Authorization" additional_secure_json_data: httpHeaderValue1: "Bearer ihavenogroot" # in a separate task or even play you then can force to update # and assert if each datasource is reporting changed=True - name: update prometheus datasource community.grafana.grafana_datasource: name: openshift_prometheus ds_type: prometheus ds_url: https://openshift-monitoring.company.com access: proxy tls_skip_verify: true additional_json_data: httpHeaderName1: "Authorization" additional_secure_json_data: httpHeaderValue1: "Bearer ihavenogroot" enforce_secure_data: true ''' RETURN = ''' --- datasource: description: datasource created/updated by module returned: changed type: dict sample: { "access": "proxy", "basicAuth": false, "database": "test_*", "id": 1035, "isDefault": false, "jsonData": { "esVersion": 5, "timeField": "@timestamp", "timeInterval": "10s", }, "secureJsonFields": { "JustASecureTest": true, }, "name": "grafana_datasource_test", "orgId": 1, "type": "elasticsearch", "url": "http://elastic.company.com:9200", "user": "", "password": "", "withCredentials": false } ''' import json from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.six.moves.urllib.parse import quote from ansible.module_utils.urls import fetch_url, url_argument_spec, basic_auth_header from ansible_collections.community.grafana.plugins.module_utils import base def compare_datasources(new, current, compareSecureData=True): if 'uid' in current: del current['uid'] del current['typeLogoUrl'] del current['id'] if 'version' in current: del current['version'] if 'readOnly' in current: del current['readOnly'] if current['basicAuth'] is False: del current['basicAuthUser'] del current['basicAuthPassword'] # check if secureJsonData should be compared if not compareSecureData: # if we should ignore it just drop alltogether new.pop('secureJsonData', None) new.pop('secureJsonFields', None) current.pop('secureJsonData', None) current.pop('secureJsonFields', None) else: # handle secureJsonData/secureJsonFields, some current facts: # - secureJsonFields is reporting each field set as true # - secureJsonFields once set cant be removed (DS has to be deleted) if not new.get('secureJsonData'): # secureJsonData is not provided so just remove both for comparision new.pop('secureJsonData', None) current.pop('secureJsonFields', None) else: # we have some secure data so just "rename" secureJsonFields for comparison as it will change anyhow everytime current['secureJsonData'] = current.pop('secureJsonFields') return dict(before=current, after=new) def get_datasource_payload(data): payload = { 'orgId': data['org_id'], 'name': data['name'], 'type': data['ds_type'], 'access': data['access'], 'url': data['ds_url'], 'database': data['database'], 'withCredentials': data['with_credentials'], 'isDefault': data['is_default'], 'user': data['user'], 'password': data['password'], 'jsonData': data['additional_json_data'], 'secureJsonData': data['additional_secure_json_data'] } # define basic auth if 'basic_auth_user' in data and data['basic_auth_user'] and 'basic_auth_password' in data and data['basic_auth_password']: payload['basicAuth'] = True payload['basicAuthUser'] = data['basic_auth_user'] payload['basicAuthPassword'] = data['basic_auth_password'] else: payload['basicAuth'] = False # define tls auth json_data = payload['jsonData'] secure_json_data = payload['secureJsonData'] if data.get('tls_client_cert') and data.get('tls_client_key'): json_data['tlsAuth'] = True if data.get('tls_ca_cert'): secure_json_data['tlsCACert'] = data['tls_ca_cert'] secure_json_data['tlsClientCert'] = data['tls_client_cert'] secure_json_data['tlsClientKey'] = data['tls_client_key'] json_data['tlsAuthWithCACert'] = True else: secure_json_data['tlsClientCert'] = data['tls_client_cert'] secure_json_data['tlsClientKey'] = data['tls_client_key'] else: json_data['tlsAuth'] = False json_data['tlsAuthWithCACert'] = False if data.get('tls_ca_cert'): json_data['tlsAuthWithCACert'] = True secure_json_data['tlsCACert'] = data['tls_ca_cert'] if data.get('tls_skip_verify'): json_data['tlsSkipVerify'] = True # datasource type related parameters if data['ds_type'] == 'elasticsearch': json_data['esVersion'] = data['es_version'] json_data['timeField'] = data['time_field'] if data.get('interval'): json_data['interval'] = data['interval'] if data['es_version'] >= 56: json_data['maxConcurrentShardRequests'] = data['max_concurrent_shard_requests'] if data['ds_type'] == 'elasticsearch' or data['ds_type'] == 'influxdb': if data.get('time_interval'): json_data['timeInterval'] = data['time_interval'] if data['ds_type'] == 'opentsdb': json_data['tsdbVersion'] = data['tsdb_version'] if data['tsdb_resolution'] == 'second': json_data['tsdbResolution'] = 1 else: json_data['tsdbResolution'] = 2 if data['ds_type'] == 'postgres': json_data['sslmode'] = data['sslmode'] if data['ds_type'] == 'alexanderzobnin-zabbix-datasource': if data.get('trends'): json_data['trends'] = True json_data['username'] = data['zabbix_user'] json_data['password'] = data['zabbix_password'] if data['ds_type'] == 'cloudwatch': if data.get('aws_credentials_profile'): payload['database'] = data.get('aws_credentials_profile') json_data['authType'] = data['aws_auth_type'] json_data['defaultRegion'] = data['aws_default_region'] if data.get('aws_custom_metrics_namespaces'): json_data['customMetricsNamespaces'] = data.get('aws_custom_metrics_namespaces') if data.get('aws_assume_role_arn'): json_data['assumeRoleArn'] = data.get('aws_assume_role_arn') if data.get('aws_access_key') and data.get('aws_secret_key'): secure_json_data['accessKey'] = data.get('aws_access_key') secure_json_data['secretKey'] = data.get('aws_secret_key') payload['jsonData'] = json_data payload['secureJsonData'] = secure_json_data return payload class GrafanaInterface(object): def __init__(self, module): self._module = module self.grafana_url = base.clean_url(module.params.get("url")) # {{{ Authentication header self.headers = {"Content-Type": "application/json"} if module.params.get('grafana_api_key', None): self.headers["Authorization"] = "Bearer %s" % module.params['grafana_api_key'] else: self.headers["Authorization"] = basic_auth_header(module.params['url_username'], module.params['url_password']) self.switch_organisation(module.params['org_id']) # }}} def _send_request(self, url, data=None, headers=None, method="GET"): if data is not None: data = json.dumps(data, sort_keys=True) if not headers: headers = [] full_url = "{grafana_url}{path}".format(grafana_url=self.grafana_url, path=url) resp, info = fetch_url(self._module, full_url, data=data, headers=headers, method=method) status_code = info["status"] if status_code == 404: return None elif status_code == 401: self._module.fail_json(failed=True, msg="Unauthorized to perform action '%s' on '%s'" % (method, full_url)) elif status_code == 403: self._module.fail_json(failed=True, msg="Permission Denied") elif status_code == 200: return self._module.from_json(resp.read()) self._module.fail_json(failed=True, msg="Grafana API answered with HTTP %d for url %s and data %s" % (status_code, url, data)) def switch_organisation(self, org_id): url = "/api/user/using/%d" % org_id response = self._send_request(url, headers=self.headers, method='POST') def datasource_by_name(self, name): datasource_exists = False ds = {} url = "/api/datasources/name/%s" % quote(name, safe='') return self._send_request(url, headers=self.headers, method='GET') def delete_datasource(self, name): url = "/api/datasources/name/%s" % quote(name, safe='') self._send_request(url, headers=self.headers, method='DELETE') def update_datasource(self, ds_id, data): url = "/api/datasources/%d" % ds_id self._send_request(url, data=data, headers=self.headers, method='PUT') def create_datasource(self, data): url = "/api/datasources" self._send_request(url, data=data, headers=self.headers, method='POST') def main(): # use the predefined argument spec for url argument_spec = base.grafana_argument_spec() argument_spec.update( name=dict(required=True, type='str'), ds_type=dict(choices=['graphite', 'prometheus', 'elasticsearch', 'influxdb', 'opentsdb', 'mysql', 'postgres', 'cloudwatch', 'alexanderzobnin-zabbix-datasource', 'camptocamp-prometheus-alertmanager-datasource', 'sni-thruk-datasource', 'redis-datasource', 'loki'], required=True), ds_url=dict(required=True, type='str'), access=dict(default='proxy', choices=['proxy', 'direct']), database=dict(type='str', default=""), user=dict(default='', type='str'), password=dict(default='', no_log=True, type='str'), basic_auth_user=dict(type='str'), basic_auth_password=dict(type='str', no_log=True), with_credentials=dict(default=False, type='bool'), tls_client_cert=dict(type='str', no_log=True), tls_client_key=dict(type='str', no_log=True), tls_ca_cert=dict(type='str', no_log=True), tls_skip_verify=dict(type='bool', default=False), is_default=dict(default=False, type='bool'), org_id=dict(default=1, type='int'), es_version=dict(type='int', default=5, choices=[2, 5, 56, 60, 70]), max_concurrent_shard_requests=dict(type='int', default=256), time_field=dict(default='@timestamp', type='str'), time_interval=dict(type='str'), interval=dict(type='str', choices=['', 'Hourly', 'Daily', 'Weekly', 'Monthly', 'Yearly'], default=''), tsdb_version=dict(type='int', default=1, choices=[1, 2, 3]), tsdb_resolution=dict(type='str', default='second', choices=['second', 'millisecond']), sslmode=dict(default='disable', choices=['disable', 'require', 'verify-ca', 'verify-full']), trends=dict(default=False, type='bool'), aws_auth_type=dict(default='keys', choices=['keys', 'credentials', 'arn']), aws_default_region=dict(default='us-east-1', choices=['ap-northeast-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-south-1', 'ca-central-1', 'cn-north-1', 'cn-northwest-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'sa-east-1', 'us-east-1', 'us-east-2', 'us-gov-west-1', 'us-west-1', 'us-west-2']), aws_access_key=dict(default='', no_log=True, type='str'), aws_secret_key=dict(default='', no_log=True, type='str'), aws_credentials_profile=dict(default='', type='str'), aws_assume_role_arn=dict(default='', type='str'), aws_custom_metrics_namespaces=dict(type='str'), zabbix_user=dict(type='str'), zabbix_password=dict(type='str', no_log=True), additional_json_data=dict(type='dict', default={}, required=False), additional_secure_json_data=dict(type='dict', default={}, required=False), enforce_secure_data=dict(type='bool', default=False, required=False) ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=False, required_together=[['url_username', 'url_password', 'org_id'], ['tls_client_cert', 'tls_client_key']], mutually_exclusive=[['url_username', 'grafana_api_key'], ['tls_ca_cert', 'tls_skip_verify']], required_if=[ ['ds_type', 'opentsdb', ['tsdb_version', 'tsdb_resolution']], ['ds_type', 'influxdb', ['database']], ['ds_type', 'elasticsearch', ['database', 'es_version', 'time_field', 'interval']], ['ds_type', 'mysql', ['database']], ['ds_type', 'postgres', ['database', 'sslmode']], ['ds_type', 'cloudwatch', ['aws_auth_type', 'aws_default_region']], ['es_version', 56, ['max_concurrent_shard_requests']], ['es_version', 60, ['max_concurrent_shard_requests']], ['es_version', 70, ['max_concurrent_shard_requests']] ], ) state = module.params['state'] name = module.params['name'] enforce_secure_data = module.params['enforce_secure_data'] grafana_iface = GrafanaInterface(module) ds = grafana_iface.datasource_by_name(name) if state == 'present': payload = get_datasource_payload(module.params) if ds is None: grafana_iface.create_datasource(payload) ds = grafana_iface.datasource_by_name(name) module.exit_json(changed=True, datasource=ds, msg='Datasource %s created' % name) else: diff = compare_datasources(payload.copy(), ds.copy(), enforce_secure_data) if diff.get('before') == diff.get('after'): module.exit_json(changed=False, datasource=ds, msg='Datasource %s unchanged' % name) grafana_iface.update_datasource(ds.get('id'), payload) ds = grafana_iface.datasource_by_name(name) if diff.get('before') == diff.get('after'): module.exit_json(changed=False, datasource=ds, msg='Datasource %s unchanged' % name) module.exit_json(changed=True, diff=diff, datasource=ds, msg='Datasource %s updated' % name) else: if ds is None: module.exit_json(changed=False, datasource=None, msg='Datasource %s does not exist.' % name) grafana_iface.delete_datasource(name) module.exit_json(changed=True, datasource=None, msg='Datasource %s deleted.' % name) if __name__ == '__main__': main()
35.072368
147
0.64003
bd5fb92a2d29450c371c9f6740e916c6e9b80e8e
2,084
py
Python
wordspotting/att/emb_atts.py
cwiep/query-by-online-handwriting
d38178b1c558f11f6bc2bae2840737fb6c8ea89a
[ "Apache-2.0" ]
3
2016-09-29T08:28:23.000Z
2022-01-24T17:19:38.000Z
wordspotting/att/emb_atts.py
cwiep/query-by-online-handwriting
d38178b1c558f11f6bc2bae2840737fb6c8ea89a
[ "Apache-2.0" ]
null
null
null
wordspotting/att/emb_atts.py
cwiep/query-by-online-handwriting
d38178b1c558f11f6bc2bae2840737fb6c8ea89a
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- """ @author: Christian Wieprecht @license: Apache License, Version 2.0 Building Attribute SVMS as described in "Word Spotting and Recognition with Embedded Attributes" by Almazan et al. """ import numpy as np import platt import tools.logging as log import svm class AttributesSVMGenerator(): def __init__(self): self.attribute_svms = None self.platts = False self.transform = None self.train_scores = None def fit(self, X, Y, platts=False): self.attribute_svms = svm.learn_embedded_attributes(X, Y) self.train_scores = svm.classify_embedded_attributes(X, self.attribute_svms) if platts: self.platts = True self.__learn_sigmoid_params(X) def __learn_sigmoid_params(self, data_mat): log.d("Platt's scaling (visual feature SVMs)...") class_labels = svm.predict_embedded_attributes_labels(data_mat, self.attribute_svms) self.sigmoid_params = platt.learn_platts_scaling_params(self.train_scores, class_labels) del class_labels def score(self, X): scores = svm.classify_embedded_attributes(X, self.attribute_svms) if self.platts: return platt.perform_platts_scaling(scores, self.sigmoid_params).T if self.transform is not None: # there is no nice way to test ndarray against None... if not np.equal(self.transform, None): return np.dot(scores.T, self.transform) return scores.T def save_to_file(self, path): log.d("Saving svms to {}".format(path)) f = file(path, "wb") np.save(f, self.attribute_svms) np.save(f, self.platts) np.save(f, self.transform) if self.platts: np.save(f, self.sigmoid_params) f.close() def load_from_file(self, path): f = file(path, "rb") self.attribute_svms = np.load(f) self.platts = np.load(f) self.transform = np.load(f) if self.platts: self.sigmoid_params = np.load(f) f.close()
32.5625
96
0.642514
a68d46e8a6c1502bc89dad4ae22b9a7ac6f8e4a1
15,684
py
Python
pandas/tests/io/parser/test_dtypes.py
LauraCollard/pandas
b1c3a9031569334cafc4e8d45d35408421f7dea4
[ "BSD-3-Clause" ]
2
2019-12-02T11:24:30.000Z
2021-02-28T12:13:54.000Z
pandas/tests/io/parser/test_dtypes.py
ivan-vasilev/pandas
4071dde86e33434e1bee8304fa62074949f813cc
[ "BSD-3-Clause" ]
1
2019-10-31T08:19:49.000Z
2019-10-31T08:19:49.000Z
pandas/tests/io/parser/test_dtypes.py
ivan-vasilev/pandas
4071dde86e33434e1bee8304fa62074949f813cc
[ "BSD-3-Clause" ]
4
2019-10-09T07:52:08.000Z
2021-07-12T02:37:59.000Z
""" Tests dtype specification during parsing for all of the parsers defined in parsers.py """ from io import StringIO import os import numpy as np import pytest from pandas.errors import ParserWarning from pandas.core.dtypes.dtypes import CategoricalDtype import pandas as pd from pandas import Categorical, DataFrame, Index, MultiIndex, Series, Timestamp, concat import pandas.util.testing as tm @pytest.mark.parametrize("dtype", [str, object]) @pytest.mark.parametrize("check_orig", [True, False]) def test_dtype_all_columns(all_parsers, dtype, check_orig): # see gh-3795, gh-6607 parser = all_parsers df = DataFrame( np.random.rand(5, 2).round(4), columns=list("AB"), index=["1A", "1B", "1C", "1D", "1E"], ) with tm.ensure_clean("__passing_str_as_dtype__.csv") as path: df.to_csv(path) result = parser.read_csv(path, dtype=dtype, index_col=0) if check_orig: expected = df.copy() result = result.astype(float) else: expected = df.astype(str) tm.assert_frame_equal(result, expected) def test_dtype_all_columns_empty(all_parsers): # see gh-12048 parser = all_parsers result = parser.read_csv(StringIO("A,B"), dtype=str) expected = DataFrame({"A": [], "B": []}, index=[], dtype=str) tm.assert_frame_equal(result, expected) def test_dtype_per_column(all_parsers): parser = all_parsers data = """\ one,two 1,2.5 2,3.5 3,4.5 4,5.5""" expected = DataFrame( [[1, "2.5"], [2, "3.5"], [3, "4.5"], [4, "5.5"]], columns=["one", "two"] ) expected["one"] = expected["one"].astype(np.float64) expected["two"] = expected["two"].astype(object) result = parser.read_csv(StringIO(data), dtype={"one": np.float64, 1: str}) tm.assert_frame_equal(result, expected) def test_invalid_dtype_per_column(all_parsers): parser = all_parsers data = """\ one,two 1,2.5 2,3.5 3,4.5 4,5.5""" with pytest.raises(TypeError, match='data type "foo" not understood'): parser.read_csv(StringIO(data), dtype={"one": "foo", 1: "int"}) @pytest.mark.parametrize( "dtype", [ "category", CategoricalDtype(), {"a": "category", "b": "category", "c": CategoricalDtype()}, ], ) def test_categorical_dtype(all_parsers, dtype): # see gh-10153 parser = all_parsers data = """a,b,c 1,a,3.4 1,a,3.4 2,b,4.5""" expected = DataFrame( { "a": Categorical(["1", "1", "2"]), "b": Categorical(["a", "a", "b"]), "c": Categorical(["3.4", "3.4", "4.5"]), } ) actual = parser.read_csv(StringIO(data), dtype=dtype) tm.assert_frame_equal(actual, expected) @pytest.mark.parametrize("dtype", [{"b": "category"}, {1: "category"}]) def test_categorical_dtype_single(all_parsers, dtype): # see gh-10153 parser = all_parsers data = """a,b,c 1,a,3.4 1,a,3.4 2,b,4.5""" expected = DataFrame( {"a": [1, 1, 2], "b": Categorical(["a", "a", "b"]), "c": [3.4, 3.4, 4.5]} ) actual = parser.read_csv(StringIO(data), dtype=dtype) tm.assert_frame_equal(actual, expected) def test_categorical_dtype_unsorted(all_parsers): # see gh-10153 parser = all_parsers data = """a,b,c 1,b,3.4 1,b,3.4 2,a,4.5""" expected = DataFrame( { "a": Categorical(["1", "1", "2"]), "b": Categorical(["b", "b", "a"]), "c": Categorical(["3.4", "3.4", "4.5"]), } ) actual = parser.read_csv(StringIO(data), dtype="category") tm.assert_frame_equal(actual, expected) def test_categorical_dtype_missing(all_parsers): # see gh-10153 parser = all_parsers data = """a,b,c 1,b,3.4 1,nan,3.4 2,a,4.5""" expected = DataFrame( { "a": Categorical(["1", "1", "2"]), "b": Categorical(["b", np.nan, "a"]), "c": Categorical(["3.4", "3.4", "4.5"]), } ) actual = parser.read_csv(StringIO(data), dtype="category") tm.assert_frame_equal(actual, expected) @pytest.mark.slow def test_categorical_dtype_high_cardinality_numeric(all_parsers): # see gh-18186 parser = all_parsers data = np.sort([str(i) for i in range(524289)]) expected = DataFrame({"a": Categorical(data, ordered=True)}) actual = parser.read_csv(StringIO("a\n" + "\n".join(data)), dtype="category") actual["a"] = actual["a"].cat.reorder_categories( np.sort(actual.a.cat.categories), ordered=True ) tm.assert_frame_equal(actual, expected) def test_categorical_dtype_latin1(all_parsers, csv_dir_path): # see gh-10153 pth = os.path.join(csv_dir_path, "unicode_series.csv") parser = all_parsers encoding = "latin-1" expected = parser.read_csv(pth, header=None, encoding=encoding) expected[1] = Categorical(expected[1]) actual = parser.read_csv(pth, header=None, encoding=encoding, dtype={1: "category"}) tm.assert_frame_equal(actual, expected) def test_categorical_dtype_utf16(all_parsers, csv_dir_path): # see gh-10153 pth = os.path.join(csv_dir_path, "utf16_ex.txt") parser = all_parsers encoding = "utf-16" sep = "," expected = parser.read_csv(pth, sep=sep, encoding=encoding) expected = expected.apply(Categorical) actual = parser.read_csv(pth, sep=sep, encoding=encoding, dtype="category") tm.assert_frame_equal(actual, expected) def test_categorical_dtype_chunksize_infer_categories(all_parsers): # see gh-10153 parser = all_parsers data = """a,b 1,a 1,b 1,b 2,c""" expecteds = [ DataFrame({"a": [1, 1], "b": Categorical(["a", "b"])}), DataFrame({"a": [1, 2], "b": Categorical(["b", "c"])}, index=[2, 3]), ] actuals = parser.read_csv(StringIO(data), dtype={"b": "category"}, chunksize=2) for actual, expected in zip(actuals, expecteds): tm.assert_frame_equal(actual, expected) def test_categorical_dtype_chunksize_explicit_categories(all_parsers): # see gh-10153 parser = all_parsers data = """a,b 1,a 1,b 1,b 2,c""" cats = ["a", "b", "c"] expecteds = [ DataFrame({"a": [1, 1], "b": Categorical(["a", "b"], categories=cats)}), DataFrame( {"a": [1, 2], "b": Categorical(["b", "c"], categories=cats)}, index=[2, 3] ), ] dtype = CategoricalDtype(cats) actuals = parser.read_csv(StringIO(data), dtype={"b": dtype}, chunksize=2) for actual, expected in zip(actuals, expecteds): tm.assert_frame_equal(actual, expected) @pytest.mark.parametrize("ordered", [False, True]) @pytest.mark.parametrize( "categories", [["a", "b", "c"], ["a", "c", "b"], ["a", "b", "c", "d"], ["c", "b", "a"]], ) def test_categorical_category_dtype(all_parsers, categories, ordered): parser = all_parsers data = """a,b 1,a 1,b 1,b 2,c""" expected = DataFrame( { "a": [1, 1, 1, 2], "b": Categorical( ["a", "b", "b", "c"], categories=categories, ordered=ordered ), } ) dtype = {"b": CategoricalDtype(categories=categories, ordered=ordered)} result = parser.read_csv(StringIO(data), dtype=dtype) tm.assert_frame_equal(result, expected) def test_categorical_category_dtype_unsorted(all_parsers): parser = all_parsers data = """a,b 1,a 1,b 1,b 2,c""" dtype = CategoricalDtype(["c", "b", "a"]) expected = DataFrame( { "a": [1, 1, 1, 2], "b": Categorical(["a", "b", "b", "c"], categories=["c", "b", "a"]), } ) result = parser.read_csv(StringIO(data), dtype={"b": dtype}) tm.assert_frame_equal(result, expected) def test_categorical_coerces_numeric(all_parsers): parser = all_parsers dtype = {"b": CategoricalDtype([1, 2, 3])} data = "b\n1\n1\n2\n3" expected = DataFrame({"b": Categorical([1, 1, 2, 3])}) result = parser.read_csv(StringIO(data), dtype=dtype) tm.assert_frame_equal(result, expected) def test_categorical_coerces_datetime(all_parsers): parser = all_parsers dtype = {"b": CategoricalDtype(pd.date_range("2017", "2019", freq="AS"))} data = "b\n2017-01-01\n2018-01-01\n2019-01-01" expected = DataFrame({"b": Categorical(dtype["b"].categories)}) result = parser.read_csv(StringIO(data), dtype=dtype) tm.assert_frame_equal(result, expected) def test_categorical_coerces_timestamp(all_parsers): parser = all_parsers dtype = {"b": CategoricalDtype([Timestamp("2014")])} data = "b\n2014-01-01\n2014-01-01T00:00:00" expected = DataFrame({"b": Categorical([Timestamp("2014")] * 2)}) result = parser.read_csv(StringIO(data), dtype=dtype) tm.assert_frame_equal(result, expected) def test_categorical_coerces_timedelta(all_parsers): parser = all_parsers dtype = {"b": CategoricalDtype(pd.to_timedelta(["1H", "2H", "3H"]))} data = "b\n1H\n2H\n3H" expected = DataFrame({"b": Categorical(dtype["b"].categories)}) result = parser.read_csv(StringIO(data), dtype=dtype) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "data", [ "b\nTrue\nFalse\nNA\nFalse", "b\ntrue\nfalse\nNA\nfalse", "b\nTRUE\nFALSE\nNA\nFALSE", "b\nTrue\nFalse\nNA\nFALSE", ], ) def test_categorical_dtype_coerces_boolean(all_parsers, data): # see gh-20498 parser = all_parsers dtype = {"b": CategoricalDtype([False, True])} expected = DataFrame({"b": Categorical([True, False, None, False])}) result = parser.read_csv(StringIO(data), dtype=dtype) tm.assert_frame_equal(result, expected) def test_categorical_unexpected_categories(all_parsers): parser = all_parsers dtype = {"b": CategoricalDtype(["a", "b", "d", "e"])} data = "b\nd\na\nc\nd" # Unexpected c expected = DataFrame({"b": Categorical(list("dacd"), dtype=dtype["b"])}) result = parser.read_csv(StringIO(data), dtype=dtype) tm.assert_frame_equal(result, expected) def test_empty_pass_dtype(all_parsers): parser = all_parsers data = "one,two" result = parser.read_csv(StringIO(data), dtype={"one": "u1"}) expected = DataFrame( {"one": np.empty(0, dtype="u1"), "two": np.empty(0, dtype=np.object)}, index=Index([], dtype=object), ) tm.assert_frame_equal(result, expected) def test_empty_with_index_pass_dtype(all_parsers): parser = all_parsers data = "one,two" result = parser.read_csv( StringIO(data), index_col=["one"], dtype={"one": "u1", 1: "f"} ) expected = DataFrame( {"two": np.empty(0, dtype="f")}, index=Index([], dtype="u1", name="one") ) tm.assert_frame_equal(result, expected) def test_empty_with_multi_index_pass_dtype(all_parsers): parser = all_parsers data = "one,two,three" result = parser.read_csv( StringIO(data), index_col=["one", "two"], dtype={"one": "u1", 1: "f8"} ) exp_idx = MultiIndex.from_arrays( [np.empty(0, dtype="u1"), np.empty(0, dtype=np.float64)], names=["one", "two"] ) expected = DataFrame({"three": np.empty(0, dtype=np.object)}, index=exp_idx) tm.assert_frame_equal(result, expected) def test_empty_with_mangled_column_pass_dtype_by_names(all_parsers): parser = all_parsers data = "one,one" result = parser.read_csv(StringIO(data), dtype={"one": "u1", "one.1": "f"}) expected = DataFrame( {"one": np.empty(0, dtype="u1"), "one.1": np.empty(0, dtype="f")}, index=Index([], dtype=object), ) tm.assert_frame_equal(result, expected) def test_empty_with_mangled_column_pass_dtype_by_indexes(all_parsers): parser = all_parsers data = "one,one" result = parser.read_csv(StringIO(data), dtype={0: "u1", 1: "f"}) expected = DataFrame( {"one": np.empty(0, dtype="u1"), "one.1": np.empty(0, dtype="f")}, index=Index([], dtype=object), ) tm.assert_frame_equal(result, expected) def test_empty_with_dup_column_pass_dtype_by_indexes(all_parsers): # see gh-9424 parser = all_parsers expected = concat( [Series([], name="one", dtype="u1"), Series([], name="one.1", dtype="f")], axis=1, ) expected.index = expected.index.astype(object) data = "one,one" result = parser.read_csv(StringIO(data), dtype={0: "u1", 1: "f"}) tm.assert_frame_equal(result, expected) def test_empty_with_dup_column_pass_dtype_by_indexes_raises(all_parsers): # see gh-9424 parser = all_parsers expected = concat( [Series([], name="one", dtype="u1"), Series([], name="one.1", dtype="f")], axis=1, ) expected.index = expected.index.astype(object) with pytest.raises(ValueError, match="Duplicate names"): data = "" parser.read_csv(StringIO(data), names=["one", "one"], dtype={0: "u1", 1: "f"}) def test_raise_on_passed_int_dtype_with_nas(all_parsers): # see gh-2631 parser = all_parsers data = """YEAR, DOY, a 2001,106380451,10 2001,,11 2001,106380451,67""" msg = ( "Integer column has NA values" if parser.engine == "c" else "Unable to convert column DOY" ) with pytest.raises(ValueError, match=msg): parser.read_csv(StringIO(data), dtype={"DOY": np.int64}, skipinitialspace=True) def test_dtype_with_converters(all_parsers): parser = all_parsers data = """a,b 1.1,2.2 1.2,2.3""" # Dtype spec ignored if converted specified. with tm.assert_produces_warning(ParserWarning): result = parser.read_csv( StringIO(data), dtype={"a": "i8"}, converters={"a": lambda x: str(x)} ) expected = DataFrame({"a": ["1.1", "1.2"], "b": [2.2, 2.3]}) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "dtype,expected", [ (np.float64, DataFrame(columns=["a", "b"], dtype=np.float64)), ("category", DataFrame({"a": Categorical([]), "b": Categorical([])}, index=[])), ( dict(a="category", b="category"), DataFrame({"a": Categorical([]), "b": Categorical([])}, index=[]), ), ("datetime64[ns]", DataFrame(columns=["a", "b"], dtype="datetime64[ns]")), ( "timedelta64[ns]", DataFrame( { "a": Series([], dtype="timedelta64[ns]"), "b": Series([], dtype="timedelta64[ns]"), }, index=[], ), ), ( dict(a=np.int64, b=np.int32), DataFrame( {"a": Series([], dtype=np.int64), "b": Series([], dtype=np.int32)}, index=[], ), ), ( {0: np.int64, 1: np.int32}, DataFrame( {"a": Series([], dtype=np.int64), "b": Series([], dtype=np.int32)}, index=[], ), ), ( {"a": np.int64, 1: np.int32}, DataFrame( {"a": Series([], dtype=np.int64), "b": Series([], dtype=np.int32)}, index=[], ), ), ], ) def test_empty_dtype(all_parsers, dtype, expected): # see gh-14712 parser = all_parsers data = "a,b" result = parser.read_csv(StringIO(data), header=0, dtype=dtype) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "dtype", list(np.typecodes["AllInteger"] + np.typecodes["Float"]) ) def test_numeric_dtype(all_parsers, dtype): data = "0\n1" parser = all_parsers expected = DataFrame([0, 1], dtype=dtype) result = parser.read_csv(StringIO(data), header=None, dtype=dtype) tm.assert_frame_equal(expected, result)
28.361664
88
0.604756
987b271e2006b3f32f112a845e30fd8b94f4903e
847
py
Python
8_leader.py
alexey-ernest/codility
8545d9d15531cb7d3592e872b9324b72f5ef150f
[ "MIT" ]
null
null
null
8_leader.py
alexey-ernest/codility
8545d9d15531cb7d3592e872b9324b72f5ef150f
[ "MIT" ]
null
null
null
8_leader.py
alexey-ernest/codility
8545d9d15531cb7d3592e872b9324b72f5ef150f
[ "MIT" ]
null
null
null
""" Fast leader search algorithm: O(n) Leader is a number which occurs more than n/2 times """ def leader(A): n = len(A) size = 0 value = None for i in xrange(n): if size == 0: # push first element to the stack size += 1 value = A[i] else: if value != A[i]: # remove to different elements from the stack (one from the top and one new) size -= 1 else: # put the same number as the all elements in the stack size += 1 if size == 0: return -1 candidate = value leader = -1 count = 0 # counting candidate occurences for i in xrange(n): if A[i] == candidate: count += 1 if count > n // 2: leader = candidate return leader assert leader([6,8,4,6,8,6,6]) == 6 assert leader([6,8,4,6,8,6,6,6]) == 6 assert leader([6,8,4,6,8,6]) == -1
18.822222
84
0.565525
5297ba5aaf1755ebb3f9fa9dc60b9bc4d2cbd20a
16,329
py
Python
triggers/storages/base.py
todofixthis/triggers
f02c28d95ff094023c9bebe431ad166c912cdabf
[ "MIT" ]
2
2018-01-02T00:46:58.000Z
2018-05-20T05:10:45.000Z
triggers/storages/base.py
todofixthis/triggers
f02c28d95ff094023c9bebe431ad166c912cdabf
[ "MIT" ]
null
null
null
triggers/storages/base.py
todofixthis/triggers
f02c28d95ff094023c9bebe431ad166c912cdabf
[ "MIT" ]
2
2018-02-19T19:46:00.000Z
2019-08-14T20:09:47.000Z
# coding=utf-8 from __future__ import absolute_import, division, print_function, \ unicode_literals from abc import ABCMeta, abstractmethod as abstract_method from collections import defaultdict from contextlib import contextmanager as context_manager from typing import Any, Dict, Iterable, Mapping, MutableMapping, Optional, \ Text, Tuple, Union, List from class_registry import EntryPointClassRegistry from six import iteritems, itervalues, with_metaclass from triggers.locking import Lockable from triggers.types import TaskConfig, TaskInstance __all__ = [ 'BaseTriggerStorage', 'TaskInstanceCollection', 'storage_backends', ] class BaseTriggerStorage(with_metaclass(ABCMeta, Lockable)): """ Base functionality for trigger storage backends. """ name = None # type: Text """ Unique identifier used to look up this storage backend type, e.g., when running celery tasks. References: - :py:data:`storages` """ def __init__(self, uid): # type: (Text) -> None """ :param uid: Identifier that the backend can use to load the corresponding data. """ super(BaseTriggerStorage, self).__init__() self.uid = uid # type: Text self._loaded = False # type: bool """ Prevents loading data from the backend unnecessarily. """ self._configs = None # type: Dict[Text, TaskConfig] """ Locally-cached task configurations ("tasks"). """ self._instances = None # type: TaskInstanceCollection """ Locally-cached task instances. """ self._metas = None # type: dict """ Locally-cached session metadata ("status"). """ def __getitem__(self, instance_name): # type: (Text) -> TaskInstance """ Retrieves a task instance. Note: After being loaded from the backend, the instance caches the values locally. """ return self.instances[instance_name] def __iter__(self): # type: () -> Iterable[TaskInstance] """ Returns a generator for iterating over task instances. """ self._load() return itervalues(self._instances) @abstract_method def _load_from_backend(self): # type: () -> Tuple[Mapping, Mapping, Mapping] """ Loads configuration and status values from the backend. :return: (task configs, task instances, session metadata) """ raise NotImplementedError( 'Not implemented in {cls}.'.format(cls=type(self).__name__), ) # noinspection PyMethodMayBeStatic def _load_default_configuration(self): # type: () -> Optional[Mapping] """ Loads the default configuration to use if the session does not have an existing one stored in the backend. :return: Trigger task configuration (i.e., a value that could be passed to :py:meth:`update_configuration`). """ return None @abstract_method def _save(self): """ Persists changes to the backend. This method MAY assume that the instance owns the active lock for the current UID. References: - https://www.ietf.org/rfc/rfc2119.txt """ raise NotImplementedError( 'Not implemented in {cls}.'.format(cls=type(self).__name__), ) @property def tasks(self): # type: () -> Dict[Text, TaskConfig] """ Returns the task configurations stored in the backend. Note: After being loaded from the backend, the instance caches the values locally. """ self._load() return self._configs @property def instances(self): # type: () -> Union[TaskInstanceCollection, Dict[Text, TaskInstance]] """ Returns the task instances stored in the backend. Note: After being loaded from the backend, the instance caches the values locally. """ self._load() return self._instances @property def latest_kwargs(self): # type: () -> Dict[Text, Mapping] """ Returns the most recent kwargs received for each trigger. """ return self.metadata['latest_kwargs'] def get_lock_name(self): # type: () -> Text """ Returns the key used to lock the UID. References: - :py:class:`Lockable` """ return 'triggers:{uid}:lock'.format( uid = self.uid, ) @property def metadata(self): # type: () -> Mapping """ Returns session metadata (status info not attached to individual tasks). """ self._load() return self._metas @context_manager def acquire_lock(self, ttl=True, block=True): """ Attempts to acquire a lock on the storage backend, forcing a reload of the locally-stored data and ensuring that no other tasks/processes for the same UID can write to the backend until the lock is released. It is important that you invoke this method before performing any actions that result in changes to the stored data. This helps eliminate race conditions when two or more tasks for the same UID are running in parallel. :param ttl: Number of seconds before the lock expires. If ``True`` (default), the cache's ``default_timeout`` value is used. :param block: Determines what happens if the lock is not available: - ``True`` (Default): Wait until the lock is released, giving up after `ttl` seconds. - ``False``: Give up right away (by raising an exception). :raise: - :py:class:`common.cache.lock.LockAcquisitionFailed` if the lock is not available and ``block`` is ``False``. """ if self.has_lock: yield self else: with super(BaseTriggerStorage, self).acquire_lock(ttl, block): # Ensure that we reload data from the backend, just in # case another process/thread made changes while we # weren't looking. if self._loaded: self.invalidate_cache() yield self def get_instances_with_unresolved_logs(self): # type: () -> List[TaskInstance] """ Returns all task instances that have unresolved log messages. """ return [ instance for instance in self.iter_instances() if not instance.logs_resolved ] def get_unresolved_tasks(self): # type: () -> List[TaskConfig] """ Returns all trigger tasks where: - At least one of its instances is unresolved, or - no instances have been created yet (i.e., none of the triggers in its ``after`` clause have fired yet). :return: :py:class:`TaskConfig` objects. Order is undefined. """ unresolved = [] for task in itervalues(self.tasks): instances = itervalues(self.instances_of_task(task)) try: instance = next(instances) except StopIteration: # Task has no instances yet. unresolved.append(task) else: while instance: if not instance.is_resolved: # Task has at least one unresolved instance. unresolved.append(task) break instance = next(instances, None) return unresolved def get_unresolved_instances(self): # type: () -> List[TaskInstance] """ Returns all task instances that are currently in unresolved state. Note: if none of a task's triggers have fired yet, then it will not have any instances. The task itself is might be considered "unresolved", but it will have no unresolved instances. To get a list of unresolved tasks, invoke the :py:meth:`get_unresolved_tasks` method instead. :return: :py:class:`TaskInstance` objects. Order is undefined. """ return [ instance for instance in self.iter_instances() if not instance.is_resolved ] def iter_instances(self): # type: () -> Iterable[TaskInstance] """ Returns a generator for iterating over all task instances. """ return itervalues(self.instances) def clone_instance(self, task_instance): # type: (Union[TaskInstance, Text]) -> TaskInstance """ Installs a clone of an existing TaskInstance. :param task_instance: :py:class:`TaskInstance` object, or instance name. :return: The cloned task instance. """ if not isinstance(task_instance, TaskInstance): task_instance = self.instances[task_instance] return self.create_instance( abandonState = task_instance.abandon_state, kwargs = task_instance.kwargs, task_config = task_instance.config, metadata = { TaskInstance.META_DEPTH: task_instance.depth + 1, TaskInstance.META_PARENT: task_instance.name, }, ) def create_instance(self, task_config, **kwargs): # type: (Union[TaskConfig, Text], **Any) -> TaskInstance """ Installs a new :py:class:`TaskInstance`. :type task_config: :py:class:`TaskConfig` object, or task name. :param kwargs: Additional kwargs to provide to the TaskInstance initializer. """ self._load() if not isinstance(task_config, TaskConfig): task_config = self.tasks[task_config] return self._instances.create_instance( task_config = task_config, status = TaskInstance.STATUS_UNSTARTED, **kwargs ) def instances_of_task(self, task_config): # type: (Union[TaskConfig, Text]) -> Dict[Text, TaskInstance] """ Returns all instances that have been created for the specified task. :param task_config: :py:class:`TaskConfig` object, or task name. """ self._load() return self._instances.get_from_task(task_config) def close(self, *args, **kwargs): """ Closes the active connection to the storage backend. """ pass def save(self): """ Persists changes to the backend. """ if not self.has_lock: raise RuntimeError('You must ``acquire_lock`` before saving!') # If we haven't loaded anything yet, then it's guaranteed that # we haven't modified anything yet, either. if self._loaded: self._save() def invalidate_cache(self): """ Invalidates locally-cached values so that they are reloaded from the backend on next access. """ self._loaded = False self._configs = None self._instances = None self._metas = None def update_configuration(self, config_dict): # type: (Mapping[Text, Mapping]) -> None """ Updates the configuration from a dict. Note: Changes will NOT be persisted until you call :py:meth:`save`. """ self._load() self._update_configs(config_dict, {}) def debug_repr(self): # type: () -> dict """ Returns a dict representation of the trigger storage data, useful for debugging. """ self._load() return { 'tasks': self._serialize(self.tasks, False), 'instances': self._serialize(self.instances, False), 'metas': self._metas, } def _load(self, force=False): # type: (bool) -> None """ Loads values from the backend. """ if force or not self._loaded: raw_configs, raw_statuses, raw_metas = self._load_from_backend() self._configs = {} self._instances = TaskInstanceCollection() if not raw_configs: raw_configs = self._load_default_configuration() if raw_configs: self._update_configs(raw_configs, raw_statuses) # Meta status is a bit easier to load. self._metas = raw_metas or {} # Ensure metas have the proper types. self._metas.setdefault('latest_kwargs', {}) self._loaded = True def _update_configs(self, raw_configs, raw_statuses): # type: (Mapping[Text, Mapping], Mapping[Text, MutableMapping]) -> None """ Updates local task config cache. """ for name, raw_config in iteritems(raw_configs): self._configs[name] = TaskConfig(name=name, **raw_config) for name, raw_status in iteritems(raw_statuses): self._instances.create_instance( name = name, task_config = self._configs[raw_status.pop('task')], **raw_status ) # noinspection PyMethodMayBeStatic,PyUnusedLocal def _serialize(self, dict_, optimize_for_backend=True): # type: (Union[Dict[Text, TaskConfig], TaskInstance], bool) -> dict """ Serializes values in a config/status dict so they can be persisted to the backend. :param optimize_for_backend: Whether to optimize the result for backend storage. Depending on the backend, this parameter might have no effect. """ return { name: obj.serialize() for name, obj in iteritems(dict_) } class TaskInstanceCollection(dict): """ Keeps track of collections of TaskInstances. """ def __init__(self): super(TaskInstanceCollection, self).__init__() self._collections = defaultdict(dict) # type: Union[defaultdict, Dict[Text, Dict[Text, TaskInstance]]] """ Indexes TaskInstances by task name so that we can apply numeric suffixes. """ def get_from_task(self, task_config): # type: (Union[TaskConfig, Text]) -> Dict[Text, TaskInstance] """ Returns all instances matching the specified task. :param task_config: :py:class:`TaskConfig` instance, or task name. :return: Returns an empty dict if the task has no instances. """ if isinstance(task_config, TaskConfig): task_config = task_config.name return self._collections.get(task_config, {}) def create_instance(self, task_config, name=None, **kwargs): # type: (TaskConfig, Optional[Text], **Any) -> TaskInstance """ Creates a new TaskInstance. :param task_config: The configuration that the new instance will use. :param name: Instance name. Will be auto-assigned if omitted. :param kwargs: Additional kwargs to pass to the TaskInstance initializer. """ if name is None: name = '{task}#{i}'.format( task = task_config.name, i = len(self._collections[task_config.name]), ) instance = TaskInstance( name = name, config = task_config, **kwargs ) self[name] = instance self._collections[task_config.name][name] = instance return instance storage_backends =\ EntryPointClassRegistry( attr_name = 'triggers__registry_key', group = 'triggers.storages', ) # type: Union[EntryPointClassRegistry, Dict[Text, BaseTriggerStorage]] """ Registry of storage backends available to the triggers framework. """
30.071823
110
0.580623
d64625336c49ddec40a4ab86ec56bc8581c935b2
5,398
py
Python
hummingbot/connector/exchange/altmarkets/altmarkets_in_flight_order.py
pecuniafinance/hummingbot
2cbb19c187a429d3e6000dc938617ca2a1f9f357
[ "Apache-2.0" ]
542
2021-12-17T22:34:31.000Z
2022-03-31T14:36:23.000Z
hummingbot/connector/exchange/altmarkets/altmarkets_in_flight_order.py
pecuniafinance/hummingbot
2cbb19c187a429d3e6000dc938617ca2a1f9f357
[ "Apache-2.0" ]
291
2021-12-17T20:07:53.000Z
2022-03-31T11:07:23.000Z
hummingbot/connector/exchange/altmarkets/altmarkets_in_flight_order.py
pecuniafinance/hummingbot
2cbb19c187a429d3e6000dc938617ca2a1f9f357
[ "Apache-2.0" ]
220
2021-12-17T12:41:23.000Z
2022-03-31T23:03:22.000Z
import asyncio from decimal import Decimal from typing import ( Any, Dict, Optional, ) from hummingbot.connector.in_flight_order_base import InFlightOrderBase from hummingbot.core.data_type.common import OrderType, TradeType from .altmarkets_constants import Constants s_decimal_0 = Decimal(0) class AltmarketsInFlightOrder(InFlightOrderBase): def __init__(self, client_order_id: str, exchange_order_id: Optional[str], trading_pair: str, order_type: OrderType, trade_type: TradeType, price: Decimal, amount: Decimal, creation_timestamp: float, initial_state: str = "local"): super().__init__( client_order_id, exchange_order_id, trading_pair, order_type, trade_type, price, amount, creation_timestamp, initial_state, ) self.trade_id_set = set() self.cancelled_event = asyncio.Event() @property def is_done(self) -> bool: return self.last_state in Constants.ORDER_STATES['DONE'] @property def is_failure(self) -> bool: return self.last_state in Constants.ORDER_STATES['FAIL'] @property def is_cancelled(self) -> bool: return self.last_state in Constants.ORDER_STATES['CANCEL'] @property def is_local(self) -> bool: return self.last_state == "local" def update_exchange_order_id(self, exchange_id: str): super().update_exchange_order_id(exchange_id) if self.is_local: self.last_state = "submitted" def update_with_order_update(self, order_update: Dict[str, Any]) -> bool: """ Updates the in flight order with trade update (from private/get-order-detail end point) return: True if the order gets updated otherwise False Example Order: { "id": 9401, "market": "rogerbtc", "kind": "ask", "side": "sell", "ord_type": "limit", "price": "0.00000099", "avg_price": "0.00000099", "state": "wait", "origin_volume": "7000.0", "remaining_volume": "2810.1", "executed_volume": "4189.9", "at": 1596481983, "created_at": 1596481983, "updated_at": 1596553643, "trades_count": 272 } """ # Update order execution status self.last_state = order_update["state"] # Update order executed_price = Decimal(str(order_update.get("price") if order_update.get("price") is not None else order_update.get("avg_price", "0"))) self.executed_amount_base = Decimal(str(order_update["executed_volume"])) self.executed_amount_quote = (executed_price * self.executed_amount_base) \ if self.executed_amount_base > s_decimal_0 else s_decimal_0 if self.executed_amount_base <= s_decimal_0: # No trades executed yet. return False trade_id = f"{order_update['id']}-{order_update['updated_at']}" if trade_id in self.trade_id_set: # trade already recorded return False self.trade_id_set.add(trade_id) # Check if trade fee has been sent reported_fee_pct = order_update.get("maker_fee") if reported_fee_pct: self.fee_paid = Decimal(str(reported_fee_pct)) * self.executed_amount_base else: self.fee_paid = order_update.get("trade_fee") * self.executed_amount_base if not self.fee_asset: self.fee_asset = self.quote_asset return True def update_with_trade_update(self, trade_update: Dict[str, Any]) -> bool: """ Updates the in flight order with trade update (from private/get-order-detail end point) return: True if the order gets updated otherwise False Example Trade: { "amount":"1.0", "created_at":1615978645, "id":9618578, "market":"rogerbtc", "order_id":2324774, "price":"0.00000004", "side":"sell", "taker_type":"sell", "total":"0.00000004" } """ self.executed_amount_base = Decimal(str(trade_update.get("amount", "0"))) self.executed_amount_quote = Decimal(str(trade_update.get("total", "0"))) if self.executed_amount_base <= s_decimal_0: # No trades executed yet. return False trade_id = f"{trade_update['order_id']}-{trade_update['created_at']}" if trade_id in self.trade_id_set: # trade already recorded return False trade_update["exchange_trade_id"] = trade_update["id"] self.trade_id_set.add(trade_id) # Check if trade fee has been sent reported_fee_pct = trade_update.get("fee") if reported_fee_pct: self.fee_paid = Decimal(str(reported_fee_pct)) * self.executed_amount_base else: self.fee_paid = trade_update.get("trade_fee") * self.executed_amount_base if not self.fee_asset: self.fee_asset = self.quote_asset return True
36.228188
95
0.589292
0099ebe6a752563f875ebc48c7bacab0636072ed
72,314
py
Python
Dictator_service/auto_commands.py
FurqanKhan1/Dictator
74e29c12a8f92292ab3275661622c0632cdd0a7b
[ "Unlicense" ]
5
2019-03-14T10:17:22.000Z
2019-10-23T14:04:12.000Z
Dictator_service/auto_commands.py
FurqanKhan1/Dictator
74e29c12a8f92292ab3275661622c0632cdd0a7b
[ "Unlicense" ]
null
null
null
Dictator_service/auto_commands.py
FurqanKhan1/Dictator
74e29c12a8f92292ab3275661622c0632cdd0a7b
[ "Unlicense" ]
14
2019-03-14T10:34:02.000Z
2021-10-31T17:34:13.000Z
""" @Author :Furqan Khan @Email :furqankhan08@gmail.com @Date :12/30/2016 Objective : The purpose of this file /module /Class is to actually execute the external scripts for vulnerability assessment and scanning.It runs metasploit modules ,external python ,ruby,bash,shell,java class files and some perl as well as NSE scripts.This file is invoked from driver_meta.py and it invokes appropriate method at 1 time depending upon the type of service and checks to be carried. Thus there are various method catagories like : (1) Single line :For the scripts that only require to be invoked and they return data after completion of execution . (2) Interactive :This catagory of methods create a virtual terminal to execute the commands in interactive manner ,where the next input given to virtual terminal depends upon the output produced from the preceeding command. (3) Sniffing :This catagory generates triffic sniffing files for the service /port being testes (4) Metasploit :This catagory will invoke the metasploit modules and would execute them and collect data from the execution (5) Single line timeout :THis catagory comes with a timeout parameter which will wait for external script to finish its execution for some specified time """ import shlex import sys #import msfrpc import time import pyshark import pexpect from subprocess import Popen, PIPE, STDOUT import commands import urllib2 import requests import threading import subprocess import psutil import logging import logging.handlers import threading import Auto_logger import IPexploits import time import unicodedata import chardet import os import json """ Objective : The following class Commands has got all the catagories of methods discussed above """ class Commands: """ Objective : The following class Commands has got all the catagories of methods discussed above """ def __init__(self): print "Inside INIT" self.project_id=004 self.method_id="INIT" self.command_id=None self.Log_file=str(self.project_id) +str("_Log_file") self.lock = threading.Lock() self.logger =None self.logger_info=None self.Log_file_info=None self.exploit_results=None self.con=None self.cursor=None self.Auto_logger=Auto_logger.Logger() self.IPexploitObj=IPexploits.IPexploits() self.current_record_id=None self.general_op="" self.current_host='' self.current_port='' self.data_path='' self.general_op="" self.Kill=False def set_log_file(self): """ Objective : When invoked from the GUI the whole code executes in the background and in order to track the details of execution we log the debugging messages that help us track the execution flow.This method initilizes the logger class and sets a logger file for the current project (scanning phase only) """ #print "Inside set Log file " self.Log_file=str(self.project_id) +str("_Log_file") self.Log_file_path = os.path.join(self.data_path, self.Log_file) #self.Log_file_info=str(self.project_id) +str("_Log_file_info") print "Log file is : " +str(self.Log_file) self.logger=self.Auto_logger.configureLogger(self.method_id,self.Log_file_path) #self.logger_info=self.Auto_logger.configureLoggerInfo(self.method_id,self.Log_file_info) time.sleep(3) def init_connection(self): """ Objective : This method would initialize the database connection """ try: self.con=MySQLdb.connect("localhost","<USER>","<PASSWORD>","nmapscan") self.cursor = self.con.cursor() except Exception, e: self.print_Error("EXception in connection-->"+str(e)) def print_Log(self,message): """ Objective : This method would log the command id and message (obtained results) to the log file """ message="Command Logger --->Command id --> "+str(self.command_id) +" Message --> :" +str(message) try: self.lock.acquire() self.logger.debug(message) self.lock.release() except Exception ,e: self.lock.acquire() self.logger.critical(message +"--Exception : --"+str(e)) self.lock.release() print "Log exception :"+str(e) print message+"\n" def print_Error(self,message): """ Objective : This method log any exception or error to the logger with the flag info as ERROR """ print "Error Logger Command fro file -->"+str(self.Log_file) #self.logger=self.Auto_logger.configureLogger(self.method_id,self.Log_file) message="Error -->Command id --> "+str(self.command_id) +" Message --> :" +str(message) print message try: self.lock.acquire() self.logger.error(message) self.lock.release() except Exception ,e: self.lock.acquire() self.logger.error(message +"--Exception : --"+str(e)) self.lock.release() def print_Log_info(self,message): """ Objective : This method would log the execution flow to the different log file (info) .The purpose of this log is to do debugging and track execution flow of commands """ message="Command id --> "+str(self.command_id) +" Message --> :" +str(message) message=message.replace("\n","") message=message.replace("\\n","") """print "-----------------------------------------------------------------------------------------" print "Logger Info for file -->"+str(self.Log_file_info) #print "Inside print log !!--Log file is "+str(self.Log_file) print "Message is " +str(message) print "-----------------------------------------------------------------------------------------" """ #self.logger_info=self.Auto_logger.configureLoggerInfo(self.method_id,self.Log_file_info) #print "\n\n\n" #print "logger is -->"+str(self.logger) try: self.lock.acquire() self.logger_info.debug(message) self.lock.release() except Exception ,e: self.lock.acquire() self.logger_info.critical(message +"--Exception : --"+str(e)) self.lock.release() print "Log exception :"+str(e) print message+"\n" def print_Error_info(self,message): """ Objective : This method would log errors pertaining to execution flow with flag set as 'Error' """ #self.logger_info=self.Auto_logger.configureLoggerInfo(self.method_id,self.Log_file_info) message="Command id --> "+str(self.command_id) +" Message --> :" +str(message) print message try: self.lock.acquire() self.logger_info.error(message) self.lock.release() except Exception ,e: self.lock.acquire() self.logger_info.error(message +"--Exception : --"+str(e)) self.lock.release() def cleanUp(self): """ Objective : This method would clean up the virtual console """ #a = client.call('console.write', [console_id, "workspace\n"]) #time.sleep(1) #self.print_Log( "\n\n"+str(a)+"--->Written<----\n\n" cleanup = self.client.call('console.destroy',[self.console_id]) time.sleep(1) self.print_Log( "Clean up :"+str(cleanup)) self.print_Log( "Cleanup result: %s" %cleanup['result']) def exit_child(self,child): """ Objective : This method would gracefully exit the msfconsole when all metasploit commands are ececuted """ try: self.print_Log_info("\nExiting from msfconsole !!!\n") self.print_Log("\nExiting from msfconsole !!!\n") child.sendline('exit') time.sleep(2) j=child.expect(['[$/#]',pexpect.EOF,pexpect.TIMEOUT],timeout=60) print "j is "+str(j) if(j==1): self.print_Log("Exited from msfconsole !!!") self.Display_msg(child) else : self.print_Log("\n\nSome Error Occured while Exiting\n\n") self.Display_msg(child) except Exception ,e: self.print_Error_info("\n\nException in Exit Child "+str(e)) self.print_Error("\n\nException in Exit Child "+str(e)) self.Display_msg(child) def SaveDetails(self,commands,result): """ Objective : This method is commonly shared amongst all catagories of methods (singleline ,interactive ,metasploit ,sniffing and etc) which are responsible for invoking the external scripts as well as the metasploit modules .Actually when ever the methods execute the external scripts teh recived data from external scripts is passed on to this method and it saves the findings inside the databse table """ #print "\n\n\n\n" self.print_Log("Saving details :") self.print_Log_info("Saving details :") print "\n\n Here :Commands Executed for Record id -> " +str(self.current_record_id) +" and Command Id : -->"+str(self.command_id )+" and Method id -->"+self.method_id print str(commands) print ("\n\n\n\n") print "\n\nResults for Record id -> " +str(self.current_record_id) +" and Command Id : -->"+str(self.command_id) +" and Method id -->"+self.method_id print str(result) #print str(result) status=1 self.IPexploitObj.logger=self.logger status=self.IPexploitObj.Update(self.project_id,self.current_record_id,self.command_id,commands,result,False) if (status==1): self.print_Log_info( "Details Updated successfully") #self.print_Log( "Details Update Failed") print "Details Updated successfully" else: self.print_Log_info( "Details Update Failed") self.print_Log( "Details Update Failed") print "Details Update Failed" #print str(result)+"\n\n\n" x=1 def custom_meta(self,commands): """ Objective : This method would take the list of commands as aurgument and would invoke metasploit as a subprocess in virtual console and would execute the commands and would collect the resukts and finally would pass the findings to savedetails method to save the results """ try: exploit_result='' commands_launched=[] self.method_id="Custom meta" self.print_Log_info("Inside command_meta") self.print_Log("Inside command_meta") #child=pexpect.spawn("msfconsole") child = pexpect.spawn('msfconsole -q') commands_launched.append('>msfconsole \n') print "Console created " #print str(child) #child = pexpect.spawn(args[0]) i=child.expect(['.*> ',pexpect.EOF,pexpect.TIMEOUT],timeout=480) run=True if (i==0): self.print_Log(str(child.after)) commands_launched.append(str(child.after)) self.print_Log(str(i)) for command in commands: command=command.replace("\n","") child.sendline(command) #commands_launched.append(command+"\n") time.sleep(3) j=child.expect(['.*> ',pexpect.EOF,pexpect.TIMEOUT],timeout=280) if(j==0): self.print_Log(str(child.after)) commands_launched.append(str(child.after)+"\n") continue elif(j==1): self.print_Log("EOF reached-->Not launching the run command") self.Display_msg(child) commands_launched.append(str(child.after)+"\n") run=False break else: self.print_Log("Time out exceeded in child check ->Not launching the run command") self.Display_msg(child) commands_launched.append(str(child.after)+"\n") run=False break elif(i==1): print "Reache1" self.print_Log("EOF reached Outer Expect-->Not launching the run command") run=False self.Display_msg(child) commands_launched.append("EOF->"+str(child.after)+"\n") else: print "Reache2" self.print_Log("Time out exceeded in parent check ->Not launching the run command") run=False self.Display_msg(child) commands_launched.append("Time out exceeded "+str(child.after)+"") if(run==True): print "Reache3" self.print_Log("\n\nEverything Fine till now-->Launching run command\n\n") self.print_Log_info("\nEverything Fine till now-->Launching run command\n") child.sendline('run') #commands_launched.append('>run') time.sleep(3) k=child.expect(['.*>.*',pexpect.EOF,pexpect.TIMEOUT],timeout=1500) time.sleep(2) if(k==0): self.print_Log("\n\nModule Execution completed\n\n") self.print_Log_info("\nModule Execution completed\n") self.Display_msg(child) commands_launched.append(''+str(child.after)+'\n') exploit_result=exploit_result+"Command Executed :"+commands_launched[0] exploit_result="\n"+exploit_result+"\nResult :\n"+str(child.after) #exploit_result=str(child.after) self.print_Log("\n\nNow exiting !!!\n\n") self.exit_child(child) self.print_Log("Closing the child pipe !!!") child.close(force=True) else: self.print_Log("some error occured while running the aux module !!") self.print_Log_info("some error occured while running the aux module !!") self.print_Log_Error("some error occured while running the aux module !!") self.print_Log("The value of expect here is :" +str(k)) self.Display_msg(child) commands_launched.append('<Finished-T/O or EOF>'+str(child.after)+'') exploit_result=exploit_result+"Command Executed :"+commands_launched[0] exploit_result="\n"+exploit_result+"\nResult :\n"+str(child.after) #exploit_result=str(child.after) self.print_Log("\n\nNow exiting !!!\n\n") self.exit_child(child) self.print_Log("Closing the child pipe !!!") child.close(force=True) else: self.print_Log("Run Flag is Not true !!") self.print_Log_info("Run Flag is Not true !!") self.print_Log("Closing the child pipe !!!") child.sendline('exit') child.close(force=True) exploit_result="Command msf console failed to load the console or timeout occured " exploit_result=exploit_result+"Command Executed :"+commands_launched[0] exploit_result="\n"+exploit_result+"\nResult :\n"+commands_launched[len(commands_launched)-1] #self.SaveDetails(''.join(commands_launched),exploit_result) self.SaveDetails(str(commands_launched),exploit_result) self.print_Log_info("Exiting custom_meta !!") except Exception ,e: self.print_Error(str(child.after)) self.print_Error("Custom MetaSploit module has exception :" +str(e)) self.print_Error_info("Custom MetaSploit module has exception :" +str(e)) #self.Display_msg("Closing the child pipe !!!") child.close(force=True) def meta_commands(self,commands): """ Objective : This method is obselete and is not used in final draft of code.Its purpose was to use github version of code for metasploit modules execution ,but due to its unstable nature we adapted our own custom methodology using Python's pexpect """ try: self.print_Log( "Console id is :"+str(self.console_id)) for command in commands: a = self.client.call('console.write', [self.console_id, command]) time.sleep(1) a = self.client.call('console.write', [self.console_id, "run\n"]) time.sleep(5) self.print_Log( str(a)) while True: self.res = self.client.call('console.read',[self.console_id]) if len(self.res['data']) > 1: self.print_Log( "Result :" + self.res['data']) if self.res['busy'] == True: self.print_Log( "Console is busy :") time.sleep(1) continue break except Exception,e: print "Exception meta_commands-->"+str(e) self.print_Error( "EXception Meta "+str(e)) def start_wireshark(self,args): """ Objective : This method would start python version of wireshark called as pyshark for traffic sniffing """ self.print_Log( "\n\nStarting wireshark for 50 sec\n\n") self.print_Log_info( "\n\nStarting wireshark for 50 sec\n\n") try: capture = pyshark.LiveCapture(interface=args[0],bpf_filter=args[1]) capture.sniff(timeout=50)#will mae the pyshark to capture packets for next 50 seconds for packet in capture.sniff_continuously(packet_count=5): self.print_Log( 'Just arrived:'+str( packet)) except Exception ,ee: self.print_Error( "EXception Wireshark-old "+str(ee)) self.print_Error_info( "EXception Wireshark-old "+str(ee)) return def Display_msg(self,child): """ Objective : This method would pass the debugging messages to print_Log method to keep track of execution flow """ try: self.print_Log( "Before : \n"+ str(child.before) + "After : \n"+ str(child.after)) except Exception, ee: self.print_Error("Error in Display_msg methos --> : "+str(ee)) self.print_Error_info("Error in Display_msg methos --> : "+str(ee)) def Nfs_Mount_intaractive(self,args): """ Objective : Nfs mount is used for service NFS and this check will attempt to mount directories of remote system to local machine .The method is interacive and is customizd only for this purpose. Todo : For now we are hard coding-->assuming root permission -->later try to parse the directories which have permission and mount them only.It assumes /temp/ directory is created already """ try: #For now we are hard coding-->assuming root permission -->later try to parse the directories which have permission and mount them only.It assumes /temp/ directory is created already self.print_Log( "\n\nStarting Mount all retive\n\n") self.print_Log_info( "\n\nStarting Mount all retive\n\n") print ("Launching command--> "+str(args[0])) commands_executed=[] commands_executed.append(">"+str(args[0])+"\n") exploit_result='' child = pexpect.spawn(args[0]) print "Launched" i=child.expect([pexpect.TIMEOUT, '[#\$]','.*access denied.*',pexpect.EOF],timeout=25) if ((i==1)or(i==3)): print "here" self.print_Log(str(child.after)) commands_executed.append(">"+str(child.after)) self.print_Log( str(i)) for counter in range (1,len(args)): child.sendline(args[counter]) commands_executed.append(args[counter]+"\n") time.sleep(2) j=child.expect([pexpect.TIMEOUT, '[#\$] ',pexpect.EOF],timeout=15) time.sleep(2) commands_executed.append(str(child.after)) if((j==1)or (j==2)): self.print_Log(str(child.after)) continue else : self.print_Log("Some Error occured--During command launching") self.print_Log_info("Some Error occured--During command launching") self.Display_msg(child) break exploit_result="Command Executed :"+commands_executed[0] exploit_result="\n"+exploit_result+"Result:\n"+commands_executed[len(commands_executed)-1] self.print_Log("Closing Child now !!") self.print_Log_info("Closing Child now !!") child.close(force=True) elif (i==2): commands_executed.append(str(child.after)) exploit_result="Command Executed :"+commands_executed[0] exploit_result="\n"+exploit_result+"Result:\n"+commands_executed[len(commands_executed)-1] self.print_Log("Closing Child now !!") self.print_Log_info("Closing Child now !!") child.close(force=True) else: self.print_Log("Either timeout or End of file "+str(i)) self.print_Log_info("Either timeout or End of file "+str(i)) self.print_Log("Closing Child now !!") exploit_result="Command Executed :"+commands_executed[0] exploit_result="\n"+exploit_result+"\nResult:\n"+commands_executed[len(commands_executed)-1] child.close(force=True) #self.SaveDetails(''.join(commands_executed),exploit_result) self.SaveDetails(str(commands_executed),exploit_result) self.print_Log_info("Exiting mathos Nfs interactive now !!") except Exception,e: child.close(force=True) self.print_Error("Exception in mount interactive "+str(e)) self.print_Error_info("Exception in mount interactive "+str(e)) #self.print_Error("Closing Child now !!") def ftp_interactive(self,args): #Note never execute it as a sinle line command as the console gets stuck """ Objective : The purpose of this method is to check weather anonymous login is allowed on ftp service on the given remote host.Altough the same task could be achived by passing appropriate aurguments to General_interactive catagory of methos ,but this method was developed before developemt of General_interactive and thus is customized only for anonymous FTP check using interactive mode with virtual console """ try : commands_executed=[] exploit_result='' self.method_id="Ftp_interactive ()" self.print_Log( "\n\nStarting FTP Login --Anonmous\n\n") self.print_Log_info( "\n\nStarting FTP Login --Anonmous\n\n") child = pexpect.spawn(args[0]) i=child.expect(['Permission denied', 'Name .*:','.* Connection refused',pexpect.TIMEOUT, '[#\$] '],timeout=25) commands_executed.append(args[0]+"\n") commands_executed.append(str(child.after)+"\n") if (i==1): self.print_Log(str(child.before) +" " +str(child.after)) commands_executed.append(str(child.after)) #self.print_Log( str(i)) child.sendline('anonymous') commands_executed.append('anonymous'+"\n") time.sleep(3) j=child.expect(['.*Password:',pexpect.TIMEOUT],timeout=25) if(j==0): self.print_Log( "Before : "+ str(child.before) + "After : "+ str(child.after)) commands_executed.append(str(child.after)+"\n") child.sendline('noah@example.com') time.sleep(3) commands_executed.append('noah@example.com'+"\n") k=child.expect(['.*ftp> ',pexpect.TIMEOUT],15) commands_executed.append(str(child.after)+"\n") if(k==0): exploit_result="Login SuccesFul --> "+str(child.after) self.print_Log( "Login Successful") self.print_Log_info( "Login Successful") self.print_Log( "Before : "+ str(child.before) + "After : "+ str(child.after)) else: exploit_result="Login Not SuccesFul --> "+str(child.after) self.print_Log( "Login Not Successful") self.print_Log_info( "Login Not Successful") self.Display_msg(child) else: commands_executed.append(str(child.after)+"\n") self.Display_msg(child) elif ((i==2)or (i==3)): self.print_Log( "Host seems to be down or service is turned off : ") self.print_Log_info( "Host seems to be down or service is turned off- or connection Timed out : ") self.Display_msg(child) elif (i==4): self.print_Log( "Host has very less security as it permits ftp login without any password: ") self.print_Log_info( "Host has very less security as it permits ftp login without any password: ") self.Display_msg(child) else : self.print_Log( "\n\nPermission Denied\n\n") self.print_Log_info( "\n\nPermission Denied\n\n") self.Display_msg(child) self.print_Log("Closing Child now !!") child.close(force=True) exploit_result=exploit_result+"Command Executed :"+commands_executed[0] exploit_result="\n"+exploit_result+"\nResult :\n"+str(child.after) #self.SaveDetails(''.join(commands_executed),exploit_result) self.SaveDetails(str(commands_executed),exploit_result) self.print_Log_info("Exiting method Ftp interactive !!") except Exception,e: self.print_Error("Closing Child now !!") child.close(force=True) self.print_Error( "Exception ftp_intaractive "+str(e)) self.print_Error_info( "Exception ftp_intaractive "+str(e)) def ssh_check_execution(self,child,commands_executed): """This method works in conjuction with ssh_root_login check/ssh_interactive""" exploit_result="" try: print "In here" i=child.expect(['.*Permission denied.*', 'root@.* password:.*','.* Connection refused',pexpect.TIMEOUT,'[#\$]',pexpect.EOF],timeout=15) time.sleep(2) print "got something-->"+str(i) commands_executed.append(str(child.after)+"\n") print "i is -->"+str(i) if ((i==1)): self.print_Log( "Root is expecting a pssword--supplying default password") self.print_Log_info( "Root is expecting a pssword--supplying default password") #self.print_Log( str(i)) child.sendline('root') commands_executed.append('root'+"\n") time.sleep(2) j=child.expect(['root@.* password:.*' ,'[#\$] ','Permission denied'],timeout=15) commands_executed.append(str(child.after)+"\n") #commands_executed.append('root'+"\n") #time.sleep(2) exploit_result=str(child.after)+"\n" if(j==1): self.print_Log( "Login Successful with password root") self.print_Log_info( "Login Successful with password root") self.print_Log( "Before : "+ str(child.before) + "After : "+ str(child.after)) else: #exploit_result ="Before -: "+str(child.before) + "After - :" +str(child.after) self.print_Log("No login with pw root-Cant guess weather root login is enabled.Need to brute force\n" +str(j)) self.print_Log_info("No login with pw root-Cant guess weather root login is enabled.Need to brute force") self.Display_msg(child) elif (i==4): self.print_Log( "Login successful ..Root is set to weak privlages it permits login without password:") self.print_Log_info( "Login successful ..Root is set to weak privlages it permits login without password:") self.Display_msg(child) elif (i==2): self.print_Log( "Connection refused-->Service not running on host") self.print_Log_info( "Connection refused-->Service not running on host") self.Display_msg(child) elif (i==3) or (i==5): self.print_Log( "TimeOut occcured or EOF") self.print_Log_info( "Connection Timed out !!!") self.Display_msg(child) else : self.print_Log( "Permission Denied at inception for root--Good ") self.print_Log_info( "Permission Denied at inception for root--Good ") self.Display_msg(child) #exploit_result ="Before -: "+str(child.before) + "After - :" +str(child.after) exploit_result="Command Executed :"+commands_executed[0]+"\n" exploit_result=exploit_result+"\nResult:\n"+str(commands_executed[len(commands_executed)-1]) self.print_Log("Closing Child now !!") child.close(force=True) #self.SaveDetails(''.join(commands_executed),exploit_result) self.SaveDetails(str(commands_executed),exploit_result) self.print_Log_info("Exiting method ssh interactive!!") except Exception,e: self.print_Error("Closing Child now !!") child.close(force=True) self.print_Error( "Exception ssh_intaractive "+str(e)) self.print_Error_info( "Exception ssh_intaractive "+str(e)) def ssh_interactive(self,args): #Note never execute it as a sinle line command as the console gets stuck """ Objective : The purpose of this method is to check weather root login is allowed on ssh service on the given remote host.Altough the same task could be achived by passing appropriate aurguments to General_interactive catagory of methods ,but this method was developed before developemt of General_interactive and thus is customized only for SSH root login check using interactive mode with virtual console """ try: print "In ssh interactive !!!!!" commands_executed=[] exploit_result="" self.method_id="ssh_interactive()" self.print_Log( "\n\nStarting ssh--INteractive\n\n") self.print_Log_info( "\n\nStarting ssh--INteractive\n\n") child = pexpect.spawn(args[0]) #root@192.168.179.136's password: commands_executed.append(args[0]+"\n") check_list=['.*Permission denied.*', 'root@.* password:.*','.* Connection refused','.*(yes/no).*','[#\$] ',pexpect.TIMEOUT,pexpect.EOF] i=child.expect(['.*Permission denied.*', 'root@.* password:.*','.* Connection refused','.*(yes/no).*',pexpect.TIMEOUT,'[#\$]',pexpect.EOF],timeout=15) print "THe value oof i is "+str(i) if(i==3): print "Hre-yes/no" child.sendline('yes') time.sleep(3) self.ssh_check_execution(child,commands_executed) else: print "here -->other--->" +str(i) self.print_Log_info( "Root is expecting a pssword--supplying default password") #self.print_Log( str(i)) commands_executed.append(str(child.after)+"\n") child.sendline('root') commands_executed.append('root'+"\n") self.ssh_check_execution(child,commands_executed) except Exception,e: self.print_Error("Closing Child now !!") child.close(force=True) self.print_Error( "Exception ssh_intaractive "+str(e)) self.print_Error_info( "Exception ssh_intaractive "+str(e)) def domain_interactive(self,args): """ Objective : The purpose of this method is to check /conduct various checks related to domain server /DNS service like (zone transfers ,guessing subdomains and etc).Altough the same task could be achived by passing appropriate aurguments to General_interactive catagory of methods ,but this method was developed before developemt of General_interactive and thus is customized only for Domain server checks using interactive mode with virtual console """ try: self.method_id="Domain_interactive()" self.print_Log("Launching Domain Interactive ::<--- Command :--->"+str(args[0])) self.print_Log_info("Launching Domain Interactive ::<--- Command :--->"+str(args[0])) child = pexpect.spawn(args[0]) #root@192.168.179.136's password: commands_executed=[] exploits_result='' commands_executed.append(args[0]+"\n") i=child.expect(['.*>.*'],timeout=55)#note > is kept with purposefully here,* is not there as it does something like xx-> time.sleep(2) if (i==0): self.print_Log( "$"+str(args[1])+"\n" ) #self.print_Log( str(i)) self.Display_msg(child) child.sendline(args[1]) #commands_executed.append(args[1]) time.sleep(2) j=child.expect(['Address: .*#.*> ' ,"nslookup: couldn't get.*",".*>.*"],timeout=35) #note this case will work only when the given <host> is in 192.x.x.x notation commands_executed.append(str(child.after)+"\n") if(j==0) or (j==2): #self.print_Log( "Dns lookup Address changed successfully-->"+str(child.before)+str(child.after)) self.Display_msg(child) commands_executed.append(str(child.before) +" " +str(child.after)) child.sendline(str(args[2])) commands_executed.append(args[2]+"\n") time.sleep(2) k=child.expect(['.*>.*' ,".* SERVFAIL",".*no servers could be reached.*"],timeout=20) commands_executed.append(str(child.after)+"\n") exploit_result=str(child.after)+"\n" else: exploit_result=str(child.after)+"\n" self.print_Log("Invalid host address given \n" +str(j)) self.print_Log_info("Invalid host address given \n" +str(args[2])+" J is --> " +str(j)) self.Display_msg(child) exploit_result=exploit_result+"\n\n""Command Executed :"+commands_executed[0]+"\n" exploit_result=exploit_result+"Result:\n"+str(commands_executed[len(commands_executed)-1]) self.print_Log("Closing Child now !!") child.close(force=True) #self.SaveDetails(''.join(commands_executed),exploit_result) self.SaveDetails(str(commands_executed),exploit_result) self.print_Log("Closing Child now !!") child.close(force=True) self.print_Log("Exiting Domain interactive !!") except Exception ,e: self.print_Error( "Exception Domain Intaractive " +str(e)) self.print_Error_info( "Exception Domain Intaractive " +str(e)) self.print_Error(self.Display_msg(child)) self.print_Error("Closing Child now !!") child.close(force=True) def imap_interactive(self,args): """ Objective : The purpose of this method is to check /conduct various checks related to Imap service. To do : Right now teh username and password passed to this module are (msfadmin,msfadmin).Add additional aurguments to the master json file for this service to take username password from master json or name list to brute force login attempt. """ try: commands_executed=[] self.method_id="Imap_interactive" exploit_result='' self.print_Log("Launching Imap Interactive ::Command-->" +str(args[0])) self.print_Log_info("Launching Imap Interactive ::Command-->" +str(args[0])) child = pexpect.spawn(args[0]) #Telnet <IP> 143: Connection refused commands_executed.append(args[0]) i=child.expect(['.*: No route to host', '.* login:','.*: Connection refused', '[#\$] ',pexpect.TIMEOUT],timeout=25) #self.print_Log(str(i)) commands_executed.append(str(child.after)+"\n") if (i==1): self.print_Log( "Telnet is expecting Username -- supplying default Username") self.print_Log_info( "Telnet is expecting Username -- supplying default Username") #self.print_Log( str(i) child.sendline('msfadmin') commands_executed.append('msfadmin'+"\n") time.sleep(2) j=child.expect(['.*Password:' ,'[#\$] ','Last login',pexpect.TIMEOUT],timeout=15) commands_executed.append(str(child.after)) if(j==0): self.print_Log( "Telnet is expecting Password-- supplying default Password") self.print_Log_info( "Telnet is expecting Password-- supplying default Password") child.sendline('msfadmin') commands_executed.append('msfadmin'+"\n") time.sleep(2) k=child.expect(['.* login:' ,'[#\$] ','Last login:',pexpect.TIMEOUT],timeout=15) commands_executed.append(str(child.after)+"\n") if(k==2): self.print_Log( "Login Successful with password root "+str(k)) self.print_Log_info( "Login Successful with password root "+str(k)) self.Display_msg(child) else: self.print_Log( "Login Failed with default username and password "+str(k)) self.print_Log_info( "Login Failed with default username and password "+str(k)) self.Display_msg(child) else: self.print_Log( "Weak login -->Only default username was sufficient -- \n" +str(j) ) self.print_Log_info( "Weak login -->Only default username was sufficient -- \n" +str(j) ) self.Display_msg(child) elif(i==0): self.print_Log( "There is no route to host--The host is not up and running !!") self.print_Log_info( "There is no route to host--The host is not up and running !!") self.Display_msg(child) elif(i==2): self.print_Log( "The remote host has no service running on the supplied port :"+str(args[0])) self.print_Log_info( "The remote host has no service running on the supplied port :"+str(args[0])) self.Display_msg(child) else: self.print_Log( "Week security !!--Telnet can be logged in without any username and password -command :"+str(args[0])) self.print_Log_info( "Week security !!--Telnet can be logged in without any username and password -command :"+str(args[0])) exploit_result="Command Executed :"+commands_executed[0]+"\n" exploit_result=exploit_result+"\nResult:\n"+str(commands_executed[len(commands_executed)-1]) self.print_Log("Closing Child now !!") child.close(force=True) #self.SaveDetails(''.join(commands_executed),exploit_result) self.SaveDetails(str(commands_executed),exploit_result) self.print_Log("Closing Child now !!") self.print_Log_info("Exiting Imap interactive!!") child.close(force=True) except Exception ,e: # self.print_Error( "Exception Imap_intaractive " +str(e)) self.print_Error_info( "Exception Imap_intaractive " +str(e)) self.print_Error(self.Display_msg(child)) self.print_Error("Closing Child now !!") child.close(force=True) def time_out_command(self,arg,timeout): """ Objective : The purpose of this method is to accomdate execution of all scripts that can be invoked with a single command along with host and port info and do not require any further interaction with the user.The timeout parameter asks the controllor thread to wait for "n" units of time and even then if the external script does not finish execution then abort the execution of external script such that other services and scriptsare not starved for execution. """ try: print "Command is---> ::" +str(cmd) print "hello world !!1" #cmd ="nslookup google.com" commands_executed=[] exploit_result='' self.print_Log( 'Thread started --with command '+str(cmd)) self.print_Log_info( 'Thread started --with command '+str(cmd)) commands_executed.append(cmd+"\n") self.process=subprocess.Popen(cmd,shell=True,stderr=subprocess.PIPE,stdout=subprocess.PIPE)#best way to implement -->gives o/p in variable (output, err)=self.process.communicate() #seunicode characters.sends ouput continuesly.Thus we may not know in which chunk of o/p we would recieve unicode character.Its better to convert all output into utf-8 and then back to ascii with ignoring special characters/unicode characters result = chardet.detect(output) charenc = result['encoding'] print "Encoding used is --> : "+str(charenc) if (charenc is not None): output=output.decode(charenc).encode('ascii','replace') err=err.decode(charenc).encode('ascii','replace') self.print_Log_info( 'Thread finished') self.general_op=(str(output)+"\n"+str(err)+"\n") #return (str(output)+"\n"+str(err)+"\n") except Exception ,ee: self.print_Error("Exception in gneral :"+str(ee)) self.general_op= "0" +str(ee) def threadControllor(self,cmd,timeout=100): """ Objective : The purpose of this method is to start a new thread which will inturn launch a new subprocess and that subprocess will actually execute the external script.Further more the thread will wait for the subprocess to complete its execution for the time specified in timeout parameter (in secconds) ,and if teh sub process dors not finish within that time ,the thread kills the subprocess and recursively kills all its children processes(external scripts) """ thread = threading.Thread(target=self.execute_singleLine,args=(cmd,True)) thread.start() timeout=100 timeout_=int(timeout) print "Joined and waiting !!!\n\n" thread.join(timeout_) print "Timeout\n\n\n" #self.method_id="Dns_Ferice_Check()" if thread.is_alive(): self.print_Log( 'Terminating process') self.print_Log_info( 'Terminating process') try: process = psutil.Process(self.process.pid) for proc in process.children(recursive=True): self.print_Log_info( "Killing Process with id -->"+str(proc)) try: proc.kill() except Exception ,ew: self.print_Error("Exception while killing :"+str(ew)) self.print_Log_info("Killed Process with id -->"+str(proc)) try: process = psutil.Process(self.process.pid) if process: self.process.kill() thread.join(60) #commands_executed.append('Process killed--.timeout') except: self.print_Log("Parent Process already KIlled") except Exception ,ee: self.print_Error("Exception caught in th-controllor"+str(ee)) def Dns_FierceCheck(self,args):#Aur are send seperately cuz we need to do a reverse dns lookup also """ Objective : The purpose of this method is to check /conduct various checks related to DNS. It does dns fierce check for the host and also then for reverse dns of the host. """ try: commands_executed=[] exploit_result='' self.method_id="Dns_Ferice_Check()" self.print_Log("Launching FierceCheck with the given host --> "+str(args[1])) self.print_Log_info("Launching FierceCheck with the given host --> "+str(args[1])) cmd=str(args[0])+str(args[1])+str(args[2]) print "command is " +cmd commands_executed.append(cmd+"\n") self.threadControllor(cmd,100) time.sleep(50) print "Not executed till thread is killed" #p = commands.getoutput(cmd) p=self.general_op print "Output ### is -->" +str(p)+"\n\n\n" self.print_Log(str(p)) commands_executed.append(str(p) +"\n") host=self.getReverseDns(str(args[1])) self.method_id="Dns_Ferice_Check()" commands_executed.append("Result --> "+str(host)) if(host!=-1): self.print_Log("Launching reverse DNS FierceCheck") self.print_Log_info("Launching reverse DNS FierceCheck") cmd=str(args[0])+str(host)+str(args[2]) commands_executed.append(cmd) self.threadControllor(cmd,100) p=self.general_op #p = commands.getoutput(cmd) commands_executed.append(str(p)) self.print_Log( str(p)) else: self.print_Log("There is no reverse dns resolution for ip :"+args[1]) self.print_Log_info("There is no reverse dns resolution for ip :"+args[1]) commands_executed.append("No reverse dns for ip -->" +args[1]) exploit_result="Command Executed :"+commands_executed[0]+"\n" exploit_result=exploit_result+"\nResult:\n"+str(commands_executed[len(commands_executed)-1]) self.SaveDetails(str(commands_executed),exploit_result) self.print_Log_info("Exiting Dns_Ferice_check()") except Exception ,e: self.print_Error("Exception in Dns_FierceCheck "+str(e)) self.print_Error_info("Exception in Dns_FierceCheck "+str(e)) def Dns_ReconCheck(self,args): """ Objective : The purpose of this method is to check /conduct various checks related to DNS. It does dns_recon check for the host and also then for reverse dns of the host. """ try: commands_executed=[] exploit_results='' host=str(args[0]) self.method_id="DNS_Recon_check()" self.print_Log("In Dns_recon check") self.print_Log_info("In Dns_recon check") commands_executed.append("Dns check : "+str(args[0])) rev_host=self.getReverseDns(host) commands_executed.append("Res:"+str(rev_host)) print "Length of args : "+str(len(args)) for i in range (1,len(args)): #print args[i] if (("<reversehost>" in args[i])): self.print_Log_info( "Comamnd to be launched -->" +str(args[i])) self.print_Log( "Comamnd to be launched -->" +str(args[i])) if((rev_host !=-1)): cmd=args[i].replace("<reversehost>",rev_host) commands_executed.append(cmd+"\n") print "Updated command --> " +str(cmd) p = commands.getoutput(cmd) commands_executed.append(str(p)+"\n") self.print_Log( str(p)+"\n\n") else: cmd=args[i] commands_executed.append(cmd+"\n") self.print_Log("Launching Command --> :"+str(cmd)) p = commands.getoutput(cmd) commands_executed.append(str(p)+"\n") self.print_Log( str(p)+"\n\n") exploit_result="Command Executed :"+commands_executed[0]+"\n" exploit_result=exploit_result+"\nResult :\n"+str(commands_executed[len(commands_executed)-1]) #self.SaveDetails(''.join(commands_executed),exploit_result) self.SaveDetails(str(commands_executed),exploit_result) self.print_Log_info("Exiting Dns_recon check") # except Exception ,e: #child.close(force=True) self.print_Error("Exception dns recon " +str(e)) self.print_Error_info("Exception dns recon " +str(e)) #.print_Error("Closing Child now !!") def start_sniffing(self,interface,timeout): """ Objective : The purpose of this method is to sniff network packets for various services using terminal version of wireshark called as Tshark.This method would start the sniffer on given interface. Todo: Right now the interface name is hardcoded to 'eth0' ,add additional aurguments to master json to accomdate this flexibility """ try: self.print_Log("IN Start_sniffing() method") self.print_Log_info("IN Start_sniffing() method") cmd="tshark -f 'port "+ str(self.current_port) +" and host "+ str(self.current_host) + "' -i "+str(interface)+" -a duration:"+str(timeout)+" -w "+ os.path.join(self.data_path,str(self.project_id)+"_"+str(self.current_host)+"_"+str(self.current_port)+"_capture-output.pcap") commands_executed=[] exploit_result='' commands_executed.append(cmd+"\n") self.print_Log("sniffing command is --> "+str(cmd)) self.process_sniff=subprocess.Popen(cmd,shell=True,stderr=subprocess.PIPE,stdout=subprocess.PIPE) (output, err)=self.process_sniff.communicate() commands_executed.append(str(output)+"\n"+str(err)+"\n") #commands_executed.append() exploit_result="Command Executed :"+commands_executed[0]+"\n" exploit_result=exploit_result+"\nResult:\n"+str(commands_executed[len(commands_executed)-1]) #self.SaveDetails(''.join(commands_executed),exploit_result) print "output is " +str(output) + "Error is " +str(err) self.print_Log_info("Exiting Start_sniffing() method") except Exception ,e: self.print_Log("Exception while sniffing !!"+str(e)) self.print_Log_info("Exception while sniffing !!"+str(e)) def execute_singleLine(self,cmd,result_=False,grep_commands=None):#A good thing is that even when a process is killed the thread resumes and details are saved """ Objective : The purpose of this method is to execute scripts that can be invoked by single line command and no timeout parameter is used here. """ try: print "Command is---> ::" +str(cmd) print "hello world !!1" #cmd ="nslookup google.com" commands_executed=[] exploit_result='' self.print_Log( 'Thread started --with command '+str(cmd)) self.print_Log_info( 'Thread started --with command '+str(cmd)) commands_executed.append(cmd+"") polling_elements=[] elements={} output='' file_path = os.path.join(os.path.dirname(os.path.realpath(__file__)) ,"polling_TC.json") with open(file_path,"r+") as f: elements=json.loads(f.read()) e=elements["entries"] for item in e: polling_elements.append(item) print "Entries Read :" +str(polling_elements) if self.command_id in polling_elements: out_file=open(str(self.project_id)+"_"+str(self.command_id)+"_output.txt","w") err_file=open(str(self.project_id)+"_"+str(self.command_id)+"_error.txt","w") in_file=open(str(self.project_id)+"_"+str(self.command_id)+"_input.txt","w") in_file.write('n') self.process=subprocess.Popen(cmd,shell=True,stderr=err_file,stdout=out_file,stdin=in_file) err='' try: (output, err)=self.process.communicate() out_file.close() err_file.close() in_file.close() f=open(str(self.project_id)+"_"+str(self.command_id)+"_output.txt","r") e=open(str(self.project_id)+"_"+str(self.command_id)+"_error.txt","r") output=f.read() err=e.read() f.close() e.close() os.remove(str(self.project_id)+"_"+str(self.command_id)+"_error.txt") os.remove(str(self.project_id)+"_"+str(self.command_id)+"_output.txt") os.remove(str(self.project_id)+"_"+str(self.command_id)+"_input.txt") if self.Kill: self.Kill=False err=err+"Killed@" except Exception ,exx: if self.Kill: self.Kill=False err=err+"Killed@" else: self.process=subprocess.Popen(cmd,shell=True,stderr=subprocess.STDOUT,stdout=subprocess.PIPE)#best way to implement -->gives o/p in variable (output, err)=self.process.communicate() #seunicode characters.sends ouput continuesly.Thus we may not know in which chunk of o/p we would recieve unicode character.Its better to convert all output into utf-8 and then back to ascii with ignoring special characters/unicode characters result = chardet.detect(output) charenc = result['encoding'] #print "Encoding used is --> : "+str(charenc) if (charenc is not None): output=output.decode(charenc).encode('ascii','replace') if err is not None: err=err.decode(charenc).encode('ascii','replace') else: err='' if self.Kill: self.Kill=False err=err+"Killed@" commands_executed.append(str(output)+"\n"+str(err)+"\n") parent_output=str(output) exploit_result="Command Executed :"+commands_executed[0]+"\n" exploit_result=exploit_result+"\nResult"+str(commands_executed[len(commands_executed)-1]) commands_executed[len(commands_executed)-1]="\nEnd" self.print_Log( 'Thread finished') self.print_Log_info( 'Thread finished') if(result_==False): #print "Execution result : "+str(exploit_result) #print "Hello" self.SaveDetails((str(commands_executed)),exploit_result) var=0 if grep_commands !=None : for dic in grep_commands: if var <1: #var =1 try:#for kk ,vv in dic.iteritems(): #var=1 kk=dic["id"] vv=dic["grep_string"] commands_executed=[] self.command_id=kk command=cmd +" | "+ str(vv) commands_executed.append(command+"\n") to_execute="echo "+"'"+str(parent_output) +"'" +"|" +str(vv) split_output=parent_output.split("\n") counter_var=0 result="None" output='' for op in split_output: if vv in op: #print "Found at counter val :"+str(counter_var) output=op after_val=int(dic["after"]) before_val=int(dic["before"]) grep_before='' if before_val !=0: before_counter=counter_var-before_val #print "Before counter is : "+str(before_counter) for i in range(before_counter,counter_var): grep_before=grep_before +"\n"+split_output[i] grep_after='' if after_val !=0: after_counter=counter_var+after_val for i in range(counter_var +1 ,after_counter): grep_after=grep_after +"\n"+split_output[i] output=grep_before +"\n"+ output +"\n"+ grep_after break counter_var=counter_var + 1 result=chardet.detect(output) charenc = result['encoding'] if (charenc is not None): output=output.decode(charenc).encode('ascii','replace') if err is not None: err=err.decode(charenc).encode('ascii','replace') else: err='' if self.Kill: self.Kill=False err=err+"Killed@" if err==None: err="" commands_executed.append(str(output)+"\n"+str(err)+"\n") exploit_result="Command Executed :"+commands_executed[0]+"\n" exploit_result=exploit_result+"\nResult\n"+str(commands_executed[len(commands_executed)-1]) commands_executed[len(commands_executed)-1]="\nEnd" self.SaveDetails((str(commands_executed)),exploit_result) except Exception ,exc: print "INternal Exception " +str(exc) self.print_Error( "Inner Exception - " +str(exc)) self.print_Error_info( "Inner Exception" +str(exc)) else: self.general_op=(str(output)+"\n"+str(err)+"\n") #return str(str(output)+"\n"+str(err)+"\n") except Exception ,e : print "EXception " +str(e) self.print_Error( "Exception in thread " +str(e)) self.print_Error_info( "Exception in thread " +str(e)) def test_ssl(self,args): """ Objective : The purpose of this method is to execute test_ssl.py script .The script detects various ciphers used and is only customized for this purpose.It could have not been accomdated in General_interactive catagory and thus we had to write custom code for this """ try: self.method_id="Test_ssl" self.print_Log_info("Starting Test ssl") cmd=args[1] to=args[0] print( 'Thread started --with command '+str(cmd)) commands_executed=[] exploit_result='' commands_executed.append(cmd+"\n") child = pexpect.spawn(cmd) i=child.expect(['.*Proceed ?.*','.* Unable to open a socket to .*',pexpect.TIMEOUT,pexpect.EOF],timeout=int(to)) if (i==0): print "\n\nReached at here"+str(child.after) child.sendline('yes') #commands_executed.append('yes') j=child.expect(['.*Proceed ?.*','.* Unable to open a socket to .*',pexpect.TIMEOUT,pexpect.EOF],timeout=int(to)) print "J is --" +str(j)+"\n\n\n\n"+str(child.before)+" "+str(child.after)+"\n\n\n\n\n" commands_executed.append(str(child.before)+str(child.after)) if(i==2): commands_executed.append(str(child.after)+"Time out -It seems host is down") if(i==3): commands_executed.append(str(child.before)+str(child.after)+"End of file -") exploit_result="Command Executed :"+commands_executed[0]+"\n" exploit_result=exploit_result+"\nResult\n"+str(commands_executed[len(commands_executed)-1]) self.SaveDetails(str(commands_executed),exploit_result) self.print_Log_info("Stopping Test ssl") child.close(force=True) except Exception ,e : self.print_Error("Exception general interactive " +str(e)) self.print_Error_info("Exception general interactive " +str(e)) self.print_Error("Closing Child now !!") child.close(force=True) def general_interactive_special_char(self,args): """ Objective : The purpose of this method is to execute teh interactive scripts or kali tools which return various special charactes which need to be decoded first to interpret meaning from them before passing the next command of interaction """ try: self.method_id="general_interactive_special_char()" self.print_Log("Starting Special char-Interactive Session with command --> "+str(args[1]) +" and timeout " +str(args[0])) cmd=args[1] timeout=args[0] child=pexpect.spawn(cmd) commands_executed=[] commands_executed.append(cmd+"\n") exploit_result='' self.print_Log_info("Starting Special char-Interactive Session with command --> "+str(args[1]) +" and timeout " +str(args[0])) for i in range(2,len(args),2): #print "Commands are --" +str(args[i]) + " " +str(args[i+1]) #child.sendline(args[i]) #time.sleep(2) arg_list=[] check_list=[] #<<<<<<< HEAD arg_list=list(args[i]) #======= #arg_list=args[i] #>>>>>>> b6b8e9ee72399e3d683c7808a85d7f1c8ce3cbf6 check_list=arg_list.pop(0).split(',') count=len(arg_list)-1 arg_list.append(pexpect.TIMEOUT) check_list.append(str(count+1)) arg_list.append(pexpect.EOF) check_list.append(str(count+2)) self.print_Log("Arg list is --> "+str(arg_list)) commands_executed.append(str(arg_list)) self.print_Log("check list is --> "+str(check_list)) print "Waiting for 60 sec" #<<<<<<< HEAD j=child.expect(arg_list,120) #======= #j=child.expect(arg_list,60) #>>>>>>> b6b8e9ee72399e3d683c7808a85d7f1c8ce3cbf6 print "The value of j is :"+str(j) print str(child.after)+"\n\n"+str(child.before) #commands_executed.append(str(child.after)+"\n") commands_executed.append("\n"+str(child.before)+"\n"+str(child.after)) time.sleep(2) print "J is "+str(j) +"\n and i is " +str(i) if(str(j) in check_list): self.print_Log("Before :"+str(child.before) + "\n" + "After : "+str(child.after)+" j is "+str(j) ) if((i+1)<len(args)): # i can never be == len (args) as i is an even number and len args wil always be odd child.send(args[i+1]) child.send('\r') commands_executed.append(args[i+1]+"\n") self.print_Log("Just sent command --> "+str(args[i+1])) time.sleep(2) continue; else: self.print_Log("Results not as expected --> see aurguments " +str(j) +"\n"+str(child.before) + " " + str(child.after)) self.print_Log_info("Results not as expected --> see aurguments ") break #self.print_Log("Closing Child !") exploit_result="Command Executed :"+commands_executed[0]+"\n" exploit_result=exploit_result+"\nResult:\n"+str(commands_executed[len(commands_executed)-1]) #self.SaveDetails(''.join(commands_executed),exploit_result) self.SaveDetails(str(commands_executed),exploit_result) self.print_Log("Before : "+str(child.before)+"After : "+str(child.after)) self.print_Log("Closing Child now !!") child.sendcontrol('z') child.sendcontrol('c') child.close(force=True) self.print_Log_info("Exiting general Interactive with special char()") except Exception ,e: self.print_Error("Exception general interactive " +str(e)) self.print_Error_info("Exception general interactive " +str(e)) self.print_Error("Closing Child now !!") child.close(force=True) def general_interactive(self,args): """ Objective : This is a generic and important method and the purpose of this method is to accomdate most of the interactive commands /tools that require user interaction.It automates the whole process and there are various scripts that are executed using this method by passing appripriate script aurguments to this method. """ try: print "Inside general interactive" self.method_id="General_Interactive()" self.print_Log("Starting Interactive Session with command --> "+str(args[1]) +" and timeout " +str(args[0])) self.print_Log_info("Starting Interactive Session with command --> "+str(args[1]) +" and timeout " +str(args[0])) cmd=args[1] timeout=args[0] child=pexpect.spawn(cmd) commands_executed=[] commands_executed.append(cmd+"\n") exploit_result='' print "here" for i in range(2,len(args),2): #print "Commands are --" +str(args[i]) + " " +str(args[i+1]) #child.sendline(args[i]) #time.sleep(2) arg_list=[] check_list=[] #<<<<<<< HEAD arg_list=list(args[i]) #print "Initial arg list is ;"+str(arg_list) check_list=arg_list.pop(0).split(',') #print "Initial check list is :::: " +str(check_list) #======= #arg_list=args[i] #check_list=arg_list.pop(0).split(',') #>>>>>>> b6b8e9ee72399e3d683c7808a85d7f1c8ce3cbf6 count=len(arg_list)-1 arg_list.append(pexpect.TIMEOUT) check_list.append(str(count+1)) arg_list.append(pexpect.EOF) check_list.append(str(count+2)) self.print_Log("Arg list is --> "+str(arg_list)) #<<<<<<< HEAD #commands_executed.append("\nThe console would produce a pattern similar to following :\n "+str(arg_list)+"\n") self.print_Log("check list is --> "+str(check_list)) print "Waiting for 60 sec" j=child.expect(arg_list,120) commands_executed.append(str(str(child.before)+"\n\nConsole is Now expecting :"+str(arg_list[j])+"\n\n\nActual Output by console \n:"+str(child.after)+"\n\n").replace("<class 'pexpect.EOF'>","Console Ended").replace("<class 'pexpect.exceptions.TIMEOUT'>","Time out").replace("<class 'pexpect.exceptions.EOF'>","Console Ended"))# #======= #commands_executed.append("\nThe console would produce a pattern similar to following :\n "+str(arg_list)+"\n") #self.print_Log("check list is --> "+str(check_list)) #print "Waiting for 60 sec" #j=child.expect(arg_list,120) #commands_executed.append(str("\nThe index of item that console produced is :"+str(j)+"\n\n"+str(child.before)+"\n:"+str(child.after)+"\n\n").replace("<class 'pexpect.EOF'>","Console Ended").replace("<class 'pexpect.TIMEOUT'>","Time out")) #>>>>>>> b6b8e9ee72399e3d683c7808a85d7f1c8ce3cbf6 time.sleep(4) print "J is "+str(j) +"\n and i is " +str(i) if(str(j) in check_list): self.print_Log("Before :"+str(child.before) + "\n" + "After : "+str(child.after)+" j is "+str(j) ) if((i+1)<len(args)): # i can never be == len (args) as i is an even number and len args wil always be odd child.sendline(args[i+1]) #<<<<<<< HEAD commands_executed.append("Writing on console : "+args[i+1]+"\n") #======= #commands_executed.append(args[i+1]+"\n") #>>>>>>> b6b8e9ee72399e3d683c7808a85d7f1c8ce3cbf6 self.print_Log("Just sent command --> "+str(args[i+1])) time.sleep(2) continue; else: #<<<<<<< HEAD self.print_Log("Results not as expected --> see aurguments " +str(j) +str(arg_list[j]) +"\n"+str(child.before) + " " + str(child.after)) #======= #self.print_Log("Results not as expected --> see aurguments " +str(j) +"\n"+str(child.before) + " " + str(child.after)) #>>>>>>> b6b8e9ee72399e3d683c7808a85d7f1c8ce3cbf6 self.print_Log_info("Results not as expected --> see aurguments ") break #self.print_Log("Closing Child !") exploit_result="Command Executed :"+commands_executed[0]+"\n" exploit_result=exploit_result+"\nOutput\n"+str(commands_executed[len(commands_executed)-1]) #self.SaveDetails(''.join(commands_executed),exploit_result) self.SaveDetails(str(commands_executed),exploit_result) self.print_Log("Before : "+str(child.before)+"After : "+str(child.after)) self.print_Log("Closing Child now !!") child.sendcontrol('z') child.sendcontrol('c') child.close(force=True) self.print_Log_info("Exiting General_interactive()") except Exception ,e: self.print_Error("Exception general interactive " +str(e)) self.print_Error_info("Exception general interactive " +str(e)) self.print_Error("Closing Child now !!") child.close(force=True) def generalCommands_Tout_Sniff(self,arg,interactive=False): #note see the methods which inoke other methods """ Objective : The purpose of this method is to start a traffic sniffer and immidiately after that execute the external script which would do vulnerability scanning on given service and the sniffer would capture traffic in the background.The moment the external script would finish execution the method would stop the sniffer.Important point is thet ,the external script is executed with timeout value.If the script does not complete within given time frame both sniffer and external process would be stopped """ try: commands_executed=[] exploit_result='' self.method_id="General_Commands_Timeout_sniff()" self.print_Log("Starting single line + Sniff") self.print_Log_info("Starting single line + Sniff") commands_executed.append('starting sniffing') #<<<<<<< HEAD thread = threading.Thread(target=self.start_sniffing,args=("eth0","200",)) #======= #thread = threading.Thread(target=self.start_sniffing,args=("eth0","100",)) #>>>>>>> b6b8e9ee72399e3d683c7808a85d7f1c8ce3cbf6 thread.start() time.sleep(3) if (interactive==False): self.singleLineCommands_Timeout(arg) #this will act as join here and next line will execute after packets are sent else: self.general_interactive(arg) self.method_id="General_Commands_Timeout_sniff()" if thread.is_alive(): self.print_Log('Terminating Sniffing process') self.print_Log_info('Terminating Sniffing process') try: process = psutil.Process(self.process_sniff.pid) for proc in process.children(recursive=True): print "Killing Process with id -->"+str(proc) try: proc.kill() except Exception ,ew: print "Exception while killing :"+str(ew) #self.process.terminate() try: process = psutil.Process(self.process_sniff.pid) if process: self.process_sniff.kill() thread.join(60) #wait only for 1 minute print "Kill result is --> "+str(self.process_sniff.returncode) except: self.print_Log("Parent process already killed:") commands_executed.append('Finished sniffing-->Details are in pcap file') exploit_result="Command Executed :"+commands_executed[0]+"\n" exploit_result=exploit_result+"\nResult:\n"+str(commands_executed[len(commands_executed)-1]) #self.SaveDetails(''.join(commands_executed),exploit_result) except Exception ,ee: self.print_Error("Exception in killing process --> "+str(self.process_sniff.returncode) +str(ee)) self.print_Error_info( "Exception in killing process --> "+str(self.process_sniff.returncode) +str(ee)) self.print_Log_info("Exiting general_commands_tout_sniff()") except Exception ,e: self.print_Error("Exception in SingleLineCommands_Tout" +str(e)) self.print_Error_info("Exception in SingleLineCommands_Tout" +str(e)) def singleLineCommands_Timeout(self,arg,grep_commands=None): #see in this case its not necessaer to update result since it would be uodated by the other mrth """ Objective : The purpose of this method is to execute scripts that can be invoked with single line command and it internally invokes the earlier discussed single_line command method. """ self.method_id="Execute_Single_line_timeout()" self.print_Log("In method SingleLineCommands_Timeout()") self.print_Log_info("In method SingleLineCommands_Timeout()") commands_executed=[] commands_executed.append(arg[1]) if grep_commands ==None: thread = threading.Thread(target=self.execute_singleLine,args=(arg[1],)) else: print "In else with grep as true " thread = threading.Thread(target=self.execute_singleLine,args=(arg[1],False,grep_commands)) thread.start() timeout=int(arg[0]) thread.join(timeout) self.method_id="Execute_Single_line_timeout()" if thread.is_alive(): self.print_Log( 'Terminating process') self.print_Log_info( 'Terminating process') try: process = psutil.Process(self.process.pid) for proc in process.children(recursive=True): self.print_Log_info( "Killing Process with id -->"+str(proc)) try: self.Kill=True proc.kill() time.sleep(1) except Exception ,ew: print "Exception while killing :"+str(ew) self.print_Log_info( "Killed Process with id -->"+str(proc)) #self.process.terminate() try: process = psutil.Process(self.process.pid) if process: self.Kill=True self.process.kill() thread.join(60)#wait for 1 minute ,if we dont set limit here the remaining code would halt commands_executed.append('Process killed--.timeout') except: self.print_Log("Parent Process already KIlled") self.print_Log( "Kill result is --> "+str(self.process.returncode)) self.print_Log_info( "Kill result is --> "+str(self.process.returncode)) exploit_result="Command Executed :"+commands_executed[0]+"\n" exploit_result=exploit_result+"\nResult:\n"+str(commands_executed[len(commands_executed)-1]) #self.SaveDetails(''.join(commands_executed),exploit_result) except Exception ,ee: self.print_Error( "Exception in killing process --> "+str(self.process.returncode) +str(ee)) self.print_Error_info( "Exception in killing process --> "+str(self.process.returncode) +str(ee)) def getHost(self,result): #no need to put results here--its intermediate results """ Objective : The purpose of this method is to parse the output from nslookup and return host from ip. """ index=result.find("name =") if(index !=-1): index=index+6 actual_host=result[index:] actual_host=actual_host.lstrip() index_last=actual_host.find("\n") if(index_last!=-1): actual_host=actual_host.replace("\n","") actual_host=actual_host[:index_last-2] actual_host.rstrip() print "Actual host is "+actual_host return actual_host else: print "Actual host is "+actual_host return actual_host else: print "Name not found !!" print str(result) return -1 def getReverseDns(self,host):#ret again intermediate results """ Objective : The purpose of this method is to use nslookup to transform ip->domain name" """ try: #host='google.com' self.method_id="getReverseDns()" self.print_Log( "Dns reverse lookup") self.print_Log_info( "Dns reverse lookup") commands_executed=[] exploit_result='' self.print_Log_info("Recieved host is : "+str(host)) child = pexpect.spawn("nslookup "+str(host)) commands_executed.append('nslookup ' +str(host)) i=child.expect(['Address: .*',".* server can't find .*",".* name = .*",pexpect.EOF,pexpect.TIMEOUT],timeout=15) commands_executed.append(str(child.after)) self.print_Log(str(i)) if (i==0): self.print_Log( "Reverse dns successful") self.print_Log_info( "Reverse dns successful") self.Display_msg(child) result=str(child.after) index=result.find(":") index=index+1 actual_host=result[index:] actual_host=actual_host.lstrip() self.print_Log("Actual host is "+actual_host) self.print_Log_info("Actual host is "+actual_host) self.print_Log("Closing Child now !!") self.print_Log_info( "Exiting getReverseDns()") child.close(force=True) return actual_host #self.print_Log( str(i) elif (i==2): self.print_Log( "Reverse dns partially successful") self.print_Log_info( "Reverse dns partially successful") self.print_Log_info( "Exiting getReverseDns()") result=str(child.after) actual_host=self.getHost(result) self.print_Log("Closing Child now !!") child.close(force=True) return actual_host elif(i==3): self.print_Log( " (2)-->Reverse dns Timed out") self.print_Log_info( " (2)-->Reverse dns Timed out") result=str(child.before) actual_host=self.getHost(result) self.print_Log_info( "Exiting getReverseDns()") self.print_Log("Closing Child now !!") child.close(force=True) return actual_host else: self.print_Log( "Reverse dns Failed") self.print_Log_info( "Reverse dns Failed") self.print_Log_info( "Exiting getReverseDns()") self.Display_msg(child) self.print_Log("Closing Child now !!") child.close(force=True) return -1 except pexpect.TIMEOUT,e: self.print_Error("Time out exception in pexpect !!"+str(e)) self.print_Error_info("Time out exception in pexpect !!"+str(e)) self.print_Error("Closing Child now !!") child.close(force=True) return -1 #pass except pexpect.EOF,e: self.print_Error("EOF exception in pexpect !!" +str(e)) self.print_Error_info("EOF exception in pexpect !!" +str(e)) self.print_Error("Closing Child now !!") child.close(force=True) return -1 except Exception ,e: self.print_Error("Exception in Reverse Dns !!"+str(e)) self.print_Error_info("Exception in Reverse Dns !!"+str(e)) self.print_Error(self.Display_msg(child)) self.print_Log("Closing Child now !!") child.close(force=True) return -1 def singleLineCommands(self,args): """ Objective : The purpose of this method is to execute scripts that can be invoked with single line command and it internally invokes the earlier discussed single_line command method without timeout. """ try: commands_executed=[] exploit_result='' self.method_id="SingleLineCommands()" self.print_Log( "\nInvoking Single line command -->Title-->" +str(args[0])+"\n") self.print_Log_info( "\nInvoking Single line command -->Title-->" +str(args[0])+"\n") cmd=args[0] commands_executed.append(cmd+"\n") p = commands.getoutput(cmd) commands_executed.append(str(p)) exploit_result="Command Executed :"+commands_executed[0]+"\n" exploit_result=exploit_result+"\nResult\n"+str(commands_executed[len(commands_executed)-1]) #self.SaveDetails(''.join(commands_executed),exploit_result) self.SaveDetails(str(commands_executed),exploit_result) self.print_Log( str(p)) self.print_Log( "\nExiting Single line command -->Title-->" +str(args[0])+"\n") except Exception ,e: self.print_Error( "Exception single Line "+ str(e)) self.print_Error_info( "Exception single Line "+ str(e)) def http_based(self,args): """ Objective : The purpose of this method is to execute http based checks that request external urls using python get request to fetch data. """ try: commands_executed=[] exploit_result='' self.method_id="Http_based()" self.print_Log("Inside HttpBased()") self.print_Log_info("Inside HttpBased()") self.print_Log("Args are : "+str(args[0])) commands_executed.append('requests.get('+str(args[0])+')') response = requests.get(str(args[0])) self.print_Log( "Status code is : "+str(response.status_code)) self.print_Log_info( "Status code is : "+str(response.status_code)) html = response.text commands_executed.append("http-response" +str(html)) file_ = open('response.html', 'w+') file_.write(html.encode('utf8')) file_.close() exploit_result="Command Executed :"+commands_executed[0]+"\n" exploit_result=exploit_result+"\nResult\n"+str(commands_executed[len(commands_executed)-1]) #exploit_result="\nResult"+exploit_result+str(commands_executed[len(commands_executed)-1]) #self.SaveDetails(''.join(commands_executed),exploit_result) self.SaveDetails(str(commands_executed),exploit_result) self.print_Log_info("Exiting HttpBased()") except Exception ,ee: self.print_Error( "Exception Http_based " +str(ee)) self.print_Error_info( "Exception Http_based " +str(ee))
40.832298
386
0.681237
871b82296825c92346e4ea94e4ffb6f380763fe7
16,174
py
Python
identification.py
DUTLiuKevin/starch
285b1e4c9a2332e82acec4a4f08ebded6c1d77a4
[ "MIT" ]
1
2022-01-13T20:24:52.000Z
2022-01-13T20:24:52.000Z
identification.py
DUTLiuKevin/starch
285b1e4c9a2332e82acec4a4f08ebded6c1d77a4
[ "MIT" ]
null
null
null
identification.py
DUTLiuKevin/starch
285b1e4c9a2332e82acec4a4f08ebded6c1d77a4
[ "MIT" ]
null
null
null
# The storm identifier that labels individual storms with unique label at each time step of precipitation data. # The almost-connected labeling algorithm in the code, which is the method "identify" is from # Storm Tracking and Evaluation Protocol (https://github.com/DUTLiuKevin/STEP, author: Alex Rittler) and paper: # Chang, W., Stein, M. L., Wang, J., Kotamarthi, V. R., & Moyer, E. J. (2016). Changes in Spatiotemporal Precipitation # Patterns in Changing Climate Conditions. Journal of Climate, 29(23) # 2021/12/20 # import packages import copy import numpy as np from scipy.ndimage.measurements import label from scipy.ndimage.morphology import generate_binary_structure from skimage import morphology from skimage import draw from skimage.segmentation import relabel_sequential import skimage.segmentation from tqdm import tqdm def identification(prcp_array: np.ndarray, high_threshold: float = 0.5, low_threshold: float = 0.03, morph_radius: int = 4, expand_distance: int = 8): """ Method to identify and label storms at each time step from precipitation field. :param prcp_array: Precipitation array with dimension of (time, lon, lat). :param high_threshold: High precipitation filtering threshold, default 0.5 mm/hour. :param low_threshold: Low precipitation growing threshold, default 0.03 mm/hour. :param morph_radius: Radius of a circular morph structure for storm pattern dilation and erosion, default 4 pixels. :param expand_distance: Maximum distance of dilation when growing storm area, default 8 pixels. :return: An array that individual storms are assigned with unique integer labels at each time step. """ # apply high threshold filtering on precipitation field filtered_array = np.where(prcp_array < high_threshold, 0, prcp_array) # create a morph structure for erosion and dilation operations morph_structure = build_morph_structure(morph_radius=morph_radius) # run identifying code, return labelled individual storms labeled_array = identify(data=filtered_array, morph_structure=morph_structure) # apply low threshold filtering on precipitation field low_threshold_array = np.where(prcp_array < low_threshold, 0, prcp_array) # initialize the array to save results grown_array = np.zeros(prcp_array.shape) # get the total time step length of the precipitation field lifetime = prcp_array.shape[0] for i in range(lifetime): # change each pixel with precipitation to 1 and others to 0 low_threshold_binary_array = np.where(low_threshold_array[i] != 0, 1, 0) # morph dilation for identified storm dilate_array = skimage.segmentation.expand_labels(labeled_array[i], distance=expand_distance) # grow storm to low threshold boundary grown_array[i, :, :] = np.where(low_threshold_binary_array == 1, dilate_array, 0) # return identify result return grown_array def build_morph_structure(morph_radius): """ Create an array that represents a circular morph structure with specific radius. :param morph_radius: Radius of the morph structure. :return: An array describing the morph structure. """ struct = np.zeros((2 * morph_radius, 2 * morph_radius)) rr, cc = draw.disk(center=(morph_radius - 0.5, morph_radius - 0.5), radius=morph_radius) struct[rr, cc] = 1 # data in the circle equals 1 return struct def perform_connected_components(to_be_connected: np.ndarray, result: np.ndarray, lifetime: int, connectivity_type: np.ndarray) -> None: """ This code is from github project Storm Tracking and Evaluation Protocol (https://github.com/RDCEP/STEP, author: Alex Rittler. Higher order function used to label connected-components on all time slices of a dataset. :param to_be_connected: the data to perform the operation on, given as an array of dimensions Time x Rows x Cols. :param result: where the result of the operation will be stored, with the same dimensions as to_be_connected. :param lifetime: the number of time slices in the data, given as an integer. :param connectivity_type: an array representing the type of connectivity to be used by the labeling algorithm. See scipy.ndimage.measurements.label for more information. :return: (None - the operation is performed on the result in place.) """ for index in range(lifetime): cc_output, _ = label(to_be_connected[index], connectivity_type) # label also returns # of labels found result[index] = cc_output def perform_morph_op(morph_function: object, to_be_morphed: np.ndarray, result: np.ndarray, lifetime: int, structure: np.ndarray) -> None: """ This code is from github project Storm Tracking and Evaluation Protocol (https://github.com/RDCEP/STEP, author: Alex Rittler. Higher order function used to perform a morphological operation on all time slices of a dataset. :param morph_function: the morphological operation to perform, given as an object (function). :param to_be_morphed: the data to perform the operation on, given as an array of dimensions Time x Rows x Cols. :param result: where the result of the operation will be store, with the same dimensions as to_be_morphed. :param lifetime: the number of time slices in the data, given as an integer. :param structure: the structural set used to perform the operation, given as an array. See scipy.morphology for more information. :return: (None - the operation is performed on the result in place.) """ for index in range(lifetime): operation = morph_function(to_be_morphed[index], structure) result[index] = operation def identify(data: np.ndarray, morph_structure: np.ndarray) -> np.ndarray: """ This code is from github project Storm Tracking and Evaluation Protocol (https://github.com/RDCEP/STEP, author: Alex Rittler. Divides the precipitation field at each time step into individual storms using morphological operations and connected-component labeling. :param data: the precipitation data, given as an array of dimensions Time x Rows x Cols. To identify storms in a single time slice, reshape the array to dimensions (1, Rows, Cols). :param morph_structure: the structural set used to perform morphological operations, given as an array. See scipy.morphology for more information. :return: an array of time slice maps with individual storms labeled at each time slice, with the dimensions of data. """ # 1) Run connected-components algorithm on all time slices: # find the dimensions of the input shape = data.shape num_time_slices, row, col = shape # initialize a new empty array of these dimensions to hold the result of running the connected-components algorithm # on all time slices label_array = np.empty((num_time_slices, row, col)).astype(int) # use 8-connectivity for determining connectedness below connectivity = generate_binary_structure(2, 2) # run the connected-components algorithm on the data and store it in our new array # since we will repeat this process often, we use a higher order function to compute the desired result perform_connected_components(data, label_array, num_time_slices, connectivity) # 2) Run erosion on labeled maps: # initialize an array of the same dimensions to store morphological transformations in morphology_array = np.zeros((num_time_slices, row, col)).astype(int) # perform the necessary erosion operation using a similar higher order function # note: here we make use of our defined structural set given as input perform_morph_op(morphology.erosion, label_array, morphology_array, num_time_slices, morph_structure) # 3) Classify storms with 1 or more remaining grid cells after erosion as large: # initialize a list of sets, where the list's indices correspond to time slices of the dataset large_storms = [set() for _ in range(num_time_slices)] # for each time slice, if the slice originally had any labeled storms print("\nStart the first loop in identification.\n") for time_index in tqdm(range(num_time_slices)): num_labels = np.max(label_array[time_index]) # for each of these labels, check if the label still appears after the erosion for storm_segment in range(1, num_labels + 1): if storm_segment in morphology_array[time_index]: # if so, add it to the set of large storms for the current time slice large_storms[time_index].add(storm_segment) # 4) For the set of large storms, find smoothed regions using an opening operation: # initialize an array of the same dimensions as the others large_storm_array = np.zeros((num_time_slices, row, col)).astype(int) # write in the large storm labels at their appropriate locations print("\nStart the second loop in identification.\n") for time_index in tqdm(range(num_time_slices)): for col_index in range(col): for row_index in range(row): if label_array[time_index][row_index][col_index] in large_storms[time_index]: large_storm_array[time_index][row_index][col_index] = \ label_array[time_index][row_index][col_index] # define the array of small storms as the array holding the initial connected-components without those found to be # large storms small_storm_array = np.where(large_storm_array != 0, 0, label_array) # reuse our morphology array for another morphological operation, this time 'opening', to produce our desired # smoothed storm regions perform_morph_op(morphology.erosion, large_storm_array, morphology_array, num_time_slices, morph_structure) perform_morph_op(morphology.dilation, morphology_array, morphology_array, num_time_slices, morph_structure) # 5) Perform almost-connected-component labeling on the large storms: # dilate newly-smoothed regions perform_morph_op(morphology.dilation, morphology_array, morphology_array, num_time_slices, morph_structure) # run fully-connected-components algorithm on them perform_connected_components(morphology_array, morphology_array, num_time_slices, connectivity) # map clustering results onto array of large storms, but only where the storms exist in the original data print("\nStart the third loop in identification.\n") for time_index in tqdm(range(num_time_slices)): for storm in np.unique(morphology_array[time_index]): if storm: overlap = np.where((large_storm_array[time_index] != 0) & (morphology_array[time_index] == storm), 1, 0).astype(int) if np.max(overlap) > 0: labels = np.unique(np.where(overlap == 1, large_storm_array[time_index], 0)) large_storm_array[time_index] = np.where(np.isin(large_storm_array[time_index], labels) & (large_storm_array[time_index] != 0), storm + np.max(label_array), large_storm_array[time_index]) # 6) Add small areas to existing nearby rainstorm events: # copy the large storm array to compute overlaps against, ensuring overlaps are calculated on the same large storm # array data each time large_copy = copy.deepcopy(large_storm_array) # perform almost connected-component labeling on the small storm array # small_dilated = np.empty((num_time_slices, row, col)).astype(int) perform_morph_op(morphology.dilation, small_storm_array, morphology_array, num_time_slices, morph_structure) perform_connected_components(morphology_array, morphology_array, num_time_slices, connectivity) print("\nStart the forth loop in identification.\n") for time_index in tqdm(range(num_time_slices)): small_storm_array[time_index] = np.where(small_storm_array[time_index] != 0, morphology_array[time_index], small_storm_array[time_index]) # find unique labels at each time slice for both large and small storm arrays print("\nStart the fifth loop in identification.\n") for time_index in tqdm(range(num_time_slices)): # find the unique labels at each time slice for both large and small storm arrays unique_elements_large = np.unique(large_storm_array[time_index]) unique_elements_small = np.unique(small_storm_array[time_index]) # for each small storm cluster for small_index, small_storm in enumerate(unique_elements_small): max_cells_overlap = 0 # max overlap between a small storm and all large storms at that time slice overlap_amount = 0 # count for any particular combination (maximal or not) if small_storm == 0: continue # for each large storm for large_index, large_storm in enumerate(unique_elements_large): if large_storm == 0: continue # find where the two storms overlap overlap_amount = np.sum(np.where((large_copy[time_index] == large_storm) & (morphology_array[time_index] == small_storm), 1, 0)) # if we've found a larger overlap if overlap_amount > max_cells_overlap: # save the label of the overlapping large storm and update the maximum overlap largest_overlap_label = large_storm max_cells_overlap = overlap_amount # if we've found any overlaps if max_cells_overlap and largest_overlap_label: # write the small storm into the (original) large storm array using the label of the cluster with # maximum overlap, but only at the locations where it appears in the un-dilated small storm array large_storm_array[time_index] = np.where(small_storm_array[time_index] == small_storm, largest_overlap_label, large_storm_array[time_index]) # remove this small storm from the small storm array small_storm_array[time_index] = np.where(small_storm_array[time_index] == small_storm, 0, small_storm_array[time_index]) # 7) Find rainstorm events consisting only of small areas: # perform almost-connected-component labeling on those small storms that are left perform_morph_op(morphology.dilation, small_storm_array, morphology_array, num_time_slices, morph_structure) perform_connected_components(morphology_array, morphology_array, num_time_slices, connectivity) # store the max label used in each time slice of the large storm array largest_storm_label = np.empty((num_time_slices, 1, 1)).astype(int) # take the results of our almost-connected-component labeling on the small storms and add the # largest label in that time slice to it in order to produce a new label to add to the large storm array in the same # location there print('\nStart the sixth loop in identification.\n') for time_index in tqdm(range(num_time_slices)): largest_storm_label[time_index] = np.max(large_storm_array[time_index]) large_storm_array = np.where((small_storm_array != 0), morphology_array + largest_storm_label, large_storm_array) result = np.empty_like(large_storm_array) # 8) Relabel the labels in each time slice sequentially from 1: print('\nStart the seventh loop in identification.\n') for time_index in tqdm(range(num_time_slices)): result[time_index] = relabel_sequential(large_storm_array[time_index])[0] # change data type to int # result = result.astype('int') return result
56.355401
120
0.705144
a6d2706f4f1c1bd089620606c3e525a056e58e45
2,716
py
Python
tests/test_printers_prettification.py
fentik/pglast
c4652b3a6098faf26fa8d3a8fd054f23acd72f9c
[ "PostgreSQL" ]
179
2018-07-06T19:43:02.000Z
2022-03-25T10:46:50.000Z
tests/test_printers_prettification.py
fentik/pglast
c4652b3a6098faf26fa8d3a8fd054f23acd72f9c
[ "PostgreSQL" ]
90
2018-06-16T09:55:05.000Z
2022-02-28T15:11:45.000Z
tests/test_printers_prettification.py
fentik/pglast
c4652b3a6098faf26fa8d3a8fd054f23acd72f9c
[ "PostgreSQL" ]
32
2019-01-08T09:16:57.000Z
2022-03-30T05:27:25.000Z
# -*- coding: utf-8 -*- # :Project: pglast -- Assert printers emit beautiful code # :Created: dom 17 mar 2019 10:46:03 CET # :Author: Lele Gaifax <lele@metapensiero.it> # :License: GNU General Public License version 3 or later # :Copyright: © 2019, 2020, 2021 Lele Gaifax # from ast import literal_eval from pathlib import Path import pytest from pglast import _extract_comments from pglast.stream import IndentedStream, RawStream import pglast.printers # noqa this = Path(__file__) this_dir = this.parent tests_dir = this_dir / this.stem def cases(src): lineno = 1 for case in src.read_text().split('\n\n'): yield lineno, case.strip() lineno += case.count('\n') + 2 def make_id(arg): if isinstance(arg, Path): return str(arg.relative_to(this_dir)) elif isinstance(arg, int): return str(arg) # Prettification cases: each case may be composed by either two or three parts, # respectively the original statement, the expected outcome and an optional options # dictionary. The original and the expected statements are separated by a standalone "=", # while the options dictionary is introduced by a standalone ":". Thus something like # this: # # RAW_STATEMENT # = # PRETTIFIED_STATEMENT # # or this: # # RAW_STATEMENT # = # PRETTIFIED_STATEMENT # : # INDENTEDSTREAM_OPTIONS_DICTIONARY # # The prettified statement may contain standalone "\n\" lines, that are replaced with single # newlines, to allow "empty lines"; in other words, the following expected statement # # SELECT foo # # INTERSECT # # SELECT bar # # must be written as # # SELECT foo # \n\ # INTERSECT # \n\ # SELECT bar # # When it ends with a "\", it is replaced with a final newline. @pytest.mark.parametrize('src,lineno,case', ((src, lineno, case) for src in sorted(tests_dir.glob('**/*.sql')) for (lineno, case) in cases(src)), ids=make_id) def test_prettification(src, lineno, case): parts = case.split('\n=\n') original = parts[0].strip() parts = parts[1].split('\n:\n') expected = parts[0].strip().replace('\\n\\\n', '\n').replace('\\s', ' ') if expected.endswith('\\'): expected = expected[:-1] + '\n' if len(parts) == 2: options = literal_eval(parts[1]) else: options = {} if options.pop('preserve_comments', False): options['comments'] = _extract_comments(original) raw = options.pop('raw_stream', False) prettified = (RawStream if raw else IndentedStream)(**options)(original) assert expected == prettified, "%s:%d:%r != %r" % (src, lineno, expected, prettified)
28.291667
92
0.645803
257185fad01e2783e1852be4c753a3174937ab82
2,515
py
Python
files_treatment_new/fasta_contigs_NCBI.py
diogo1790team/inphinity_DM
b20d75ee0485e1f406a25efcf5f2855631166c38
[ "MIT" ]
1
2019-03-11T12:59:37.000Z
2019-03-11T12:59:37.000Z
files_treatment_new/fasta_contigs_NCBI.py
diogo1790team/inphinity_DM
b20d75ee0485e1f406a25efcf5f2855631166c38
[ "MIT" ]
21
2018-10-17T14:52:30.000Z
2019-06-03T12:43:58.000Z
files_treatment_new/fasta_contigs_NCBI.py
diogo1790team/inphinity_DM
b20d75ee0485e1f406a25efcf5f2855631166c38
[ "MIT" ]
6
2019-02-28T07:40:14.000Z
2019-09-23T13:31:54.000Z
# -*- coding: utf-8 -*- """ Created on Tur Jan 11 15:39:15 2018 @author: Diogo """ from files_treatment_new.generic_fasta_file import _generic_fasta_file from objects_new.Contigs_new import * import numpy as np class FastaContigsNCBI(_generic_fasta_file): """ Class specified in the treatment of the fasta RAST format file of fasta. Remember that its a heritage of the class generic_fasta_file that its used to read the data from a file """ def __init__(self, path_file): """ Constructor of the class fasta contigs class, this one contain all methods for the treatment of fasta contigs of RAST platform. After the parameters initialisation, the datails loaded :param path_file: Complete path with file name :type path_file: string - required """ _generic_fasta_file.__init__(self, path_file) self.read_fasta_file() def get_contig_seq_by_id(self, contig_id): """ Get the nucleic sequence of a contig given its id :param contig_id: form used to request the download of genbank file to the server :type contig_id: string - required :return: sequence nucleic in string format :rtype: string """ sequence_nuc = str(self.dict_fasta_data[contig_id].seq) return sequence_nuc def get_qty_of_contigs(self): """ Get the quantity of contigs in the fasta file :return: quantity of contigs :rtype: int """ qty_contigs = len(self.dict_fasta_data) return qty_contigs def create_contigs_from_file(self): """ This method create a list of contigs based on the fasta data :return: list of contigs :rtype: list(Contigs) """ list_of_contigs = [] for key, value in self.dict_fasta_data.items(): contig_obj = Contig(head = value.description, sequence = str(value.seq)) list_of_contigs.append(contig_obj) return list_of_contigs def get_list_contigs_id(self): """ Return a list of the contigs ids in the fasta file (usualy used to comprare with those in the EXCEL file) :return: array of contigs :rtype: array(Contigs) """ list_of_contigs_ids = np.empty([0], dtype=np.str) for key, value in self.dict_fasta_data.items(): list_of_contigs_ids = np.append(list_of_contigs_ids, [value.description]) return list_of_contigs_ids
30.670732
191
0.655666
db48058c7c22155d1a21830122562d960d74c8b8
562
py
Python
ecommerce/src/products/migrations/0010_product_timestamp.py
khalildh/ecommerce-django
48ac2be8677bd87ccfb959a9cdcd62db1ead258f
[ "MIT" ]
null
null
null
ecommerce/src/products/migrations/0010_product_timestamp.py
khalildh/ecommerce-django
48ac2be8677bd87ccfb959a9cdcd62db1ead258f
[ "MIT" ]
5
2021-02-08T20:20:05.000Z
2022-03-11T23:16:40.000Z
ecommerce/src/products/migrations/0010_product_timestamp.py
khalildh/ecommerce-django
48ac2be8677bd87ccfb959a9cdcd62db1ead258f
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-11-28 01:21 from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('products', '0009_auto_20171127_2050'), ] operations = [ migrations.AddField( model_name='product', name='timestamp', field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), preserve_default=False, ), ]
24.434783
93
0.647687
e5aeb4aeb444673cccb8bbcee201d8e22d5c4b65
5,193
py
Python
loss/modules/pose_modules.py
youansheng/PyTorchCV
3a51b2f209639e58620676bf19b3564ef8c92a75
[ "Apache-2.0" ]
68
2019-01-10T09:16:39.000Z
2022-03-20T18:23:52.000Z
loss/modules/pose_modules.py
youdonny/torchcv
c7e717fe301ba338b3e9dbea70b51f3e2cd5dabe
[ "Apache-2.0" ]
4
2019-01-10T11:47:09.000Z
2019-01-21T15:04:52.000Z
loss/modules/pose_modules.py
youdonny/torchcv
c7e717fe301ba338b3e9dbea70b51f3e2cd5dabe
[ "Apache-2.0" ]
13
2019-01-11T06:13:40.000Z
2021-05-22T03:09:52.000Z
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: Donny You(youansheng@gmail.com) # Loss function for Pose Estimation. from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch import torch.nn as nn from torch.autograd import Variable class OPMseLoss(nn.Module): def __init__(self, configer): super(OPMseLoss, self).__init__() self.configer = configer reduction = 'elementwise_mean' if self.configer.exists('loss', 'params') and 'mse_reduction' in self.configer.get('loss', 'params'): reduction = self.configer.get('loss', 'params')['mse_reduction'] self.mse_loss = nn.MSELoss(reduction=reduction) def forward(self, inputs, *targets, mask=None, weights=None): loss = 0.0 if isinstance(inputs, list): if weights is not None: for i in range(len(inputs)): if mask is not None: loss += weights[i] * self.mse_loss(inputs[i]*mask, targets) else: loss += weights[i] * self.mse_loss(inputs[i], targets) else: for i in range(len(inputs)): if mask is not None: loss += self.mse_loss(inputs[i]*mask, targets) else: loss += self.mse_loss(inputs[i], targets) else: if mask is not None: loss = self.mse_loss(inputs*mask, targets) else: loss = self.mse_loss(inputs, targets) if self.configer.get('mse_loss', 'reduction') == 'sum': loss = loss / targets.size(0) return loss class PartLoss(nn.Module): def __init__(self, configer): super(PartLoss, self).__init__() self.configer = configer self.mse_loss = nn.MSELoss(size_average=False) def forward(self, inputs, targets, mask=None): inputs = inputs.view(inputs.size(0), -1, 6, inputs.size(2), inputs.size(3)) targets = targets.view(targets.size(0), -1, 6, targets.size(2), targets.size(3)) paf_loss = self.mse_loss(inputs[:, :, 0:2, :, :], targets[:, :, 0:2, :, :]) part_loss = self.mse_loss(inputs[:, :, 2:6, :, :], targets[:, :, 2:6, :, :]) loss = paf_loss + part_loss * 6.0 loss = loss / targets.size(0) return loss class CapsuleLoss(nn.Module): def __init__(self, configer): super(CapsuleLoss, self).__init__() self.configer = configer self.mse_loss = nn.MSELoss(reduction=self.configer.get('capsule_loss', 'reduction')) def forward(self, inputs, targets, masks=None, is_focal=False): preds = torch.sqrt((inputs**2).sum(dim=1, keepdim=False)) if masks is not None: preds = preds * masks if is_focal: loss = self.mse_loss(preds, targets) else: diff = preds - targets diff = diff ** 2 alpha = 2.0 weights = targets * alpha weights = torch.exp(weights) diff = weights * diff loss = diff.mean() return loss class EmbeddingLoss(nn.Module): def __init__(self, configer): super(EmbeddingLoss, self).__init__() self.configer = configer self.num_keypoints = self.configer.get('data', 'num_keypoints') self.l_vec = self.configer.get('capsule', 'l_vec') self.mse_loss = nn.MSELoss(size_average=False) def forward(self, inputs, tags, numH, sigma=0.1): batch_size = inputs.size(0) h_tag_means = [[Variable(torch.zeros(self.l_vec,), requires_grad=True).cuda() for h in range(numH[b].numpy()[0])] for b in range(inputs.size()[0])] for b in range(batch_size): for n in range(numH[b].numpy()[0]): valik = 0 for k in range(self.num_keypoints): tag = inputs[b].masked_select(tags[b][k].eq(n+1).unsqueeze(0)) if tag.size() != torch.Size([]): h_tag_means[b][n] += tag valik = valik + 1 h_tag_means[b][n] = h_tag_means[b][n] / max(valik, 1) loss_list = list() for b in range(batch_size): for n in range(numH[b].numpy()[0]): for k in range(self.num_keypoints): tag = inputs[b].masked_select(tags[b][k].eq(n+1).unsqueeze(0)) if tag.size() != torch.Size([]): loss_list.append(self.mse_loss(tag, h_tag_means[b][n])) for b in range(batch_size): for n1 in range(numH[b].numpy()[0]): for n2 in range(numH[b].numpy()[0]): if n1 != n2: loss_same = torch.exp(-self.mse_loss(h_tag_means[b][n1], h_tag_means[b][n2]) / sigma / sigma) loss_list.append(loss_same) if len(loss_list) == 0: loss = 0.0 else: loss = loss_list[0] for i in range(len(loss_list)-1): loss += loss_list[i+1] return loss
36.0625
117
0.546505
70964ccd78bcf835b90027bdb9a476e61585b3c1
6,789
py
Python
novaagent/common/password.py
gtmanfred/novaagent
ef2e22bfd7583cefcdcf7b8b3471c9c4c60b204e
[ "Apache-2.0" ]
2
2017-08-08T21:46:02.000Z
2018-01-24T21:40:15.000Z
novaagent/common/password.py
gtmanfred/novaagent
ef2e22bfd7583cefcdcf7b8b3471c9c4c60b204e
[ "Apache-2.0" ]
27
2017-08-07T13:51:51.000Z
2021-05-22T23:46:57.000Z
novaagent/common/password.py
gtmanfred/novaagent
ef2e22bfd7583cefcdcf7b8b3471c9c4c60b204e
[ "Apache-2.0" ]
13
2017-09-16T12:12:05.000Z
2021-03-04T21:41:16.000Z
# # Copyright (c) 2011 Openstack, LLC. # 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. # """ JSON password reset handling plugin """ from subprocess import PIPE from subprocess import Popen import binascii import base64 import sys import os from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends.openssl.backend import backend if sys.version_info > (3,): long = int # This is to support older python versions that don't have hashlib try: import hashlib except ImportError: import md5 class hashlib(object): """Fake hashlib module as a class""" @staticmethod def md5(): return md5.new() class PasswordError(Exception): """ Class for password command exceptions """ def __init__(self, response): # Should be a (ResponseCode, ResponseMessage) tuple self.response = response def __str__(self): return "%s: %s" % self.response def get_response(self): return self.response class PasswordCommands(object): """ Class for password related commands """ def __init__(self): self.prime = 162259276829213363391578010288127 self.base = 5 self.min_key_length = 540 self._public = None self._private = None self._shared = None self._aes_key = None self._aes_iv = None def _generate_private_key(self): """Create a private key using /dev/urandom""" _bytes = self.min_key_length // 8 + 8 self._private = int(binascii.hexlify(os.urandom(_bytes)), 16) def _compute_public_key(self): """Given a private key, compute a public key""" self._public = pow(self.base, self._private, self.prime) def _compute_shared_key(self, remote_public_key): """Given public and private keys, compute the shared key""" self._shared = pow(remote_public_key, self._private, self.prime) def _compute_aes_key(self): """ Given a key, compute the corresponding key that can be used with AES """ shared_string = str(self._shared) self._aes_key = (hashlib.md5(shared_string.encode('utf-8'))).digest() m = hashlib.md5(self._aes_key) m.update(shared_string.encode('utf-8')) self._aes_iv = m.digest() def _decrypt_password(self, data): try: # Version 3 or later cipher = Cipher(algorithms.AES(self._aes_key), modes.CBC(self._aes_iv), backend=backend) except Exception: # Previous to version 3 cipher = Cipher(algorithms.AES(self._aes_key), modes.CBC(self._aes_iv), backend) decryptor = cipher.decryptor() decrypted_passwd = decryptor.update(data) + decryptor.finalize() # aes = pyaes.AESModeOfOperationCBC(self._aes_key, iv=self._aes_iv) # decrypted_passwd = aes.decrypt(data) try: cut_off_sz = ord(decrypted_passwd[len(decrypted_passwd) - 1]) except Exception: cut_off_sz = decrypted_passwd[len(decrypted_passwd) - 1] if cut_off_sz > 16 or len(decrypted_passwd) < 16: raise PasswordError((500, "Invalid password data received")) passwd = decrypted_passwd[: - cut_off_sz] return passwd def _decode_password(self, data): try: real_data = base64.b64decode(data) except Exception: raise PasswordError((500, "Couldn't decode base64 data")) if self._aes_key is None: raise PasswordError((500, "Password without key exchange")) try: passwd = self._decrypt_password(real_data) except PasswordError as exc: raise exc except Exception as exc: raise PasswordError((500, str(exc))) return passwd def _change_password(self, passwd): if isinstance(passwd, bytes): string_passwd = passwd.decode('utf-8') else: string_passwd = str(passwd) # Make sure there are no newlines at the end set_password('root', string_passwd.strip('\n')) def _wipe_keys(self): """ Reset Values from previous keyinit command as each password keyinit is called again and new values are generated """ self._aes_key = None self._aes_iv = None self._private = None self._public = None self._shared = None def keyinit_cmd(self, data): """ Remote public key should come in as a large number. Set it to long in case it comes in as a string """ remote_public_key = long(data) # Sets self._private self._generate_private_key() # Sets self._public self._compute_public_key() # Sets self._shared self._compute_shared_key(remote_public_key) # Sets self._aes_key and self._aes_iv self._compute_aes_key() # Return the public key as a string return ("D0", str(self._public)) def password_cmd(self, data): try: passwd = self._decode_password(data) self._change_password(passwd) except PasswordError as exc: return exc.get_response() self._wipe_keys() return ("0", "") def set_password(user, password): """Set the password for a particular user using passwd""" p = Popen( ['passwd', user], stdout=PIPE, stderr=PIPE, stdin=PIPE ) try: p.stdin.write(u'{0}\n{0}\n'.format(password)) except TypeError: # Python 3 wants bytes so catch the exception and encode properly p.stdin.write(u'{0}\n{0}\n'.format(password).encode('utf-8')) p.stdin.flush() out, err = p.communicate() if p.returncode != 0: raise PasswordError( ( 500, 'Failed to change password for {0}: {1} : {2}'.format( user, p.returncode, err ) ) ) return
28.766949
79
0.605538
922112c81b4b7767d5c1d630e8a10f114d0b165a
406
py
Python
onlinecourse/migrations/0003_choice_course.py
HilbertSpecs/onlinecourse-app
ad7175c0eb6906d36ac9339b7f2cdf28d12c74de
[ "Apache-2.0" ]
null
null
null
onlinecourse/migrations/0003_choice_course.py
HilbertSpecs/onlinecourse-app
ad7175c0eb6906d36ac9339b7f2cdf28d12c74de
[ "Apache-2.0" ]
null
null
null
onlinecourse/migrations/0003_choice_course.py
HilbertSpecs/onlinecourse-app
ad7175c0eb6906d36ac9339b7f2cdf28d12c74de
[ "Apache-2.0" ]
null
null
null
# Generated by Django 3.1.3 on 2021-12-01 22:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('onlinecourse', '0002_auto_20211201_2115'), ] operations = [ migrations.AddField( model_name='choice', name='course', field=models.ManyToManyField(to='onlinecourse.Course'), ), ]
21.368421
67
0.610837
98b20d87a120e8073cb7b71756fbb634e804ef2e
747
py
Python
tests/test_jedi_ast_tools.py
ajylee/call_map
21e7684b0814eae6f16cd4bc75597dc4e9239ec0
[ "BSD-2-Clause" ]
20
2017-12-24T00:19:15.000Z
2021-11-15T07:42:25.000Z
tests/test_jedi_ast_tools.py
ajylee/call_map
21e7684b0814eae6f16cd4bc75597dc4e9239ec0
[ "BSD-2-Clause" ]
1
2017-10-22T21:03:41.000Z
2017-12-24T04:26:22.000Z
tests/test_jedi_ast_tools.py
ajylee/call_map
21e7684b0814eae6f16cd4bc75597dc4e9239ec0
[ "BSD-2-Clause" ]
2
2017-11-04T10:06:59.000Z
2019-08-01T22:24:49.000Z
import jedi import call_map.jedi_ast_tools as jat import toolz as tz import textwrap def test_get_called_functions(): test_script = """ import call_map.jedi_ast_tools as jat def thunk(): print('hi') def ff(node): aa = jat.get_called_functions(node) thunk() """ text_script = textwrap.dedent(test_script) definitions = jedi.api.names(source=test_script) def_ff = tz.first(filter(lambda x: x.name == 'ff', definitions)) called_by_ff = list(jat.get_called_functions(def_ff._name.tree_name.get_definition().children[-1])) assert len(called_by_ff) == 2 assert {name.value for role, name, ast_node, start_pos, end_pos in called_by_ff} == {'thunk', 'get_called_functions'}
22.636364
121
0.689424
07f0e110fe7a2a70c7f2992e8d5b001d124947eb
5,338
py
Python
gprm/utils/wrapping_tools.py
siwill22/GPlatesClassStruggle
713a87ff4f054d3a493ec09e5f310aa3036d3bc5
[ "MIT" ]
7
2020-05-04T03:05:09.000Z
2022-01-28T13:52:53.000Z
gprm/utils/wrapping_tools.py
siwill22/GPlatesClassStruggle
713a87ff4f054d3a493ec09e5f310aa3036d3bc5
[ "MIT" ]
null
null
null
gprm/utils/wrapping_tools.py
siwill22/GPlatesClassStruggle
713a87ff4f054d3a493ec09e5f310aa3036d3bc5
[ "MIT" ]
3
2021-05-23T01:53:52.000Z
2021-09-14T12:21:53.000Z
# # Functions for wrapping geometries to dateline before returning request geojson # import pygplates def wrap_polylines(polylines,lon0=0,tesselate_degrees=1): data = {"type": "FeatureCollection"} data["features"] = [] for polyline in polylines: if lon0 is not None: wrapper = pygplates.DateLineWrapper(lon0) geometries = wrapper.wrap(polyline.get_geometry(),tesselate_degrees) else: geometries = polyline.get_geometries() for geometry in geometries: feature = {"type": "Feature"} feature["geometry"] = {} feature["geometry"]["type"] = "MultiLineString" point_list = [] for point in geometry.get_points(): point_list.append((point.to_lat_lon()[1],point.to_lat_lon()[0])) feature["geometry"]["coordinates"] = [point_list] data["features"].append(feature) return data def wrap_polygons(polygons,lon0=0,tesselate_degrees=1): data = {"type": "FeatureCollection"} data["features"] = [] for polygon in polygons: if lon0 is not None: wrapper = pygplates.DateLineWrapper(lon0) geometries = wrapper.wrap(polygon.get_geometry(),tesselate_degrees) for geometry in geometries: feature = {"type": "Feature"} feature["geometry"] = {} feature["geometry"]["type"] = "Polygon" point_list = [] for point in geometry.get_exterior_points(): point_list.append((point.to_lat_lon()[1],point.to_lat_lon()[0])) feature["geometry"]["coordinates"] = [point_list] data["features"].append(feature) else: for geometry in polygon.get_geometries(): feature = {"type": "Feature"} feature["geometry"] = {} feature["geometry"]["type"] = "Polygon" point_list = [] for point in geometry.get_points(): point_list.append((point.to_lat_lon()[1],point.to_lat_lon()[0])) if geometry.get_orientation() == pygplates.PolygonOnSphere.Orientation.counter_clockwise: point_list.reverse() feature["geometry"]["coordinates"] = [point_list] data["features"].append(feature) return data def wrap_reconstructed_polygons(reconstructed_polygons,lon0=0,tesselate_degrees=1): data = {"type": "FeatureCollection"} data["features"] = [] for reconstructed_polygon in reconstructed_polygons: rev=False if reconstructed_polygon.get_reconstructed_geometry().get_orientation() == pygplates.PolygonOnSphere.Orientation.counter_clockwise: rev = True if lon0 is not None: wrapper = pygplates.DateLineWrapper(lon0) geometries = wrapper.wrap(reconstructed_polygon.get_reconstructed_geometry(),tesselate_degrees) for geometry in geometries: feature = {"type": "Feature"} feature["geometry"] = {} feature["geometry"]["type"] = "Polygon" point_list = [] for point in geometry.get_exterior_points(): point_list.append((point.to_lat_lon()[1],point.to_lat_lon()[0])) if rev: point_list.reverse() feature["geometry"]["coordinates"] = [point_list] data["features"].append(feature) else: geometry = reconstructed_polygon.get_reconstructed_geometry() feature = {"type": "Feature"} feature["geometry"] = {} feature["geometry"]["type"] = "Polygon" point_list = [] for point in geometry.get_points(): point_list.append((point.to_lat_lon()[1],point.to_lat_lon()[0])) if rev: point_list.reverse() feature["geometry"]["coordinates"] = [point_list] data["features"].append(feature) return data def wrap_plate_boundaries(shared_boundary_sections,lon0=0,tesselate_degrees=1): data = {"type": "FeatureCollection"} data["features"] = [] for shared_boundary_section in shared_boundary_sections: for shared_sub_segment in shared_boundary_section.get_shared_sub_segments(): if lon0 is not None: wrapper = pygplates.DateLineWrapper(lon0) geometries = wrapper.wrap(shared_sub_segment.get_geometry(),tesselate_degrees) else: geometries = shared_sub_segment.get_geometries() for geometry in geometries: feature = {"type": "Feature"} feature["geometry"] = {} feature["geometry"]["type"] = "MultiLineString" point_list = [] for point in geometry.get_points(): point_list.append((point.to_lat_lon()[1],point.to_lat_lon()[0])) feature["geometry"]["coordinates"] = [point_list] feature["feature_type"] = str(shared_sub_segment.get_feature().get_feature_type()) feature["Length"] = float(shared_sub_segment.get_geometry().get_arc_length()) data["features"].append(feature) return data
40.135338
139
0.586737
2a712e14c9b90e37db647cd0169aae9dd1f95685
7,473
py
Python
muddery/server/utils/utils.py
dongwudanci/muddery
669fbbdb394d04995470e32e94f10d42f3387996
[ "BSD-3-Clause" ]
null
null
null
muddery/server/utils/utils.py
dongwudanci/muddery
669fbbdb394d04995470e32e94f10d42f3387996
[ "BSD-3-Clause" ]
null
null
null
muddery/server/utils/utils.py
dongwudanci/muddery
669fbbdb394d04995470e32e94f10d42f3387996
[ "BSD-3-Clause" ]
null
null
null
""" General helper functions that don't fit neatly under any given category. They provide some useful string and conversion methods that might be of use when designing your own game. """ import os, re, inspect import importlib from pkgutil import iter_modules from django.conf import settings from muddery.launcher import configs from muddery.server.database.worlddata.localized_strings import LocalizedStrings def get_muddery_version(): """ Get muddery's version. """ import muddery return muddery.__version__ def file_iterator(file, erase=False, chunk_size=512): while True: c = file.read(chunk_size) if c: yield c else: # remove temp file file.close() if erase: os.remove(file.name) break def get_unlocalized_py_strings(filename, filter): """ Get all unlocalized strings. Args: file_type: (string) type of file. filter: (boolean) filter exits strings or not. Returns: (set): a list of tuple (string, category). """ re_func = re.compile(r'_\(\s*".+?\)') re_string = re.compile(r'".*?"') re_category = re.compile(r'category.*=.*".*?"') strings = set() # search in python files with open(filename, "r") as file: lines = file.readlines() for line in lines: # parse _() function for func in re_func.findall(line): str = "" cate = "" str_search = re_string.search(func) if str_search: str = str_search.group() #remove quotations str = str[1:-1] cate_search = re_category.search(func) if cate_search: group = cate_search.group() cate = re_string.search(group).group() #remove quotations cate = cate[1:-1] if str or cate: if filter: # check database try: LocalizedStrings.get(str, cate) continue except Exception as e: pass strings.add((str, cate,)) return strings def all_unlocalized_py_strings(filter): """ Get all unlocalized strings. Args: file_type: (string) type of file. filter: (boolean) filter exits strings or not. Returns: (set): a list of tuple (string, category). """ rootdir = configs.MUDDERY_LIB strings = set() ext = ".py" # get all _() args in all files for parent, dirnames, filenames in os.walk(rootdir): for filename in filenames: file_ext = os.path.splitext(filename)[1].lower() if file_ext == ext: full_name = os.path.join(parent, filename) strings.update(get_unlocalized_py_strings(full_name, filter)) return strings def get_unlocalized_js_strings(filename, filter_set): """ Get all unlocalized strings. Args: file_type: (string) type of file. filter_set: (set) current localized stings set. Returns: (set): a list of strings. """ re_func = re.compile(r'_\(\s*".+?\)') re_string = re.compile(r'".*?"') strings = set() # search in python files with open(filename, "r") as file: lines = file.readlines() for line in lines: # parse _() function for func in re_func.findall(line): str = "" cate = "" str_search = re_string.search(func) if str_search: str = str_search.group() #remove quotations str = str[1:-1] if str: if filter_set: # check dict if str not in filter_set: strings.add(str) else: strings.add(str) return strings def all_unlocalized_js_strings(filter): """ Get all unlocalized strings. Args: file_type: (string) type of file. filter: (boolean) filter exits strings or not. Returns: (set): a list of tuple (string, category). """ rootdir = configs.MUDDERY_LIB strings = set() ext = ".js" filter_set = set() # get filter if filter: local_string_filename = os.path.join(configs.MUDDERY_LIB, "web", "webclient", "webclient", "lang", settings.LANGUAGE_CODE, "strings.js") with open(local_string_filename, "r") as file: re_dict = re.compile(r'".+?"\s*:\s*".+?"') re_string = re.compile(r'".*?"') lines = file.readlines() for line in lines: # find localization dict dict_search = re_dict.search(line) if dict_search: word_dict = dict_search.group() str_search = re_string.search(word_dict) str = str_search.group() #remove quotations str = str[1:-1] filter_set.add(str) # get all _() args in all files for parent, dirnames, filenames in os.walk(rootdir): for filename in filenames: file_ext = os.path.splitext(filename)[1].lower() if file_ext == ext: full_name = os.path.join(parent, filename) strings.update(get_unlocalized_js_strings(full_name, filter_set)) return strings def class_from_path(path): """ Get a class from its path :param path: :return: """ class_path, class_name = path.rsplit(".", 1) mod = importlib.import_module(class_path) cls = getattr(mod, class_name) return cls def load_modules(path): """ Load all modules ans sub modules in the path. Args: path: (string) modules' path """ modules = [] m = importlib.import_module(path) if hasattr(m, '__path__'): for _, subpath, ispkg in iter_modules(m.__path__): fullpath = path + '.' + subpath if ispkg: modules += load_modules(fullpath) else: modules.append(importlib.import_module(fullpath)) return modules def classes_in_path(path, cls): """ Load all classes in the path. Args: path: (string) classes' path cls: (class) classes' base class """ modules = load_modules(path) for module in modules: for name, obj in vars(module).items(): if inspect.isclass(obj) and issubclass(obj, cls) and obj is not cls: yield obj def get_module_path(path): """ Transform a normal path to a python module style path. """ root, name = os.path.split(path) if not name: return root = get_module_path(root) if root: return root + "." + name else: return name def is_player(element): """ If the element is a player character, return True. """ return element.is_element(settings.PLAYER_CHARACTER_ELEMENT_TYPE)
27.677778
98
0.532718
ab7e406a181ed7d5f250b91edc059bbe1a329770
714
py
Python
CursoPython/ex115/lib/interface/__init__.py
jesterwanderer/curso-python-cursoemvideo
b5d6d4acda10b064f89c7175391307d1b8ccac20
[ "MIT" ]
null
null
null
CursoPython/ex115/lib/interface/__init__.py
jesterwanderer/curso-python-cursoemvideo
b5d6d4acda10b064f89c7175391307d1b8ccac20
[ "MIT" ]
null
null
null
CursoPython/ex115/lib/interface/__init__.py
jesterwanderer/curso-python-cursoemvideo
b5d6d4acda10b064f89c7175391307d1b8ccac20
[ "MIT" ]
null
null
null
def leiaInt(msg): while True: try: n = int(input(msg)) except (ValueError, TypeError): print('\033[0;31mErro! Digite um número inteiro válido.\033[m') continue except (KeyboardInterrupt): print('\033[0;31mErro! O Arrombado preferiu não digitar o número.\033[m') return 0 else: return n def linha(tam=42): return '-' * tam def cab(msg): print(linha()) print(msg.center(42)) print(linha()) def menu(lista): cab("MENU PRINCIPAL!") c = 1 for item in lista: print(f"{c} - {item}") c += 1 print(linha()) opc = leiaInt("Digite sua opção: ") return opc
21.636364
85
0.532213
3171a43ecd0f226b53f82a8a0810d5237ba0861e
41,450
py
Python
Incident-Response/Tools/grr/grr/server/grr_response_server/gui/api_plugins/vfs.py
sn0b4ll/Incident-Playbook
cf519f58fcd4255674662b3620ea97c1091c1efb
[ "MIT" ]
1
2021-07-24T17:22:50.000Z
2021-07-24T17:22:50.000Z
Incident-Response/Tools/grr/grr/server/grr_response_server/gui/api_plugins/vfs.py
sn0b4ll/Incident-Playbook
cf519f58fcd4255674662b3620ea97c1091c1efb
[ "MIT" ]
2
2022-02-28T03:40:31.000Z
2022-02-28T03:40:52.000Z
Incident-Response/Tools/grr/grr/server/grr_response_server/gui/api_plugins/vfs.py
sn0b4ll/Incident-Playbook
cf519f58fcd4255674662b3620ea97c1091c1efb
[ "MIT" ]
2
2022-02-25T08:34:51.000Z
2022-03-16T17:29:44.000Z
#!/usr/bin/env python """API handlers for dealing with files in a client's virtual file system.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import itertools import os import re import zipfile from grr_response_core import config from grr_response_core.lib import rdfvalue from grr_response_core.lib import utils from grr_response_core.lib.rdfvalues import client_fs as rdf_client_fs from grr_response_core.lib.rdfvalues import crypto as rdf_crypto from grr_response_core.lib.rdfvalues import paths as rdf_paths from grr_response_core.lib.rdfvalues import structs as rdf_structs from grr_response_core.lib.util import compatibility from grr_response_core.lib.util import context as context_lib from grr_response_core.lib.util.compat import csv from grr_response_proto.api import vfs_pb2 from grr_response_server import data_store from grr_response_server import data_store_utils from grr_response_server import decoders from grr_response_server import file_store from grr_response_server import flow from grr_response_server import notification from grr_response_server.databases import db from grr_response_server.flows.general import filesystem from grr_response_server.flows.general import transfer from grr_response_server.gui import api_call_handler_base from grr_response_server.gui.api_plugins import client from grr_response_server.rdfvalues import objects as rdf_objects # Files can only be accessed if their first path component is from this list. _ROOT_FILES_ALLOWLIST = ["fs", "registry", "temp"] def ValidateVfsPath(path): """Validates a VFS path.""" components = (path or "").lstrip("/").split("/") if not components: raise ValueError("Empty path is not a valid path: %s." % path) if components[0] not in _ROOT_FILES_ALLOWLIST: raise ValueError("First path component was '%s', but has to be one of %s" % (components[0], ", ".join(_ROOT_FILES_ALLOWLIST))) return True # TODO(hanuszczak): Fix the linter warning properly. class FileNotFoundError(api_call_handler_base.ResourceNotFoundError): # pylint: disable=redefined-builtin """Raised when a certain file is not found. Attributes: client_id: An id of the client for which the file was not found. path_type: A type of the path for which the file was not found. components: Components of the path for which the file was not found. """ def __init__(self, client_id, path_type, components): self.client_id = client_id self.path_type = path_type self.components = components path = "/" + "/".join(components) message = "{path_type} path '{path}' for client '{client_id}' not found" message = message.format( client_id=client_id, path_type=path_type, path=path) super().__init__(message) class FileContentNotFoundError(api_call_handler_base.ResourceNotFoundError): """Raised when the content for a specific file could not be found. Attributes: client_id: An id of the client for which the file content was not found. path_type: A type of the path for which the file content was not found. components: Components of the path for which the file content was not found. timestamp: A timestamp of the file which content was not found. """ def __init__(self, client_id, path_type, components, timestamp=None): self.client_id = client_id self.path_type = path_type self.components = components self.timestamp = timestamp path = "/" + "/".join(components) if timestamp is None: message = "Content for {} file with path '{}' for client '{}' not found" message = message.format(path_type, path, client_id) else: message = ("Content for {} file with path '{}' and timestamp '{}' for " "client '{}' not found") message = message.format(path_type, path, timestamp, client_id) super().__init__(message) class VfsRefreshOperationNotFoundError( api_call_handler_base.ResourceNotFoundError): """Raised when a vfs refresh operation could not be found.""" class VfsFileContentUpdateNotFoundError( api_call_handler_base.ResourceNotFoundError): """Raised when a file content update operation could not be found.""" class ApiAff4ObjectAttributeValue(rdf_structs.RDFProtoStruct): protobuf = vfs_pb2.ApiAff4ObjectAttributeValue rdf_deps = [ rdfvalue.RDFDatetime, ] def GetValueClass(self): try: return rdfvalue.RDFValue.GetPlugin(self.type) except KeyError: raise ValueError("No class found for type %s." % self.type) class ApiAff4ObjectAttribute(rdf_structs.RDFProtoStruct): protobuf = vfs_pb2.ApiAff4ObjectAttribute rdf_deps = [ ApiAff4ObjectAttributeValue, ] class ApiAff4ObjectType(rdf_structs.RDFProtoStruct): """A representation of parts of an Aff4Object. ApiAff4ObjectType represents a subset of all attributes of an Aff4Object defined by a certain class of the inheritance hierarchy of the Aff4Object. """ protobuf = vfs_pb2.ApiAff4ObjectType rdf_deps = [ ApiAff4ObjectAttribute, ] class ApiAff4ObjectRepresentation(rdf_structs.RDFProtoStruct): """A proto-based representation of an Aff4Object used to render responses. ApiAff4ObjectRepresentation contains all attributes of an Aff4Object, structured by type. If an attribute is found multiple times, it is only added once at the type where it is first encountered. """ protobuf = vfs_pb2.ApiAff4ObjectRepresentation rdf_deps = [ ApiAff4ObjectType, ] class ApiFile(rdf_structs.RDFProtoStruct): protobuf = vfs_pb2.ApiFile rdf_deps = [ ApiAff4ObjectRepresentation, rdf_crypto.Hash, rdfvalue.RDFDatetime, rdf_client_fs.StatEntry, ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) try: self.age = kwargs["age"] except KeyError: self.age = rdfvalue.RDFDatetime.Now() class ApiGetFileDetailsArgs(rdf_structs.RDFProtoStruct): protobuf = vfs_pb2.ApiGetFileDetailsArgs rdf_deps = [ client.ApiClientId, rdfvalue.RDFDatetime, ] class ApiGetFileDetailsResult(rdf_structs.RDFProtoStruct): protobuf = vfs_pb2.ApiGetFileDetailsResult rdf_deps = [ ApiFile, ] def _GenerateApiFileDetails(path_infos): """Generate file details based on path infos history.""" type_attrs = [] hash_attrs = [] size_attrs = [] stat_attrs = [] pathspec_attrs = [] def _Value(age, value): """Generate ApiAff4ObjectAttributeValue from an age and a value.""" v = ApiAff4ObjectAttributeValue(age=age) # With dynamic values we first have to set the type and # then the value itself. # TODO(user): refactor dynamic values logic so that it's not needed, # possibly just removing the "type" attribute completely. v.Set("type", compatibility.GetName(value.__class__)) v.value = value return v for pi in path_infos: if pi.directory: object_type = "VFSDirectory" else: object_type = "VFSFile" type_attrs.append(_Value(pi.timestamp, rdfvalue.RDFString(object_type))) if pi.hash_entry: hash_attrs.append(_Value(pi.timestamp, pi.hash_entry)) size_attrs.append( _Value(pi.timestamp, rdfvalue.RDFInteger(pi.hash_entry.num_bytes))) if pi.stat_entry: stat_attrs.append(_Value(pi.timestamp, pi.stat_entry)) if pi.stat_entry.pathspec: pathspec_attrs.append(_Value(pi.timestamp, pi.stat_entry.pathspec)) return ApiAff4ObjectRepresentation(types=[ ApiAff4ObjectType( name="AFF4Object", attributes=[ ApiAff4ObjectAttribute( name="TYPE", values=type_attrs, ), ], ), ApiAff4ObjectType( name="AFF4Stream", attributes=[ ApiAff4ObjectAttribute( name="HASH", values=hash_attrs, ), ApiAff4ObjectAttribute( name="SIZE", values=size_attrs, ), ], ), ApiAff4ObjectType( name="VFSFile", attributes=[ ApiAff4ObjectAttribute( name="PATHSPEC", values=pathspec_attrs, ), ApiAff4ObjectAttribute( name="STAT", values=stat_attrs, ), ], ), ]) class ApiGetFileDetailsHandler(api_call_handler_base.ApiCallHandler): """Retrieves the details of a given file.""" args_type = ApiGetFileDetailsArgs result_type = ApiGetFileDetailsResult def Handle(self, args, context=None): ValidateVfsPath(args.file_path) # Directories are not really "files" so they cannot be stored in the # database but they still can be queried so we need to return something. # Sometimes they contain a trailing slash so we need to take care of that. # # TODO(hanuszczak): Require VFS paths to be normalized so that trailing # slash is either forbidden or mandatory. if args.file_path.endswith("/"): args.file_path = args.file_path[:-1] if args.file_path in [ "fs", "registry", "temp", "fs/os", "fs/tsk", "fs/ntfs" ]: api_file = ApiFile( name=args.file_path, path=args.file_path, is_directory=True, details=_GenerateApiFileDetails([])) return ApiGetFileDetailsResult(file=api_file) path_type, components = rdf_objects.ParseCategorizedPath(args.file_path) client_id = str(args.client_id) try: path_info = data_store.REL_DB.ReadPathInfo( client_id=client_id, path_type=path_type, components=components, timestamp=args.timestamp) except db.UnknownPathError: raise FileNotFoundError( client_id=client_id, path_type=path_type, components=components) last_collection_pi = file_store.GetLastCollectionPathInfo( db.ClientPath.FromPathInfo(client_id, path_info), max_timestamp=args.timestamp) history = data_store.REL_DB.ReadPathInfoHistory( client_id=client_id, path_type=path_type, components=components, cutoff=args.timestamp) history.reverse() # It might be the case that we do not have any history about the file, but # we have some information because it is an implicit path. if not history: history = [path_info] file_obj = ApiFile( name=components[-1], path=rdf_objects.ToCategorizedPath(path_type, components), stat=path_info.stat_entry, hash=path_info.hash_entry, details=_GenerateApiFileDetails(history), is_directory=path_info.directory, age=path_info.timestamp, ) if last_collection_pi: file_obj.last_collected = last_collection_pi.timestamp file_obj.last_collected_size = last_collection_pi.hash_entry.num_bytes return ApiGetFileDetailsResult(file=file_obj) class ApiListFilesArgs(rdf_structs.RDFProtoStruct): protobuf = vfs_pb2.ApiListFilesArgs rdf_deps = [ client.ApiClientId, rdfvalue.RDFDatetime, ] class ApiListFilesResult(rdf_structs.RDFProtoStruct): protobuf = vfs_pb2.ApiListFilesResult rdf_deps = [ ApiFile, ] class ApiListFilesHandler(api_call_handler_base.ApiCallHandler): """Retrieves the child files for a given file.""" args_type = ApiListFilesArgs result_type = ApiListFilesResult def _GetRootChildren(self, args, context=None): client_id = str(args.client_id) items = [] fs_item = ApiFile() fs_item.name = "fs" fs_item.path = "fs" fs_item.is_directory = True items.append(fs_item) temp_item = ApiFile() temp_item.name = "temp" temp_item.path = "temp" temp_item.is_directory = True items.append(temp_item) if data_store_utils.GetClientOs(client_id) == "Windows": registry_item = ApiFile() registry_item.name = "registry" registry_item.path = "registry" registry_item.is_directory = True items.append(registry_item) if args.count: items = items[args.offset:args.offset + args.count] else: items = items[args.offset:] return ApiListFilesResult(items=items) def _GetFilesystemChildren(self, args): items = [] ntfs_item = ApiFile() ntfs_item.name = "ntfs" ntfs_item.path = "fs/ntfs" ntfs_item.is_directory = True items.append(ntfs_item) os_item = ApiFile() os_item.name = "os" os_item.path = "fs/os" os_item.is_directory = True items.append(os_item) tsk_item = ApiFile() tsk_item.name = "tsk" tsk_item.path = "fs/tsk" tsk_item.is_directory = True items.append(tsk_item) if args.count: items = items[args.offset:args.offset + args.count] else: items = items[args.offset:] return ApiListFilesResult(items=items) def Handle(self, args, context=None): if not args.file_path or args.file_path == "/": return self._GetRootChildren(args, context=context) if args.file_path == "fs": return self._GetFilesystemChildren(args) path_type, components = rdf_objects.ParseCategorizedPath(args.file_path) child_path_infos = data_store.REL_DB.ListChildPathInfos( client_id=args.client_id.ToString(), path_type=path_type, components=components, timestamp=args.timestamp) items = [] for child_path_info in child_path_infos: if args.directories_only and not child_path_info.directory: continue child_item = ApiFile() child_item.name = child_path_info.basename if path_type == rdf_objects.PathInfo.PathType.OS: prefix = "fs/os/" elif path_type == rdf_objects.PathInfo.PathType.TSK: prefix = "fs/tsk/" elif path_type == rdf_objects.PathInfo.PathType.NTFS: prefix = "fs/ntfs/" elif path_type == rdf_objects.PathInfo.PathType.REGISTRY: prefix = "registry/" elif path_type == rdf_objects.PathInfo.PathType.TEMP: prefix = "temp/" child_item.path = prefix + "/".join(child_path_info.components) # TODO(hanuszczak): `PathInfo#directory` tells us whether given path has # ever been observed as a directory. Is this what we want here or should # we use `st_mode` information instead? child_item.is_directory = child_path_info.directory if child_path_info.stat_entry: child_item.stat = child_path_info.stat_entry child_item.age = child_path_info.timestamp if child_path_info.last_hash_entry_timestamp: child_item.last_collected = child_path_info.last_hash_entry_timestamp child_item.last_collected_size = child_path_info.hash_entry.num_bytes items.append(child_item) # TODO(hanuszczak): Instead of getting the whole list from the database and # then filtering the results we should do the filtering directly in the # database query. if args.filter: pattern = re.compile(args.filter, re.IGNORECASE) is_matching = lambda item: pattern.search(item.name) items = list(filter(is_matching, items)) items.sort(key=lambda item: item.path) if args.count: items = items[args.offset:args.offset + args.count] else: items = items[args.offset:] return ApiListFilesResult(items=items) class ApiGetFileTextArgs(rdf_structs.RDFProtoStruct): protobuf = vfs_pb2.ApiGetFileTextArgs rdf_deps = [ client.ApiClientId, rdfvalue.RDFDatetime, ] class ApiGetFileTextResult(rdf_structs.RDFProtoStruct): protobuf = vfs_pb2.ApiGetFileTextResult class ApiGetFileTextHandler(api_call_handler_base.ApiCallHandler): """Retrieves the text for a given file.""" args_type = ApiGetFileTextArgs result_type = ApiGetFileTextResult def _Decode(self, codec_name, data): """Decode data with the given codec name.""" try: return data.decode(codec_name, "replace") except LookupError: raise RuntimeError("Codec could not be found.") except AssertionError: raise RuntimeError("Codec failed to decode") def Handle(self, args, context=None): ValidateVfsPath(args.file_path) path_type, components = rdf_objects.ParseCategorizedPath(args.file_path) client_path = db.ClientPath(str(args.client_id), path_type, components) try: fd = file_store.OpenFile(client_path, max_timestamp=args.timestamp) except file_store.FileHasNoContentError: raise FileContentNotFoundError(args.client_id, path_type, components, args.timestamp) fd.seek(args.offset) # No need to protect against args.length == 0 case and large files: # file_store logic has all necessary checks in place. byte_content = fd.read(args.length or None) if args.encoding: encoding = args.encoding.name.lower() else: encoding = ApiGetFileTextArgs.Encoding.UTF_8.name.lower() text_content = self._Decode(encoding, byte_content) return ApiGetFileTextResult(total_size=fd.size, content=text_content) class ApiGetFileBlobArgs(rdf_structs.RDFProtoStruct): protobuf = vfs_pb2.ApiGetFileBlobArgs rdf_deps = [ client.ApiClientId, rdfvalue.RDFDatetime, ] class ApiGetFileBlobHandler(api_call_handler_base.ApiCallHandler): """Retrieves the byte content for a given file.""" args_type = ApiGetFileBlobArgs CHUNK_SIZE = 1024 * 1024 * 4 def _GenerateFile(self, file_obj, offset, length): file_obj.seek(offset) for start in range(offset, offset + length, self.CHUNK_SIZE): yield file_obj.read(min(self.CHUNK_SIZE, offset + length - start)) def _WrapContentGenerator(self, generator, args, username): try: for item in generator: yield item except Exception as e: path_type, components = rdf_objects.ParseCategorizedPath(args.file_path) vfs_file_ref = rdf_objects.VfsFileReference( client_id=args.client_id, path_type=path_type, path_components=components) object_reference = rdf_objects.ObjectReference( reference_type=rdf_objects.ObjectReference.Type.VFS_FILE, vfs_file=vfs_file_ref) notification.Notify( username, rdf_objects.UserNotification.Type.TYPE_FILE_BLOB_FETCH_FAILED, "File blob fetch failed for path %s on client %s: %s" % (args.client_id, args.file_path, e), object_reference) raise def Handle(self, args, context=None): ValidateVfsPath(args.file_path) path_type, components = rdf_objects.ParseCategorizedPath(args.file_path) client_path = db.ClientPath(str(args.client_id), path_type, components) try: file_obj = file_store.OpenFile(client_path, max_timestamp=args.timestamp) except file_store.FileNotFoundError: raise FileNotFoundError(args.client_id, path_type, components) except file_store.FileHasNoContentError: raise FileContentNotFoundError(args.client_id, path_type, components, args.timestamp) size = max(0, file_obj.size - args.offset) if args.length and args.length < size: size = args.length generator = self._WrapContentGenerator( self._GenerateFile(file_obj, args.offset, size), args, context.username) return api_call_handler_base.ApiBinaryStream( filename=components[-1], content_generator=generator, content_length=size) class ApiGetFileVersionTimesArgs(rdf_structs.RDFProtoStruct): protobuf = vfs_pb2.ApiGetFileVersionTimesArgs rdf_deps = [ client.ApiClientId, ] class ApiGetFileVersionTimesResult(rdf_structs.RDFProtoStruct): protobuf = vfs_pb2.ApiGetFileVersionTimesResult rdf_deps = [ rdfvalue.RDFDatetime, ] class ApiGetFileVersionTimesHandler(api_call_handler_base.ApiCallHandler): """Retrieves the list of version times of the given file.""" args_type = ApiGetFileVersionTimesArgs result_type = ApiGetFileVersionTimesResult def Handle(self, args, context=None): ValidateVfsPath(args.file_path) try: path_type, components = rdf_objects.ParseCategorizedPath( args.file_path.rstrip("/")) except ValueError: # If the path does not point to a file (i.e. "fs"), just return an # empty response. return ApiGetFileVersionTimesResult(times=[]) history = data_store.REL_DB.ReadPathInfoHistory( str(args.client_id), path_type, components) times = reversed([pi.timestamp for pi in history]) return ApiGetFileVersionTimesResult(times=times) class ApiGetFileDownloadCommandArgs(rdf_structs.RDFProtoStruct): protobuf = vfs_pb2.ApiGetFileDownloadCommandArgs rdf_deps = [ client.ApiClientId, ] class ApiGetFileDownloadCommandResult(rdf_structs.RDFProtoStruct): protobuf = vfs_pb2.ApiGetFileDownloadCommandResult class ApiGetFileDownloadCommandHandler(api_call_handler_base.ApiCallHandler): """Retrieves the export command for a given file.""" args_type = ApiGetFileDownloadCommandArgs result_type = ApiGetFileDownloadCommandResult def Handle(self, args, context=None): ValidateVfsPath(args.file_path) output_fname = os.path.basename(args.file_path) code_to_execute = ( """grrapi.Client("%s").File(r\"\"\"%s\"\"\").GetBlob().""" """WriteToFile("./%s")""") % (args.client_id, args.file_path, output_fname) export_command = u" ".join([ config.CONFIG["AdminUI.export_command"], "--exec_code", utils.ShellQuote(code_to_execute) ]) return ApiGetFileDownloadCommandResult(command=export_command) class ApiListKnownEncodingsResult(rdf_structs.RDFProtoStruct): protobuf = vfs_pb2.ApiListKnownEncodingsResult class ApiListKnownEncodingsHandler(api_call_handler_base.ApiCallHandler): """Retrieves available file encodings.""" result_type = ApiListKnownEncodingsResult def Handle(self, args, context=None): encodings = sorted(ApiGetFileTextArgs.Encoding.enum_dict.keys()) return ApiListKnownEncodingsResult(encodings=encodings) class ApiCreateVfsRefreshOperationArgs(rdf_structs.RDFProtoStruct): """Arguments for updating a VFS path.""" protobuf = vfs_pb2.ApiCreateVfsRefreshOperationArgs rdf_deps = [ client.ApiClientId, ] class ApiCreateVfsRefreshOperationResult(rdf_structs.RDFProtoStruct): """Can be immediately returned to poll the status.""" protobuf = vfs_pb2.ApiCreateVfsRefreshOperationResult class ApiCreateVfsRefreshOperationHandler(api_call_handler_base.ApiCallHandler): """Creates a new refresh operation for a given VFS path. This effectively triggers a refresh of a given VFS path. Refresh status can be monitored by polling the returned URL of the operation. """ args_type = ApiCreateVfsRefreshOperationArgs result_type = ApiCreateVfsRefreshOperationResult def _FindPathspec(self, args): path_type, components = rdf_objects.ParseCategorizedPath( args.file_path.rstrip("/")) components_copy = components[:] all_components = [] while components_copy: all_components.append(components_copy) components_copy = components_copy[:-1] res = data_store.REL_DB.ReadPathInfos( str(args.client_id), path_type, all_components) for k in sorted(res, key=len, reverse=True): path_info = res[k] if path_info is None: raise FileNotFoundError(args.client_id, path_type, components) if path_info.stat_entry and path_info.stat_entry.pathspec: ps = path_info.stat_entry.pathspec if len(k) < len(components): new_path = utils.JoinPath(*components[len(k):]) ps.Append( rdf_paths.PathSpec(path=new_path, pathtype=ps.last.pathtype)) return ps # We don't have any pathspec in the database so we just send the path we # have with the correct path type and hope for the best. pathspec = rdf_paths.PathSpec(path="/" + "/".join(components)) if path_type == rdf_objects.PathInfo.PathType.TSK: pathspec.pathtype = pathspec.PathType.TSK elif path_type == rdf_objects.PathInfo.PathType.NTFS: pathspec.pathtype = pathspec.PathType.NTFS elif path_type == rdf_objects.PathInfo.PathType.OS: pathspec.pathtype = pathspec.PathType.OS elif path_type == rdf_objects.PathInfo.PathType.REGISTRY: pathspec.pathtype = pathspec.PathType.REGISTRY elif path_type == rdf_objects.PathInfo.PathType.TEMP: pathspec.pathtype = pathspec.PathType.TMPFILE else: raise ValueError("Invalid path_type: %r" % path_type) return pathspec def Handle(self, args, context=None): if args.max_depth == 1: flow_args = filesystem.ListDirectoryArgs( pathspec=self._FindPathspec(args)) flow_cls = filesystem.ListDirectory else: flow_args = filesystem.RecursiveListDirectoryArgs( pathspec=self._FindPathspec(args), max_depth=args.max_depth) flow_cls = filesystem.RecursiveListDirectory flow_id = flow.StartFlow( client_id=str(args.client_id), flow_cls=flow_cls, flow_args=flow_args, creator=context.username if context else None) return ApiCreateVfsRefreshOperationResult(operation_id=flow_id) class ApiGetVfsRefreshOperationStateArgs(rdf_structs.RDFProtoStruct): """Arguments for checking a refresh operation.""" protobuf = vfs_pb2.ApiGetVfsRefreshOperationStateArgs rdf_deps = [ client.ApiClientId, ] class ApiGetVfsRefreshOperationStateResult(rdf_structs.RDFProtoStruct): """Indicates the state of a refresh operation.""" protobuf = vfs_pb2.ApiGetVfsRefreshOperationStateResult class ApiGetVfsRefreshOperationStateHandler(api_call_handler_base.ApiCallHandler ): """Retrieves the state of the refresh operation specified.""" args_type = ApiGetVfsRefreshOperationStateArgs result_type = ApiGetVfsRefreshOperationStateResult def _RaiseOperationNotFoundError(self, args): raise VfsRefreshOperationNotFoundError("Operation with id %s not found" % args.operation_id) def Handle(self, args, context=None): try: rdf_flow = data_store.REL_DB.ReadFlowObject( str(args.client_id), str(args.operation_id)) except db.UnknownFlowError: self._RaiseOperationNotFoundError(args) if rdf_flow.flow_class_name not in [ "RecursiveListDirectory", "ListDirectory" ]: self._RaiseOperationNotFoundError(args) complete = rdf_flow.flow_state != "RUNNING" result = ApiGetVfsRefreshOperationStateResult() if complete: result.state = ApiGetVfsRefreshOperationStateResult.State.FINISHED else: result.state = ApiGetVfsRefreshOperationStateResult.State.RUNNING return result def _GetTimelineStatEntries(api_client_id, file_path, with_history=True): """Gets timeline entries from REL_DB.""" path_type, components = rdf_objects.ParseCategorizedPath(file_path) client_id = str(api_client_id) try: root_path_info = data_store.REL_DB.ReadPathInfo(client_id, path_type, components) except db.UnknownPathError: return path_infos = [] for path_info in itertools.chain( [root_path_info], data_store.REL_DB.ListDescendantPathInfos(client_id, path_type, components), ): # TODO(user): this is to keep the compatibility with current # AFF4 implementation. Check if this check is needed. if path_info.directory: continue categorized_path = rdf_objects.ToCategorizedPath(path_info.path_type, path_info.components) if with_history: path_infos.append(path_info) else: yield categorized_path, path_info.stat_entry, path_info.hash_entry if with_history: hist_path_infos = data_store.REL_DB.ReadPathInfosHistories( client_id, path_type, [tuple(pi.components) for pi in path_infos]) for path_info in itertools.chain.from_iterable(hist_path_infos.values()): categorized_path = rdf_objects.ToCategorizedPath(path_info.path_type, path_info.components) yield categorized_path, path_info.stat_entry, path_info.hash_entry def _GetTimelineItems(client_id, file_path): """Gets timeline items for a given client id and path.""" items = [] for file_path, stat_entry, _ in _GetTimelineStatEntries( client_id, file_path, with_history=True): # It may be that for a given timestamp only hash entry is available, we're # skipping those. if stat_entry is None: continue # Add a new event for each MAC time if it exists. for c in "mac": timestamp = getattr(stat_entry, "st_%stime" % c) if timestamp is None: continue item = ApiVfsTimelineItem(timestamp=timestamp) # Remove aff4:/<client_id> to have a more concise path to the # subject. item.file_path = file_path if c == "m": item.action = ApiVfsTimelineItem.FileActionType.MODIFICATION elif c == "a": item.action = ApiVfsTimelineItem.FileActionType.ACCESS elif c == "c": item.action = ApiVfsTimelineItem.FileActionType.METADATA_CHANGED items.append(item) return sorted(items, key=lambda x: x.timestamp, reverse=True) class ApiVfsTimelineItem(rdf_structs.RDFProtoStruct): protobuf = vfs_pb2.ApiVfsTimelineItem rdf_deps = [ rdfvalue.RDFDatetime, ] class ApiGetVfsTimelineArgs(rdf_structs.RDFProtoStruct): protobuf = vfs_pb2.ApiGetVfsTimelineArgs rdf_deps = [ client.ApiClientId, ] class ApiGetVfsTimelineResult(rdf_structs.RDFProtoStruct): protobuf = vfs_pb2.ApiGetVfsTimelineResult rdf_deps = [ ApiVfsTimelineItem, ] class ApiGetVfsTimelineHandler(api_call_handler_base.ApiCallHandler): """Retrieves the timeline for a given file path.""" args_type = ApiGetVfsTimelineArgs result_type = ApiGetVfsTimelineResult def Handle(self, args, context=None): ValidateVfsPath(args.file_path) items = _GetTimelineItems(args.client_id, args.file_path) return ApiGetVfsTimelineResult(items=items) class ApiGetVfsTimelineAsCsvArgs(rdf_structs.RDFProtoStruct): protobuf = vfs_pb2.ApiGetVfsTimelineAsCsvArgs rdf_deps = [ client.ApiClientId, ] class ApiGetVfsTimelineAsCsvHandler(api_call_handler_base.ApiCallHandler): """Exports the timeline for a given file path.""" args_type = ApiGetVfsTimelineAsCsvArgs CHUNK_SIZE = 1000 def _GenerateDefaultExport(self, items): writer = csv.Writer() # Write header. Since we do not stick to a specific timeline format, we # can export a format suited for TimeSketch import. writer.WriteRow([u"Timestamp", u"Datetime", u"Message", u"Timestamp_desc"]) for start in range(0, len(items), self.CHUNK_SIZE): for item in items[start:start + self.CHUNK_SIZE]: writer.WriteRow([ str(item.timestamp.AsMicrosecondsSinceEpoch()), str(item.timestamp), item.file_path, str(item.action), ]) yield writer.Content().encode("utf-8") writer = csv.Writer() def _HandleDefaultFormat(self, args): items = _GetTimelineItems(args.client_id, args.file_path) return api_call_handler_base.ApiBinaryStream( "%s_%s_timeline" % (args.client_id, os.path.basename(args.file_path)), content_generator=self._GenerateDefaultExport(items)) def _GenerateBodyExport(self, file_infos): for path, st, hash_v in file_infos: if st is None: continue writer = csv.Writer(delimiter=u"|") if hash_v and hash_v.md5: hash_str = hash_v.md5.HexDigest() else: hash_str = u"" # Details about Body format: # https://wiki.sleuthkit.org/index.php?title=Body_file # MD5|name|inode|mode_as_string|UID|GID|size|atime|mtime|ctime|crtime writer.WriteRow([ hash_str, path, str(st.st_ino), str(st.st_mode), str(st.st_uid), str(st.st_gid), str(st.st_size), str(int(st.st_atime or 0)), str(int(st.st_mtime or 0)), str(int(st.st_ctime or 0)), str(int(st.st_btime or 0)), ]) yield writer.Content().encode("utf-8") def _HandleBodyFormat(self, args): file_infos = _GetTimelineStatEntries( args.client_id, args.file_path, with_history=False) return api_call_handler_base.ApiBinaryStream( "%s_%s_timeline" % (args.client_id, os.path.basename(args.file_path)), content_generator=self._GenerateBodyExport(file_infos)) def Handle(self, args, context=None): ValidateVfsPath(args.file_path) if args.format == args.Format.UNSET or args.format == args.Format.GRR: return self._HandleDefaultFormat(args) elif args.format == args.Format.BODY: return self._HandleBodyFormat(args) else: raise ValueError("Unexpected file format: %s" % args.format) class ApiUpdateVfsFileContentArgs(rdf_structs.RDFProtoStruct): """Arguments for updating a VFS file.""" protobuf = vfs_pb2.ApiUpdateVfsFileContentArgs rdf_deps = [ client.ApiClientId, ] class ApiUpdateVfsFileContentResult(rdf_structs.RDFProtoStruct): """Can be immediately returned to poll the status.""" protobuf = vfs_pb2.ApiUpdateVfsFileContentResult class ApiUpdateVfsFileContentHandler(api_call_handler_base.ApiCallHandler): """Creates a file update operation for a given VFS file. Triggers a flow to refresh a given VFS file. The refresh status can be monitored by polling the operation id. """ args_type = ApiUpdateVfsFileContentArgs result_type = ApiUpdateVfsFileContentResult def Handle(self, args, context=None): path_type, components = rdf_objects.ParseCategorizedPath(args.file_path) path_info = data_store.REL_DB.ReadPathInfo( str(args.client_id), path_type, components) if (not path_info or not path_info.stat_entry or not path_info.stat_entry.pathspec): raise FileNotFoundError( client_id=str(args.client_id), path_type=path_type, components=components) flow_args = transfer.MultiGetFileArgs( pathspecs=[path_info.stat_entry.pathspec]) flow_id = flow.StartFlow( client_id=str(args.client_id), flow_cls=transfer.MultiGetFile, flow_args=flow_args, creator=context.username) return ApiUpdateVfsFileContentResult(operation_id=flow_id) class ApiGetVfsFileContentUpdateStateArgs(rdf_structs.RDFProtoStruct): """Arguments for checking a file content update operation.""" protobuf = vfs_pb2.ApiGetVfsFileContentUpdateStateArgs rdf_deps = [ client.ApiClientId, ] class ApiGetVfsFileContentUpdateStateResult(rdf_structs.RDFProtoStruct): """Indicates the state of a file content update operation.""" protobuf = vfs_pb2.ApiGetVfsFileContentUpdateStateResult class ApiGetVfsFileContentUpdateStateHandler( api_call_handler_base.ApiCallHandler): """Retrieves the state of the update operation specified.""" args_type = ApiGetVfsFileContentUpdateStateArgs result_type = ApiGetVfsFileContentUpdateStateResult def Handle(self, args, context=None): try: rdf_flow = data_store.REL_DB.ReadFlowObject( str(args.client_id), str(args.operation_id)) except db.UnknownFlowError: raise VfsFileContentUpdateNotFoundError("Operation with id %s not found" % args.operation_id) if rdf_flow.flow_class_name != "MultiGetFile": raise VfsFileContentUpdateNotFoundError("Operation with id %s not found" % args.operation_id) result = ApiGetVfsFileContentUpdateStateResult() if rdf_flow.flow_state == "RUNNING": result.state = ApiGetVfsFileContentUpdateStateResult.State.RUNNING else: result.state = ApiGetVfsFileContentUpdateStateResult.State.FINISHED return result class ApiGetVfsFilesArchiveArgs(rdf_structs.RDFProtoStruct): """Arguments for GetVfsFilesArchive handler.""" protobuf = vfs_pb2.ApiGetVfsFilesArchiveArgs rdf_deps = [ client.ApiClientId, rdfvalue.RDFDatetime, ] class ApiGetVfsFilesArchiveHandler(api_call_handler_base.ApiCallHandler): """Streams archive with files collected in the VFS of a client.""" args_type = ApiGetVfsFilesArchiveArgs def _GenerateContent(self, client_id, start_paths, timestamp, path_prefix): client_paths = [] for start_path in start_paths: path_type, components = rdf_objects.ParseCategorizedPath(start_path) for pi in data_store.REL_DB.ListDescendantPathInfos( client_id, path_type, components): if pi.directory: continue client_paths.append(db.ClientPath.FromPathInfo(client_id, pi)) archive_generator = utils.StreamingZipGenerator( compression=zipfile.ZIP_DEFLATED) for chunk in file_store.StreamFilesChunks( client_paths, max_timestamp=timestamp): if chunk.chunk_index == 0: content_path = os.path.join(path_prefix, chunk.client_path.vfs_path) # TODO(user): Export meaningful file metadata. st = os.stat_result((0o644, 0, 0, 0, 0, 0, chunk.total_size, 0, 0, 0)) yield archive_generator.WriteFileHeader(content_path, st=st) yield archive_generator.WriteFileChunk(chunk.data) if chunk.chunk_index == chunk.total_chunks - 1: yield archive_generator.WriteFileFooter() yield archive_generator.Close() def _WrapContentGenerator(self, generator, args, username): if args.file_path: path_type, components = rdf_objects.ParseCategorizedPath(args.file_path) vfs_file_ref = rdf_objects.VfsFileReference( client_id=args.client_id, path_type=path_type, path_components=components) else: vfs_file_ref = rdf_objects.VfsFileReference(client_id=args.client_id) object_reference = rdf_objects.ObjectReference( reference_type=rdf_objects.ObjectReference.Type.VFS_FILE, vfs_file=vfs_file_ref) try: for item in generator: yield item notification.Notify( username, rdf_objects.UserNotification.Type.TYPE_FILE_ARCHIVE_GENERATED, "Downloaded an archive of folder %s from client %s." % (args.file_path, args.client_id), object_reference) except Exception as e: notification.Notify( username, rdf_objects.UserNotification.Type.TYPE_FILE_ARCHIVE_GENERATION_FAILED, "Archive generation failed for folder %s on client %s: %s" % (args.file_path, args.client_id, e), object_reference) raise def Handle(self, args, context=None): client_id = str(args.client_id) path = args.file_path if not path: start_paths = ["fs/os", "fs/tsk", "registry", "temp", "fs/ntfs"] prefix = "vfs_" + re.sub("[^0-9a-zA-Z]", "_", client_id) else: ValidateVfsPath(path) if path.rstrip("/") == "fs": start_paths = ["fs/os", "fs/tsk", "fs/ntfs"] else: start_paths = [path] prefix = "vfs_" + re.sub("[^0-9a-zA-Z]", "_", client_id + "_" + path).strip("_") content_generator = self._WrapContentGenerator( self._GenerateContent(client_id, start_paths, args.timestamp, prefix), args, context.username) return api_call_handler_base.ApiBinaryStream( prefix + ".zip", content_generator=content_generator) class ApiGetFileDecodersArgs(rdf_structs.RDFProtoStruct): protobuf = vfs_pb2.ApiGetFileDecodersArgs rdf_deps = [ client.ApiClientId, ] class ApiGetFileDecodersResult(rdf_structs.RDFProtoStruct): protobuf = vfs_pb2.ApiGetFileDecodersResult rdf_deps = [] class ApiGetFileDecodersHandler(api_call_handler_base.ApiCallHandler): """An API handler for listing decoders available for specified file.""" def Handle(self, args, context=None): result = ApiGetFileDecodersResult() path_type, components = rdf_objects.ParseCategorizedPath(args.file_path) client_path = db.ClientPath( client_id=str(args.client_id), path_type=path_type, components=components) for decoder_name in decoders.FACTORY.Names(): decoder = decoders.FACTORY.Create(decoder_name) filedesc = file_store.OpenFile(client_path) filectx = context_lib.NullContext(filedesc) with filectx as filedesc: if decoder.Check(filedesc): result.decoder_names.append(decoder_name) return result class ApiGetDecodedFileArgs(rdf_structs.RDFProtoStruct): protobuf = vfs_pb2.ApiGetDecodedFileArgs rdf_deps = [ client.ApiClientId, ] class ApiGetDecodedFileHandler(api_call_handler_base.ApiCallHandler): """An API handler for decoding specified file.""" def Handle(self, args, context=None): decoder = decoders.FACTORY.Create(args.decoder_name) path_type, components = rdf_objects.ParseCategorizedPath(args.file_path) client_path = db.ClientPath(str(args.client_id), path_type, components) fd = file_store.OpenFile(client_path) return api_call_handler_base.ApiBinaryStream( filename=client_path.components[-1], content_generator=decoder.Decode(fd))
32.484326
106
0.707986
c66368ea61eae3262a14053e00a423b6b83ad28d
12,008
py
Python
built-in/TensorFlow/Research/recommendation/Wide&Deep_for_TensorFlow/widedeep/WideDeep_fp16_huifeng.py
Huawei-Ascend/modelzoo
df51ed9c1d6dbde1deef63f2a037a369f8554406
[ "Apache-2.0" ]
null
null
null
built-in/TensorFlow/Research/recommendation/Wide&Deep_for_TensorFlow/widedeep/WideDeep_fp16_huifeng.py
Huawei-Ascend/modelzoo
df51ed9c1d6dbde1deef63f2a037a369f8554406
[ "Apache-2.0" ]
3
2021-03-31T20:15:40.000Z
2022-02-09T23:50:46.000Z
built-in/TensorFlow/Research/recommendation/Wide&Deep_for_TensorFlow/widedeep/WideDeep_fp16_huifeng.py
Huawei-Ascend/modelzoo
df51ed9c1d6dbde1deef63f2a037a369f8554406
[ "Apache-2.0" ]
null
null
null
"""DeepFM related model""" from __future__ import print_function import os import sys import pickle import tensorflow as tf from widedeep.tf_util import build_optimizer, init_var_map, \ get_field_index, get_field_num, split_mask, split_param, sum_multi_hot, \ activate from npu_bridge.estimator import npu_ops from npu_bridge.estimator.npu.npu_optimizer import NPUDistributedOptimizer from npu_bridge.estimator.npu.npu_loss_scale_optimizer import NPULossScaleOptimizer from npu_bridge.estimator.npu.npu_loss_scale_manager import FixedLossScaleManager from npu_bridge.estimator.npu.npu_loss_scale_manager import ExponentialUpdateLossScaleManager from npu_bridge.hccl import hccl_ops #from mindspore.ops import operations as P rank_size = int(os.getenv('RANK_SIZE')) class WideDeep: """support performing mean pooling Operation on multi-hot feature. dataset_argv: e.g. [10000, 17, [False, ...,True,True], 10] """ def __init__(self, graph, dataset_argv, architect_argv, init_argv, ptmzr_argv, reg_argv, _input_data, loss_mode='full', merge_multi_hot=False, cross_layer=False, batch_norm=False): self.graph = graph #self.MEloss = P.SigmoidCrossEntropyWithLogits() with self.graph.as_default(): #with tf.variable_scope('FMNNMG') as scope: (input_dim, input_dim4lookup, self.multi_hot_flags, self.multi_hot_len) = dataset_argv self.one_hot_flags = [not flag for flag in self.multi_hot_flags] embed_size, layer_dims, act_func = architect_argv keep_prob, _lambda = reg_argv self.num_onehot = sum(self.one_hot_flags) self.num_multihot = sum(self.multi_hot_flags) / self.multi_hot_len if merge_multi_hot: self.embed_dim = (self.num_multihot + self.num_onehot) * embed_size else: self.embed_dim = input_dim4lookup * embed_size self.all_layer_dims = [self.embed_dim] + layer_dims + [1] self.log = ('input dim: %d\nnum inputs: %d\nembed size(each): %d\n' 'embedding layer: %d\nlayers: %s\nactivate: %s\n' 'keep_prob: %g\nl2(lambda): %g\nmerge_multi_hot: %s\n' % (input_dim, input_dim4lookup, embed_size, self.embed_dim, self.all_layer_dims, act_func, keep_prob, _lambda, merge_multi_hot)) with tf.variable_scope("embedding", reuse=tf.AUTO_REUSE): self.embed_v = tf.get_variable('V', shape=[input_dim, embed_size], initializer=tf.random_uniform_initializer(-0.01, 0.01), dtype=tf.float32, collections=[tf.GraphKeys.GLOBAL_VARIABLES, "deep", "embedding"]) with tf.variable_scope("wide", reuse=tf.AUTO_REUSE): self.wide_w = tf.get_variable('wide_w', shape=[input_dim, 1], initializer=tf.random_uniform_initializer(-0.01, 0.01), dtype=tf.float32, collections=[tf.GraphKeys.GLOBAL_VARIABLES, "wide", "wide_w"]) self.wide_b = tf.get_variable('wide_b', [1], initializer = tf.random_uniform_initializer(-0.01, 0.01), dtype=tf.float32, collections=[tf.GraphKeys.GLOBAL_VARIABLES, "wide", "wide_b"]) with tf.variable_scope("mlp", reuse=tf.AUTO_REUSE): self.h_w, self.h_b = [], [] for i in range(len(self.all_layer_dims) - 1): self.h_w.append(tf.get_variable('h%d_w' % (i + 1), shape=self.all_layer_dims[i: i + 2], initializer=tf.random_uniform_initializer(-0.01, 0.01), dtype=tf.float32, collections=[tf.GraphKeys.GLOBAL_VARIABLES, "deep", "mlp_wts"])) self.h_b.append( tf.get_variable('h%d_b' % (i + 1), shape=[self.all_layer_dims[i + 1]], initializer=tf.zeros_initializer, dtype=tf.float32, collections=[tf.GraphKeys.GLOBAL_VARIABLES, "deep", "mlp_bias"])) self.wt_hldr = _input_data[2] self.id_hldr = _input_data[1] self.lbl_hldr = _input_data[0] print("_input_data[0]== self.lbl_hldr", self.lbl_hldr) wideout = self.wide_forward(self.wt_hldr, self.id_hldr) y, vx_embeds = self.forward( self.wt_hldr, self.id_hldr, act_func, keep_prob, training=True, merge_multi_hot=merge_multi_hot, cross_layer=cross_layer, batch_norm=batch_norm) y = y + wideout self.train_preds = tf.sigmoid(y, name='predicitons') basic_loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=y, labels=self.lbl_hldr) self.wide_loss = tf.reduce_mean(basic_loss) self.deep_loss = tf.reduce_mean(basic_loss) + _lambda * tf.nn.l2_loss(self.embed_v) self.l2_loss = tf.constant([0]) #self.loss self.log_loss = basic_loss self.eval_wt_hldr = tf.placeholder(tf.float32, [None, input_dim4lookup], name='wt') self.eval_id_hldr = tf.placeholder(tf.int32, [None, input_dim4lookup], name='id') eval_wideout= self.wide_forward(self.eval_wt_hldr, self.eval_id_hldr) eval_y, eval_vx_embed = self.forward( self.eval_wt_hldr, self.eval_id_hldr, act_func, keep_prob, training=False, merge_multi_hot=merge_multi_hot, cross_layer=cross_layer, batch_norm=batch_norm) eval_y = eval_y + eval_wideout self.eval_preds = tf.sigmoid(eval_y, name='predictionNode') opt_deep, lr_deep, eps_deep, decay_rate_deep, decay_step_deep = ptmzr_argv[0] opt_wide, wide_lr, wide_dc, wide_l1, wide_l2 = ptmzr_argv[1] update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) with tf.control_dependencies(update_ops): loss_scale_manager = FixedLossScaleManager(loss_scale=1000.0) loss_scale_manager2 = FixedLossScaleManager(loss_scale=1000.0) self.wide_ptmzr = tf.train.FtrlOptimizer(learning_rate=wide_lr, initial_accumulator_value=wide_dc, l1_regularization_strength=wide_l1, l2_regularization_strength=wide_l2) if rank_size > 1: self.wide_ptmzr = NPULossScaleOptimizer(self.wide_ptmzr, loss_scale_manager, is_distributed=True) grads_w = self.wide_ptmzr.compute_gradients(self.wide_loss, var_list=tf.get_collection('wide')) else: self.wide_ptmzr = NPULossScaleOptimizer(self.wide_ptmzr, loss_scale_manager) self.wide_ptmzr = self.wide_ptmzr.minimize(self.wide_loss,var_list=tf.get_collection("wide")) self.deep_optimzer = tf.train.AdamOptimizer(learning_rate=lr_deep, epsilon=eps_deep) if rank_size > 1: self.deep_optimzer = NPULossScaleOptimizer(self.deep_optimzer, loss_scale_manager2, is_distributed=True) grads_d = self.deep_optimzer.compute_gradients(self.deep_loss, var_list=tf.get_collection('deep')) else: self.deep_optimzer = NPULossScaleOptimizer(self.deep_optimzer, loss_scale_manager2) self.deep_optimzer = self.deep_optimzer.minimize(self.deep_loss,var_list=tf.get_collection("deep")) if rank_size > 1: avg_grads_w = [] avg_grads_d = [] for grad, var in grads_w: avg_grad = hccl_ops.allreduce(grad, "sum") if grad is not None else None avg_grads_w.append((avg_grad, var)) for grad, var in grads_d: avg_grad = hccl_ops.allreduce(grad, "sum") if grad is not None else None avg_grads_d.append((avg_grad, var)) apply_gradient_op_w = self.wide_ptmzr.apply_gradients(avg_grads_w) apply_gradient_op_d = self.deep_optimzer.apply_gradients(avg_grads_d) self.train_op = tf.group(apply_gradient_op_d, apply_gradient_op_w) else: self.train_op = tf.group(self.deep_optimzer, self.wide_ptmzr) def wide_forward(self, wide_wt, wide_id): wide_mask = tf.expand_dims(wide_wt, axis=2) gather = tf.gather(self.wide_w, wide_id) wide_part = tf.multiply(gather, wide_mask, name="wide_part") wide_output = tf.reshape((tf.reduce_sum(wide_part, axis=1) + self.wide_b), shape=[-1, ], name="wide_out") return wide_output def forward(self, wt_hldr, id_hldr, act_func, keep_prob, training, merge_multi_hot=False, cross_layer=False, batch_norm=False): mask = tf.expand_dims(wt_hldr, 2) if merge_multi_hot and self.num_multihot > 0: one_hot_mask, multi_hot_mask = split_mask( mask, self.multi_hot_flags, self.num_multihot) one_hot_w, multi_hot_w = split_param( self.fm_w, id_hldr, self.multi_hot_flags) one_hot_v, multi_hot_v = split_param( self.fm_v, id_hldr, self.multi_hot_flags) # linear part multi_hot_wx = sum_multi_hot( multi_hot_w, multi_hot_mask, self.num_multihot) one_hot_wx = tf.multiply(one_hot_w, one_hot_mask) wx = tf.concat([one_hot_wx, multi_hot_wx], axis=1) # fm part (reduce multi-hot vector's length to k*1) multi_hot_vx = sum_multi_hot( multi_hot_v, multi_hot_mask, self.num_multihot) one_hot_vx = tf.multiply(one_hot_v, one_hot_mask) vx_embed = tf.concat([one_hot_vx, multi_hot_vx], axis=1) else: # [batch, input_dim4lookup, embed_size] vx_embed = tf.multiply(tf.gather(self.embed_v, id_hldr), mask) hidden_output = tf.reshape(vx_embed, [-1, self.embed_dim])#*512 cross_layer_output = None for i in range(len(self.h_w)): if training: hidden_output = tf.matmul(npu_ops.dropout(activate(act_func, hidden_output), keep_prob=keep_prob), self.h_w[i]) else: hidden_output = tf.matmul(activate(act_func, hidden_output), self.h_w[i]) hidden_output = hidden_output + self.h_b[i] if batch_norm: hidden_output = tf.layers.batch_normalization( hidden_output, training=training) if cross_layer_output is not None: cross_layer_output = tf.concat( [cross_layer_output, hidden_output], 1) else: cross_layer_output = hidden_output if cross_layer and i == len(self.h_w) - 2: hidden_output = cross_layer_output return tf.reshape(hidden_output, [-1, ]), vx_embed def dump(self, model_path): var_map = {'W': self.fm_w.eval(), 'V': self.fm_v.eval(), 'b': self.fm_b.eval()} for i, (h_w_i, h_b_i) in enumerate(zip(self.h_w, self.h_b)): var_map['h%d_w' % (i+1)] = h_w_i.eval() var_map['h%d_b' % (i+1)] = h_b_i.eval() pickle.dump(var_map, open(model_path, 'wb')) print('model dumped at %s' % model_path)
54.09009
128
0.592522
e8a0337c0dbed5a7be9fce9315c04724c42e1edd
3,946
py
Python
tasks/cluster_agent.py
kaarolch/datadog-agent
88d2d9bdc262f3dba3f2b222557f67026bc6f59b
[ "Apache-2.0" ]
null
null
null
tasks/cluster_agent.py
kaarolch/datadog-agent
88d2d9bdc262f3dba3f2b222557f67026bc6f59b
[ "Apache-2.0" ]
null
null
null
tasks/cluster_agent.py
kaarolch/datadog-agent
88d2d9bdc262f3dba3f2b222557f67026bc6f59b
[ "Apache-2.0" ]
null
null
null
""" Cluster Agent tasks """ import glob import os import shutil from invoke import task from invoke.exceptions import Exit from .build_tags import get_build_tags, get_default_build_tags from .cluster_agent_helpers import build_common, clean_common, refresh_assets_common, version_common from .go import deps # constants BIN_PATH = os.path.join(".", "bin", "datadog-cluster-agent") AGENT_TAG = "datadog/cluster_agent:master" @task def build(ctx, rebuild=False, build_include=None, build_exclude=None, race=False, development=True, skip_assets=False): """ Build Cluster Agent Example invokation: inv cluster-agent.build """ build_common( ctx, "cluster-agent.build", BIN_PATH, get_default_build_tags(build="cluster-agent"), "", rebuild, build_include, build_exclude, race, development, skip_assets, ) @task def refresh_assets(ctx, development=True): """ Clean up and refresh cluster agent's assets and config files """ refresh_assets_common(ctx, BIN_PATH, [os.path.join("./Dockerfiles/cluster-agent", "dist")], development) @task def clean(ctx): """ Remove temporary objects and binary artifacts """ clean_common(ctx, "datadog-cluster-agent") @task def integration_tests(ctx, install_deps=False, race=False, remote_docker=False, go_mod="vendor"): """ Run integration tests for cluster-agent """ if install_deps: deps(ctx) # We need docker for the kubeapiserver integration tests tags = get_default_build_tags(build="cluster-agent") + ["docker"] test_args = { "go_mod": go_mod, "go_build_tags": " ".join(get_build_tags(tags, [])), "race_opt": "-race" if race else "", "exec_opts": "", } # since Go 1.13, the -exec flag of go test could add some parameters such as -test.timeout # to the call, we don't want them because while calling invoke below, invoke # thinks that the parameters are for it to interpret. # we're calling an intermediate script which only pass the binary name to the invoke task. if remote_docker: test_args["exec_opts"] = "-exec \"{}/test/integration/dockerize_tests.sh\"".format(os.getcwd()) go_cmd = 'go test -mod={go_mod} {race_opt} -tags "{go_build_tags}" {exec_opts}'.format(**test_args) prefixes = [ "./test/integration/util/kube_apiserver", "./test/integration/util/leaderelection", ] for prefix in prefixes: ctx.run("{} {}".format(go_cmd, prefix)) @task def image_build(ctx, arch='amd64', tag=AGENT_TAG, push=False): """ Build the docker image """ dca_binary = glob.glob(os.path.join(BIN_PATH, "datadog-cluster-agent")) # get the last debian package built if not dca_binary: print("No bin found in {}".format(BIN_PATH)) print("See cluster-agent.build") raise Exit(code=1) latest_file = max(dca_binary, key=os.path.getctime) ctx.run("chmod +x {}".format(latest_file)) build_context = "Dockerfiles/cluster-agent" exec_path = "{}/datadog-cluster-agent.{}".format(build_context, arch) dockerfile_path = "{}/{}/Dockerfile".format(build_context, arch) shutil.copy2(latest_file, exec_path) ctx.run("docker build -t {} {} -f {}".format(tag, build_context, dockerfile_path)) ctx.run("rm {}".format(exec_path)) if push: ctx.run("docker push {}".format(tag)) @task def version(ctx, url_safe=False, git_sha_length=7): """ Get the agent version. url_safe: get the version that is able to be addressed as a url git_sha_length: different versions of git have a different short sha length, use this to explicitly set the version (the windows builder and the default ubuntu version have such an incompatibility) """ version_common(ctx, url_safe, git_sha_length)
29.669173
119
0.665484
1f5bd65c1a5af1d5fe5be81fad946965372b7ce0
906
py
Python
sdk/python/pulumi_aws_native/elasticache/__init__.py
pulumi/pulumi-aws-native
1ae4a4d9c2256b2a79ca536f8d8497b28d10e4c3
[ "Apache-2.0" ]
29
2021-09-30T19:32:07.000Z
2022-03-22T21:06:08.000Z
sdk/python/pulumi_aws_native/elasticache/__init__.py
pulumi/pulumi-aws-native
1ae4a4d9c2256b2a79ca536f8d8497b28d10e4c3
[ "Apache-2.0" ]
232
2021-09-30T19:26:26.000Z
2022-03-31T23:22:06.000Z
sdk/python/pulumi_aws_native/elasticache/__init__.py
pulumi/pulumi-aws-native
1ae4a4d9c2256b2a79ca536f8d8497b28d10e4c3
[ "Apache-2.0" ]
4
2021-11-10T19:42:01.000Z
2022-02-05T10:15:49.000Z
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** from .. import _utilities import typing # Export this package's modules as members: from ._enums import * from .cache_cluster import * from .get_cache_cluster import * from .get_global_replication_group import * from .get_parameter_group import * from .get_replication_group import * from .get_security_group import * from .get_security_group_ingress import * from .get_subnet_group import * from .get_user import * from .get_user_group import * from .global_replication_group import * from .parameter_group import * from .replication_group import * from .security_group import * from .security_group_ingress import * from .subnet_group import * from .user import * from .user_group import * from ._inputs import * from . import outputs
31.241379
80
0.782561
6bb742ab017fc66f54a0717021ebff5ce16a1a66
1,529
py
Python
examples/gen-2/q3_b.py
sesajad/numeric
4aab3642f8311b43fb06535df258246b7ab93f16
[ "MIT" ]
null
null
null
examples/gen-2/q3_b.py
sesajad/numeric
4aab3642f8311b43fb06535df258246b7ab93f16
[ "MIT" ]
null
null
null
examples/gen-2/q3_b.py
sesajad/numeric
4aab3642f8311b43fb06535df258246b7ab93f16
[ "MIT" ]
null
null
null
from numexpr import * from numexpr.math import sin, e #false position method min = -5 max = -3 expr = lambda x : 2*sin(x) - e**x/4 - 1 print('\\[ f(x) = ', expr(Number(1, name='x')) , ' \\]\n\n') print('\\[ \\begin{cases} ') x_min = Number(min, name='x_{\\text{min}}') t_expr = expr(x_min) print('f(x_\\text{min}) = ', t_expr, '=' , t_expr.simplify(2), '=', t_expr.simplify(0)) print('\\\\') x_max = Number(max, name='x_{\\text{max}}') t_expr = expr(x_max) print('f(x_\\text{max}) = ', t_expr, '=' , t_expr.simplify(2), '=', t_expr.simplify(0)) print('\\end{cases} \\]\n\n') def falsepos(min, max, level=1): print('\\[ x_{%d} \\in [%s, %s] \\]' % (level, min, max)) x = max - (max - min)/(expr(max).simplify() - expr(min).simplify())*expr(max).simplify() print('\\[', x , '=', x.simplify(), '\\]') print('\\[ \\rightarrow ', 'x_{%d}' % level, '=', x.simplify(2) ,'\\]') print('\\[ \\rightarrow ', 'x_{%d}' % level, '=', x.simplify(0) ,'\\]') if (abs(max - min).value()/2 <= 0.001): return print('\\[ f(x_{%d})' % level, '=', expr(x.simplify()) ,'\\]') print('\\[ \\rightarrow ', 'f(x_{%d})' % level, '=', expr(x.simplify()).simplify(2) ,'\\]') print('\\[ \\rightarrow ', 'f(x_{%d})' % level, '=', expr(x.simplify()).simplify(0) ,'\\]') if expr(x).value()*expr(min).value() > 0: falsepos(x.simplify(), max.simplify(), level + 1) elif expr(x).value() == 0: return else: falsepos(min.simplify(), x.simplify(), level + 1) falsepos(x_min, x_max)
37.292683
95
0.522564
10eb7e74aa28cf0b6d385124a19edde0a7e06490
7,680
py
Python
test/functional/mining_prioritisetransaction.py
Techcoingithub/techcoin
6914faea0496d16d85f4f11fc1ae2ba05e9143b8
[ "MIT" ]
null
null
null
test/functional/mining_prioritisetransaction.py
Techcoingithub/techcoin
6914faea0496d16d85f4f11fc1ae2ba05e9143b8
[ "MIT" ]
1
2021-11-30T18:41:44.000Z
2022-01-17T17:55:26.000Z
test/functional/mining_prioritisetransaction.py
Techcoingithub/techcoin
6914faea0496d16d85f4f11fc1ae2ba05e9143b8
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # Copyright (c) 2015-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the prioritisetransaction mining RPC.""" import time from test_framework.messages import COIN, MAX_BLOCK_WEIGHT from test_framework.test_framework import TechcoinTestFramework from test_framework.util import assert_equal, assert_raises_rpc_error, create_confirmed_utxos, create_lots_of_big_transactions, gen_return_txouts class PrioritiseTransactionTest(TechcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 2 self.extra_args = [[ "-printpriority=1", "-acceptnonstdtxn=1", ]] * self.num_nodes self.supports_cli = False def skip_test_if_missing_module(self): self.skip_if_no_wallet() def run_test(self): # Test `prioritisetransaction` required parameters assert_raises_rpc_error(-1, "prioritisetransaction", self.nodes[0].prioritisetransaction) assert_raises_rpc_error(-1, "prioritisetransaction", self.nodes[0].prioritisetransaction, '') assert_raises_rpc_error(-1, "prioritisetransaction", self.nodes[0].prioritisetransaction, '', 0) # Test `prioritisetransaction` invalid extra parameters assert_raises_rpc_error(-1, "prioritisetransaction", self.nodes[0].prioritisetransaction, '', 0, 0, 0) # Test `prioritisetransaction` invalid `txid` assert_raises_rpc_error(-8, "txid must be of length 64 (not 3, for 'foo')", self.nodes[0].prioritisetransaction, txid='foo', fee_delta=0) assert_raises_rpc_error(-8, "txid must be hexadecimal string (not 'Zd1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000')", self.nodes[0].prioritisetransaction, txid='Zd1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000', fee_delta=0) # Test `prioritisetransaction` invalid `dummy` txid = '1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000' assert_raises_rpc_error(-1, "JSON value is not a number as expected", self.nodes[0].prioritisetransaction, txid, 'foo', 0) assert_raises_rpc_error(-8, "Priority is no longer supported, dummy argument to prioritisetransaction must be 0.", self.nodes[0].prioritisetransaction, txid, 1, 0) # Test `prioritisetransaction` invalid `fee_delta` assert_raises_rpc_error(-1, "JSON value is not an integer as expected", self.nodes[0].prioritisetransaction, txid=txid, fee_delta='foo') self.txouts = gen_return_txouts() self.relayfee = self.nodes[0].getnetworkinfo()['relayfee'] utxo_count = 90 utxos = create_confirmed_utxos(self, self.relayfee, self.nodes[0], utxo_count) base_fee = self.relayfee*100 # our transactions are smaller than 100kb txids = [] # Create 3 batches of transactions at 3 different fee rate levels range_size = utxo_count // 3 for i in range(3): txids.append([]) start_range = i * range_size end_range = start_range + range_size txids[i] = create_lots_of_big_transactions(self.nodes[0], self.txouts, utxos[start_range:end_range], end_range - start_range, (i+1)*base_fee) # Make sure that the size of each group of transactions exceeds # MAX_BLOCK_WEIGHT // 4 -- otherwise the test needs to be revised to # create more transactions. mempool = self.nodes[0].getrawmempool(True) sizes = [0, 0, 0] for i in range(3): for j in txids[i]: assert j in mempool sizes[i] += mempool[j]['vsize'] assert sizes[i] > MAX_BLOCK_WEIGHT // 4 # Fail => raise utxo_count # add a fee delta to something in the cheapest bucket and make sure it gets mined # also check that a different entry in the cheapest bucket is NOT mined self.nodes[0].prioritisetransaction(txid=txids[0][0], fee_delta=int(3*base_fee*COIN)) self.nodes[0].generate(1) mempool = self.nodes[0].getrawmempool() self.log.info("Assert that prioritised transaction was mined") assert txids[0][0] not in mempool assert txids[0][1] in mempool high_fee_tx = None for x in txids[2]: if x not in mempool: high_fee_tx = x # Something high-fee should have been mined! assert high_fee_tx is not None # Add a prioritisation before a tx is in the mempool (de-prioritising a # high-fee transaction so that it's now low fee). self.nodes[0].prioritisetransaction(txid=high_fee_tx, fee_delta=-int(2*base_fee*COIN)) # Add everything back to mempool self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) # Check to make sure our high fee rate tx is back in the mempool mempool = self.nodes[0].getrawmempool() assert high_fee_tx in mempool # Now verify the modified-high feerate transaction isn't mined before # the other high fee transactions. Keep mining until our mempool has # decreased by all the high fee size that we calculated above. while (self.nodes[0].getmempoolinfo()['bytes'] > sizes[0] + sizes[1]): self.nodes[0].generate(1) # High fee transaction should not have been mined, but other high fee rate # transactions should have been. mempool = self.nodes[0].getrawmempool() self.log.info("Assert that de-prioritised transaction is still in mempool") assert high_fee_tx in mempool for x in txids[2]: if (x != high_fee_tx): assert x not in mempool # Create a free transaction. Should be rejected. utxo_list = self.nodes[0].listunspent() assert len(utxo_list) > 0 utxo = utxo_list[0] inputs = [] outputs = {} inputs.append({"txid" : utxo["txid"], "vout" : utxo["vout"]}) outputs[self.nodes[0].getnewaddress()] = utxo["amount"] raw_tx = self.nodes[0].createrawtransaction(inputs, outputs) tx_hex = self.nodes[0].signrawtransactionwithwallet(raw_tx)["hex"] tx_id = self.nodes[0].decoderawtransaction(tx_hex)["txid"] # This will raise an exception due to min relay fee not being met assert_raises_rpc_error(-26, "min relay fee not met", self.nodes[0].sendrawtransaction, tx_hex) assert tx_id not in self.nodes[0].getrawmempool() # This is a less than 1000-byte transaction, so just set the fee # to be the minimum for a 1000-byte transaction and check that it is # accepted. self.nodes[0].prioritisetransaction(txid=tx_id, fee_delta=int(self.relayfee*COIN)) self.log.info("Assert that prioritised free transaction is accepted to mempool") assert_equal(self.nodes[0].sendrawtransaction(tx_hex), tx_id) assert tx_id in self.nodes[0].getrawmempool() # Test that calling prioritisetransaction is sufficient to trigger # getblocktemplate to (eventually) return a new block. mock_time = int(time.time()) self.nodes[0].setmocktime(mock_time) template = self.nodes[0].getblocktemplate({'rules': ['segwit']}) self.nodes[0].prioritisetransaction(txid=tx_id, fee_delta=-int(self.relayfee*COIN)) self.nodes[0].setmocktime(mock_time+10) new_template = self.nodes[0].getblocktemplate({'rules': ['segwit']}) assert template != new_template if __name__ == '__main__': PrioritiseTransactionTest().main()
48.607595
266
0.679818
edefc77c4fd53b875f45db4783c8e2f028af81ee
916
py
Python
azure/mgmt/network/v2016_09_01/models/bgp_peer_status_list_result.py
EnjoyLifeFund/macHighSierra-py36-pkgs
5668b5785296b314ea1321057420bcd077dba9ea
[ "BSD-3-Clause", "BSD-2-Clause", "MIT" ]
null
null
null
azure/mgmt/network/v2016_09_01/models/bgp_peer_status_list_result.py
EnjoyLifeFund/macHighSierra-py36-pkgs
5668b5785296b314ea1321057420bcd077dba9ea
[ "BSD-3-Clause", "BSD-2-Clause", "MIT" ]
null
null
null
azure/mgmt/network/v2016_09_01/models/bgp_peer_status_list_result.py
EnjoyLifeFund/macHighSierra-py36-pkgs
5668b5785296b314ea1321057420bcd077dba9ea
[ "BSD-3-Clause", "BSD-2-Clause", "MIT" ]
null
null
null
# 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 BgpPeerStatusListResult(Model): """Response for list BGP peer status API service call. :param value: List of BGP peers :type value: list[~azure.mgmt.network.v2016_09_01.models.BgpPeerStatus] """ _attribute_map = { 'value': {'key': 'value', 'type': '[BgpPeerStatus]'}, } def __init__(self, value=None): self.value = value
32.714286
77
0.567686
4631743ac6190439c98aa3cfc0e0750e5c6f5a39
9,214
py
Python
scripts/docs_csat.py
olgaromashko/docs
c6d639f146ac8299981e4a026defa4a917e7ef90
[ "CC-BY-4.0", "BSD-3-Clause" ]
1
2021-02-14T07:51:38.000Z
2021-02-14T07:51:38.000Z
scripts/docs_csat.py
rainleander/docs
34b94b4ca65100c8f4239681ebd307d0907d387e
[ "CC-BY-4.0", "BSD-3-Clause" ]
54
2021-04-26T20:00:15.000Z
2021-05-12T21:55:53.000Z
scripts/docs_csat.py
rainleander/docs
34b94b4ca65100c8f4239681ebd307d0907d387e
[ "CC-BY-4.0", "BSD-3-Clause" ]
null
null
null
""" Calculate docs CSAT based on "Was this page helpful?" feedback submissions and unique pageviews, as tracked via Google Analytics; and generate a graph plotting docs pages based on their negative and positive votes, with dot size indicating number of unique pageviews. Help: python3 docs-csat.py --help Requirements: - Set up Google Analytics Reporting API: https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-py#1_enable_the_api. - Store GA credentials file as a GA_KEY_FILE_LOCATION env variable. - Install Google Analytics Python client library: pip3 install --upgrade google-api-python-client oauth2client - Install the Plotly visualization library: pip3 install plotly """ from googleapiclient.discovery import build import argparse from oauth2client.service_account import ServiceAccountCredentials import os import plotly.graph_objects as go parser = argparse.ArgumentParser( description='Calculate docs CSAT and generate graph of pages.' ) parser.add_argument( '--ga_key_file_location', default=os.environ.get('GA_KEY_FILE_LOCATION', None), help='''Location of your Google Analytics key file. Store as a GA_KEY_FILE_LOCATION env variable or pass here.''' ) parser.add_argument( '--ga_view_id', default='119439298', help='''Google Analytics view to query. You can use https://ga-dev-tools.appspot.com/account-explorer/ to find a view ID.''' ) parser.add_argument( '--start_date', default='2020-02-01', help='Start date for CSAT calculations and graphing' ) parser.add_argument( '--end_date', default='today', help='End date for CSAT calculations and graphing.' ) args = parser.parse_args() blocklist = ['cockroachdb-in-comparison.html'] def initialize_analyticsreporting(): credentials = ServiceAccountCredentials.from_json_keyfile_name( args.ga_key_file_location, 'https://www.googleapis.com/auth/analytics.readonly') analytics = build('analyticsreporting', 'v4', credentials=credentials) return analytics def get_no_votes(analytics): return analytics.reports().batchGet( body={ 'reportRequests': [ { 'viewId': args.ga_view_id, 'dateRanges': [ {'startDate': args.start_date, 'endDate': args.end_date} ], 'metrics': [ {'expression': 'ga:totalEvents'} ], 'dimensions': [ {'name': 'ga:pageTitle'}, {'name': 'ga:pagePath'} ], 'dimensionFilterClauses': [ { 'filters': [ { 'dimensionName': 'ga:eventCategory', 'operator': 'REGEXP', 'expressions': ['docs-feedback-no'] } ] } ] } ] } ).execute() def get_yes_votes(analytics): return analytics.reports().batchGet( body={ 'reportRequests': [ { 'viewId': args.ga_view_id, 'dateRanges': [ {'startDate': args.start_date, 'endDate': args.end_date} ], 'metrics': [ {'expression': 'ga:totalEvents'} ], 'dimensions': [ {'name': 'ga:pageTitle'}, {'name': 'ga:pagePath'} ], 'dimensionFilterClauses': [ { 'filters': [ { 'dimensionName': 'ga:eventCategory', 'operator': 'REGEXP', 'expressions': ['docs-feedback-yes'] } ] } ] } ] } ).execute() def get_pageviews(analytics): return analytics.reports().batchGet( body={ 'reportRequests': [ { 'viewId': args.ga_view_id, 'dateRanges': [ {'startDate': args.start_date, 'endDate': args.end_date} ], 'metrics': [ {'expression': 'ga:uniquePageviews'}, ], 'dimensions': [ {'name': 'ga:pageTitle'}, {'name': 'ga:pagePath'} ], 'dimensionFilterClauses': [ { 'filters': [ { 'dimensionName': 'ga:pagePath', 'operator': 'IN_LIST', 'expressions': [pages_filter] } ] } ] } ] } ).execute() no_votes = dict() yes_votes = dict() pageviews = dict() pages_filter = list() def create_dict(response, dict): for report in response.get('reports', []): for row in report.get('data', {}).get('rows', []): page = row.get('dimensions')[1] metrics = row.get('metrics') for values in metrics: value = values.get('values')[0] if page in dict: dict[page] += float(value) else: dict[page] = float(value) pages_filter.append(page) average_csats = dict() weighted_csats = dict() def calculate_csat(no_votes, yes_votes, pageviews): # Remove blocklisted pages. for p in blocklist: for k in list(pageviews): if p in k: del pageviews[k] for k in list(no_votes): if p in k: del no_votes[k] for k in list(yes_votes): if p in k: del yes_votes[k] # Even out dictionaries. for k in pageviews.keys(): if k not in no_votes: no_votes[k] = 0.0 if k not in yes_votes: yes_votes[k] = 0.0 for k in no_votes.keys(): if k not in yes_votes: yes_votes[k] = 0.0 if k not in pageviews: pageviews[k] = 0.0 for k in yes_votes.keys(): if k not in no_votes: no_votes[k] = 0.0 if k not in pageviews: pageviews[k] = 0.0 # Basic CSAT total_yes = 0.0 total_no = 0.0 for v in yes_votes.values(): total_yes += v for v in no_votes.values(): total_no += v total_votes = total_yes + total_no basic_csat = total_yes / total_votes # Weighted CSAT for k,v in yes_votes.items(): yes = v total = yes + no_votes[k] average_csats[k] = yes / total for k,v in average_csats.items(): weighted_csats[k] = v * pageviews[k] weighted_csat = sum(weighted_csats.values()) / sum(pageviews.values()) return basic_csat, weighted_csat def main(): # Requests analytics = initialize_analyticsreporting() create_dict(get_no_votes(analytics), no_votes) create_dict(get_yes_votes(analytics), yes_votes) create_dict(get_pageviews(analytics), pageviews) # Overall CSAT print() print( 'Docs CSAT (basic, weighted):', calculate_csat(no_votes, yes_votes, pageviews) ) print() # for k in pageviews: # print('Page:', k) # print('Unique Pageviews:', pageviews[k]) # print('No Votes:', no_votes[k]) # print('Yes Votes:', yes_votes[k]) # print() # Graph pages = list() uniques = list() negative = list() positive = list() for k in pageviews: pages.append(k) uniques.append(pageviews[k]) negative.append(no_votes[k]) positive.append(yes_votes[k]) # print(len(positive)) # print(len(yes_votes)) fig = go.Figure(data=go.Scatter( x=negative, y=positive, text=pages, customdata=uniques, hovertemplate= 'No votes: %{x}'+ '<br>Yes votes: %{y}'+ '<br>%{text}'+ '<br>Unique pageviews: %{customdata}', mode='markers', marker=dict( size=uniques, sizemode='area', sizeref=2.*max(uniques)/(100.**2), sizemin=4 ) )) fig.update_layout( title="Docs CSAT", xaxis_title="Negative Votes", yaxis_title="Positive Votes", font=dict( family="Courier New, monospace", size=18, color="#7f7f7f" ) ) fig.show() if __name__ == '__main__': main()
28.79375
111
0.493488
fdc4de386bbc3be7739b8fc2f46cdf7859a484ed
439
py
Python
output/models/nist_data/atomic/name/schema_instance/nistschema_sv_iv_atomic_name_max_length_3_xsd/nistschema_sv_iv_atomic_name_max_length_3.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
1
2021-08-14T17:59:21.000Z
2021-08-14T17:59:21.000Z
output/models/nist_data/atomic/name/schema_instance/nistschema_sv_iv_atomic_name_max_length_3_xsd/nistschema_sv_iv_atomic_name_max_length_3.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
4
2020-02-12T21:30:44.000Z
2020-04-15T20:06:46.000Z
output/models/nist_data/atomic/name/schema_instance/nistschema_sv_iv_atomic_name_max_length_3_xsd/nistschema_sv_iv_atomic_name_max_length_3.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
null
null
null
from dataclasses import dataclass, field __NAMESPACE__ = "NISTSchema-SV-IV-atomic-Name-maxLength-3-NS" @dataclass class NistschemaSvIvAtomicNameMaxLength3: class Meta: name = "NISTSchema-SV-IV-atomic-Name-maxLength-3" namespace = "NISTSchema-SV-IV-atomic-Name-maxLength-3-NS" value: str = field( default="", metadata={ "required": True, "max_length": 11, } )
23.105263
65
0.628702
438b524a74e34f66b26e2b409a5d132979fad49d
14,258
py
Python
keras_retinanet_3D/utils/anchors.py
arangesh/Ground-Plane-Polling
ad58ab712a1275c263b4f0a50c5c909401d9a99b
[ "MIT" ]
12
2019-02-23T21:48:21.000Z
2022-02-01T06:05:07.000Z
keras_retinanet_3D/utils/anchors.py
arangesh/Ground-Plane-Polling
ad58ab712a1275c263b4f0a50c5c909401d9a99b
[ "MIT" ]
2
2019-05-27T08:45:43.000Z
2021-06-11T02:41:45.000Z
keras_retinanet_3D/utils/anchors.py
arangesh/Ground-Plane-Polling
ad58ab712a1275c263b4f0a50c5c909401d9a99b
[ "MIT" ]
4
2019-02-13T08:34:53.000Z
2020-01-26T13:42:57.000Z
""" Copyright 2017-2018 Fizyr (https://fizyr.com) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import numpy as np #import scipy #import sys def anchor_targets_bbox( image_shape, annotations, ignore_region, num_classes, mask_shape=None, negative_overlap=0.4, positive_overlap=0.5, **kwargs ): """ Generate anchor targets for bbox detection. Args image_shape: Shape of the image. annotations: np.array of shape (N, 17) for (x1, y1, x2, y2, xl, yl, xm, ym, xr, yr, xt, yt, height, width, length, class, orientation). ignore_region: np.array of shape (M, 4) for (x1, y1, x2, y2) denoting ignore region in an image. num_classes: Number of classes to predict. mask_shape: If the image is padded with zeros, mask_shape can be used to mark the relevant part of the image. negative_overlap: IoU overlap for negative anchors (all anchors with overlap < negative_overlap are negative). positive_overlap: IoU overlap or positive anchors (all anchors with overlap > positive_overlap are positive). Returns labels: np.array of shape (A, 4*num_classes) where a cols consists of -1 for ignore, 0 for negative and 1 for positive for a certain class. annotations: np.array of shape (A, 12) for (x1, y1, x2, y2, xl, yl, xm, ym, xr, yr, xt, yt). anchors: np.array of shape (A, 4) for (x1, y1, x2, y2) containing the anchor boxes. labels_dim: np.array of shape (A, num_classes) where cols consists of -1 for ignore, 0 for negative and 1 for positive for a certain class. annotations_dim: np.array of shape (A, 3*num_classes) where cols consists of (height, width, length) for each class. """ anchors = anchors_for_shape(image_shape, **kwargs) #scipy.io.savemat('anchors.mat', {'anchors': anchors}) #sys.exit(0) if annotations.shape[0]: # label: 1 is positive, 0 is negative, -1 is dont care labels = np.ones((anchors.shape[0], 4*num_classes)) * -1 labels_dim = np.ones((anchors.shape[0], num_classes)) * -1 # obtain indices of gt annotations with the greatest overlap overlaps = compute_overlap(anchors, annotations) argmax_overlaps_inds = np.argmax(overlaps, axis=1) max_overlaps = overlaps[np.arange(overlaps.shape[0]), argmax_overlaps_inds] # compute box regression targets annotations = annotations[argmax_overlaps_inds] # assign bg labels first so that positive labels can clobber them labels[max_overlaps < negative_overlap, :] = 0 labels_dim[max_overlaps < negative_overlap, :] = 0 # fg label: above threshold IOU positive_indices = max_overlaps >= positive_overlap labels[positive_indices, :] = 0 labels_dim[positive_indices, :] = 0 # retain positive indices for dimension regression labels_dim[positive_indices, annotations[positive_indices, -2].astype(int)] = 1 annotations_dim = np.tile(annotations[:, 12:-2], (1, num_classes)) # retain positive indices for only the correct 3D orientation class_indices = 4*annotations[positive_indices, -2] + annotations[positive_indices, -1] # Identify anchor associated with correct class and orientation and set as positive labels[positive_indices, class_indices.astype(int)] = 1 # retain only bbox columns annotations = annotations[:, :12] else: # no annotations? then everything is background labels_dim = np.zeros((anchors.shape[0], num_classes)) annotations_dim = np.zeros((anchors.shape[0], 3*num_classes)) labels = np.zeros((anchors.shape[0], 4*num_classes)) annotations = np.zeros((anchors.shape[0], 12)) # ignore anchors inside ignore boxes anchors_centers = np.vstack([(anchors[:, 0] + anchors[:, 2]) / 2, (anchors[:, 1] + anchors[:, 3]) / 2]).T indices = np.zeros((anchors_centers.shape[0])).astype(bool) for region in ignore_region: indices = np.logical_or(indices, np.logical_and.reduce((anchors_centers[:, 0] >= region[0], anchors_centers[:, 1] >= region[1], anchors_centers[:, 0] <= region[2], anchors_centers[:, 1] <= region[3]))) labels_dim[indices, :] = -1 labels[indices, :] = -1 return labels, annotations, anchors, labels_dim, annotations_dim def layer_shapes(image_shape, model): """Compute layer shapes given input image shape and the model. Args image_shape: The shape of the image. model: The model to use for computing how the image shape is transformed in the pyramid. Returns A dictionary mapping layer names to image shapes. """ shape = { model.layers[0].name: (None,) + image_shape, } for layer in model.layers[1:]: nodes = layer._inbound_nodes for node in nodes: inputs = [shape[lr.name] for lr in node.inbound_layers] if not inputs: continue shape[layer.name] = layer.compute_output_shape(inputs[0] if len(inputs) == 1 else inputs) return shape def make_shapes_callback(model): """ Make a function for getting the shape of the pyramid levels. """ def get_shapes(image_shape, pyramid_levels): shape = layer_shapes(image_shape, model) image_shapes = [shape["P{}".format(level)][1:3] for level in pyramid_levels] return image_shapes return get_shapes def guess_shapes(image_shape, pyramid_levels): """Guess shapes based on pyramid levels. Args image_shape: The shape of the image. pyramid_levels: A list of what pyramid levels are used. Returns A list of image shapes at each pyramid level. """ image_shape = np.array(image_shape[:2]) image_shapes = [(image_shape + 2 ** x - 1) // (2 ** x) for x in pyramid_levels] return image_shapes def anchors_for_shape( image_shape, pyramid_levels=None, ratios=None, scales=None, strides=None, sizes=None, shapes_callback=None, ): """ Generators anchors for a given shape. Args image_shape: The shape of the image. pyramid_levels: List of ints representing which pyramids to use (defaults to [3, 4, 5, 6, 7]). ratios: List of ratios with which anchors are generated (defaults to [0.5, 1, 2]). scales: List of scales with which anchors are generated (defaults to [2^0, 2^(1/3), 2^(2/3)]). strides: Stride per pyramid level, defines how the pyramids are constructed. sizes: Sizes of the anchors per pyramid level. shapes_callback: Function to call for getting the shape of the image at different pyramid levels. Returns np.array of shape (N, 4) containing the (x1, y1, x2, y2) coordinates for the anchors. """ if pyramid_levels is None: pyramid_levels = [3, 4, 5, 6, 7] if strides is None: strides = [2 ** x for x in pyramid_levels] if sizes is None: sizes = [2 ** (x + 2) for x in pyramid_levels] if ratios is None: ratios = np.array([0.5, 1, 2]) if scales is None: scales = np.array([2 ** (-2.0 / 3.0), 2 ** 0, 2 ** (1.0 / 3.0), 2 ** (2.0 / 3.0)]) if shapes_callback is None: shapes_callback = guess_shapes image_shapes = shapes_callback(image_shape, pyramid_levels) # compute anchors over all pyramid levels all_anchors = np.zeros((0, 4)) for idx, p in enumerate(pyramid_levels): anchors = generate_anchors(base_size=sizes[idx], ratios=ratios, scales=scales) shifted_anchors = shift(image_shapes[idx], strides[idx], anchors) all_anchors = np.append(all_anchors, shifted_anchors, axis=0) return all_anchors def shift(shape, stride, anchors): """ Produce shifted anchors based on shape of the map and stride size. Args shape : Shape to shift the anchors over. stride : Stride to shift the anchors with over the shape. anchors: The anchors to apply at each location. """ shift_x = (np.arange(0, shape[1]) + 0.5) * stride shift_y = (np.arange(0, shape[0]) + 0.5) * stride shift_x, shift_y = np.meshgrid(shift_x, shift_y) shifts = np.vstack(( shift_x.ravel(), shift_y.ravel(), shift_x.ravel(), shift_y.ravel() )).transpose() # add A anchors (1, A, 4) to # cell K shifts (K, 1, 4) to get # shift anchors (K, A, 4) # reshape to (K*A, 4) shifted anchors A = anchors.shape[0] K = shifts.shape[0] all_anchors = (anchors.reshape((1, A, 4)) + shifts.reshape((1, K, 4)).transpose((1, 0, 2))) all_anchors = all_anchors.reshape((K * A, 4)) return all_anchors def generate_anchors(base_size=16, ratios=None, scales=None): """ Generate anchor (reference) windows by enumerating aspect ratios X scales w.r.t. a reference window. """ if ratios is None: ratios = np.array([0.5, 1, 2]) if scales is None: scales = np.array([2 ** (-2.0 / 3.0), 2 ** 0, 2 ** (1.0 / 3.0), 2 ** (2.0 / 3.0)]) num_anchors = len(ratios) * len(scales) # initialize output anchors anchors = np.zeros((num_anchors, 4)) # scale base_size anchors[:, 2:] = base_size * np.tile(scales, (2, len(ratios))).T # compute areas of anchors areas = anchors[:, 2] * anchors[:, 3] # correct for ratios anchors[:, 2] = np.sqrt(areas / np.repeat(ratios, len(scales))) anchors[:, 3] = anchors[:, 2] * np.repeat(ratios, len(scales)) # transform from (x_ctr, y_ctr, w, h) -> (x1, y1, x2, y2) anchors[:, 0::2] -= np.tile(anchors[:, 2] * 0.5, (2, 1)).T anchors[:, 1::2] -= np.tile(anchors[:, 3] * 0.5, (2, 1)).T return anchors def bbox_transform(anchors, gt_boxes, num_classes, mean=None, std=None): """Compute bounding-box regression targets for an image.""" if mean is None: mean = np.array([-0.0373, -0.0165, 0.0373, 0.0171, -0.0286, -0.0478, 0.2929, 0.0114, 0.0288, -0.0589, 0.2932, -0.0007]) if std is None: std = np.array([0.1957, 0.1896, 0.1957, 0.1897, 0.1967, 0.2034, 0.2046, 0.1898, 0.1964, 0.2052, 0.2048, 0.1903]) if isinstance(mean, (list, tuple)): mean = np.array(mean) elif not isinstance(mean, np.ndarray): raise ValueError('Expected mean to be a np.ndarray, list or tuple. Received: {}'.format(type(mean))) if isinstance(std, (list, tuple)): std = np.array(std) elif not isinstance(std, np.ndarray): raise ValueError('Expected std to be a np.ndarray, list or tuple. Received: {}'.format(type(std))) anchor_widths = anchors[:, 2] - anchors[:, 0] anchor_heights = anchors[:, 3] - anchors[:, 1] targets_dx1 = (gt_boxes[:, 0] - anchors[:, 0]) / anchor_widths targets_dy1 = (gt_boxes[:, 1] - anchors[:, 1]) / anchor_heights targets_dx2 = (gt_boxes[:, 2] - anchors[:, 2]) / anchor_widths targets_dy2 = (gt_boxes[:, 3] - anchors[:, 3]) / anchor_heights targets_dxl = (gt_boxes[:, 4] - anchors[:, 0]) / anchor_widths targets_dyl = (gt_boxes[:, 5] - anchors[:, 3]) / anchor_heights targets_dxm = (gt_boxes[:, 6] - (anchors[:, 0] + anchors[:, 2])/2) / anchor_widths targets_dym = (gt_boxes[:, 7] - anchors[:, 3]) / anchor_heights targets_dxr = (gt_boxes[:, 8] - anchors[:, 2]) / anchor_widths targets_dyr = (gt_boxes[:, 9] - anchors[:, 3]) / anchor_heights targets_dxt = (gt_boxes[:, 10] - (anchors[:, 0] + anchors[:, 2])/2) / anchor_widths targets_dyt = (gt_boxes[:, 11] - anchors[:, 1]) / anchor_heights targets_sign = (np.sign(targets_dxm) + 1)/2 targets_sign = np.concatenate((np.tile(1 - targets_sign, (4*num_classes, 1)), np.tile(targets_sign, (4*num_classes, 1))), axis = 0) targets_sign = targets_sign.T targets_dxm = np.absolute(targets_dxm) targets_dxt = np.absolute(targets_dxt) targets = np.stack((targets_dx1, targets_dy1, targets_dx2, targets_dy2, targets_dxl, targets_dyl, targets_dxm, targets_dym, targets_dxr, targets_dyr, targets_dxt, targets_dyt)) targets = targets.T targets = (targets - mean) / std return targets, targets_sign def dim_transform(gt_dims, mean=None, std=None): """Compute dimension regression targets for an image.""" # mean and std should have 3*num_classes elements corresponding to (height, width, length) of each class if mean is None: mean = np.array([1.6570, 1.7999, 4.2907]) if std is None: std = np.array([0.2681, 0.2243, 0.6281]) if isinstance(mean, (list, tuple)): mean = np.array(mean) elif not isinstance(mean, np.ndarray): raise ValueError('Expected mean to be a np.ndarray, list or tuple. Received: {}'.format(type(mean))) if isinstance(std, (list, tuple)): std = np.array(std) elif not isinstance(std, np.ndarray): raise ValueError('Expected std to be a np.ndarray, list or tuple. Received: {}'.format(type(std))) targets = (gt_dims - mean) / std return targets def compute_overlap(a, b): """ Args a: (N, 4) ndarray of float b: (K, 4) ndarray of float Returns overlaps: (N, K) ndarray of overlap between boxes and query_boxes """ area = (b[:, 2] - b[:, 0]) * (b[:, 3] - b[:, 1]) iw = np.minimum(np.expand_dims(a[:, 2], axis=1), b[:, 2]) - np.maximum(np.expand_dims(a[:, 0], 1), b[:, 0]) ih = np.minimum(np.expand_dims(a[:, 3], axis=1), b[:, 3]) - np.maximum(np.expand_dims(a[:, 1], 1), b[:, 1]) iw = np.maximum(iw, 0) ih = np.maximum(ih, 0) ua = np.expand_dims((a[:, 2] - a[:, 0]) * (a[:, 3] - a[:, 1]), axis=1) + area - iw * ih ua = np.maximum(ua, np.finfo(float).eps) intersection = iw * ih return intersection / ua
39.17033
209
0.639781
c275aeed93b6241373b403f0b7bb52a2678450ed
12,073
py
Python
v2.5.7/toontown/parties/PartyLoader.py
TTOFFLINE-LEAK/ttoffline
bb0e91704a755d34983e94288d50288e46b68380
[ "MIT" ]
4
2019-07-01T15:46:43.000Z
2021-07-23T16:26:48.000Z
v2.5.7/toontown/parties/PartyLoader.py
TTOFFLINE-LEAK/ttoffline
bb0e91704a755d34983e94288d50288e46b68380
[ "MIT" ]
1
2019-06-29T03:40:05.000Z
2021-06-13T01:15:16.000Z
v2.5.7/toontown/parties/PartyLoader.py
TTOFFLINE-LEAK/ttoffline
bb0e91704a755d34983e94288d50288e46b68380
[ "MIT" ]
4
2019-07-28T21:18:46.000Z
2021-02-25T06:37:25.000Z
import math, random from direct.directnotify import DirectNotifyGlobal from direct.interval.IntervalGlobal import * from direct.fsm import ClassicFSM, State from panda3d.core import * from panda3d.core import NodePath from toontown.toonbase.ToontownGlobals import * from toontown.safezone import SafeZoneLoader from toontown.parties import Party from toontown.parties.PartyGlobals import FireworksStartedEvent, FireworksFinishedEvent class PartyLoader(SafeZoneLoader.SafeZoneLoader): notify = DirectNotifyGlobal.directNotify.newCategory('PartyLoader') def __init__(self, hood, parentFSM, doneEvent): SafeZoneLoader.SafeZoneLoader.__init__(self, hood, parentFSM, doneEvent) del self.fsm self.fsm = ClassicFSM.ClassicFSM('PartyLoader', [State.State('start', self.enterStart, self.exitStart, ['quietZone', 'party', 'planning']), State.State('party', self.enterParty, self.exitParty, ['quietZone']), State.State('quietZone', self.enterQuietZone, self.exitQuietZone, ['planning', 'party']), State.State('final', self.enterFinal, self.exitFinal, ['start'])], 'start', 'final') self.musicFile = 'phase_13/audio/bgm/party_original_theme.ogg' self.activityMusicFile = 'phase_13/audio/bgm/party_waltz_dance.ogg' self.dnaFile = 'phase_13/dna/party_sz.jazz' self.safeZoneStorageDNAFile = None self.cloudSwitch = 0 self.id = PartyHood self.partyOwnerId = None self.branchZone = None self.partyDoneEvent = 'partyDone' self.barrel = None self.clouds = [] self.cloudTrack = None self.sunMoonNode = None self.fsm.enterInitialState() return def load(self): self.oldClear = base.win.getClearColor() base.win.setClearColor(Vec4(0.47, 0.69, 0.3, 1.0)) SafeZoneLoader.SafeZoneLoader.load(self) self.underwaterSound = base.loader.loadSfx('phase_4/audio/sfx/AV_ambient_water.ogg') self.swimSound = base.loader.loadSfx('phase_4/audio/sfx/AV_swim_single_stroke.ogg') self.submergeSound = base.loader.loadSfx('phase_5.5/audio/sfx/AV_jump_in_water.ogg') self.birdSound = map(base.loader.loadSfx, ['phase_4/audio/sfx/SZ_TC_bird1.ogg', 'phase_4/audio/sfx/SZ_TC_bird2.ogg', 'phase_4/audio/sfx/SZ_TC_bird3.ogg']) self.cricketSound = map(base.loader.loadSfx, ['phase_4/audio/sfx/SZ_TC_bird1.ogg', 'phase_4/audio/sfx/SZ_TC_bird2.ogg', 'phase_4/audio/sfx/SZ_TC_bird3.ogg']) def unload(self): self.ignoreAll() base.win.setClearColor(self.oldClear) if base.cr.partyManager: base.cr.partyManager.leaveParty() self.partyOwnerId = None self.partyZoneId = None if self.place: self.place.exit() self.place.unload() del self.place del self.underwaterSound del self.swimSound del self.submergeSound del self.birdSound del self.cricketSound self.__cleanupCloudFadeInterval() if self.sunMoonNode: self.sunMoonNode.removeNode() del self.sunMoonNode self.sunMoonNode = None if self.clouds: for cloud in self.clouds: cloud[0].removeNode() del cloud[1] del self.clouds if self.barrel: self.barrel.removeNode() SafeZoneLoader.SafeZoneLoader.unload(self) return def loadClouds(self): self.loadCloudPlatforms() if base.cloudPlatformsEnabled and 0: self.setCloudSwitch(1) if self.cloudSwitch: self.setCloudSwitch(self.cloudSwitch) def enter(self, requestStatus): self.partyOwnerId = requestStatus.get('ownerId', base.localAvatar.doId) base.localAvatar.inParty = 1 self.accept(FireworksStartedEvent, self.__handleFireworksStarted) self.accept(FireworksFinishedEvent, self.__handleFireworksFinished) SafeZoneLoader.SafeZoneLoader.enter(self, requestStatus) def exit(self): self.ignoreAll() base.cr.cache.flush() base.localAvatar.stopChat() base.localAvatar.inParty = 0 self.ignore(FireworksStartedEvent) self.ignore(FireworksFinishedEvent) SafeZoneLoader.SafeZoneLoader.exit(self) def createSafeZone(self, dnaFile): SafeZoneLoader.SafeZoneLoader.createSafeZone(self, dnaFile) parent = self.geom.getParent() geom = self.geom n = NodePath('PartyGroundRoot') n.reparentTo(parent) geom.reparentTo(n) geom.setPos(-10.0, 0.0, 0.0) self.geom = n self.loadSunMoon() def loadSunMoon(self): self.sun = loader.loadModel('phase_4/models/props/sun') self.moon = loader.loadModel('phase_5.5/models/props/moon') self.sunMoonNode = self.geom.attachNewNode('sunMoon') self.sunMoonNode.setPosHpr(0, 0, 0, 0, 0, 0) if self.sun: self.sun.reparentTo(self.sunMoonNode) self.sun.setY(270) self.sun.setScale(2) self.sun.setBillboardPointEye() if self.moon: self.moon.reparentTo(self.sunMoonNode) self.moon.setY(-270) self.moon.setScale(15) self.moon.setBillboardPointEye() self.sunMoonNode.setP(30) def enterParty(self, requestStatus): self.notify.debug('enterParty: requestStatus = %s' % requestStatus) ownerId = requestStatus.get('ownerId') if ownerId: self.partyOwnerId = ownerId zoneId = requestStatus['zoneId'] self.notify.debug('enterParty, ownerId = %s, zoneId = %s' % (self.partyOwnerId, zoneId)) self.accept(self.partyDoneEvent, self.handlePartyDone) self.place = Party.Party(self, self.partyOwnerId, zoneId, self.fsm.getStateNamed('party'), self.partyDoneEvent) base.cr.playGame.setPlace(self.place) self.place.load() self.place.enter(requestStatus) self.partyZoneId = zoneId def exitParty(self): self.notify.debug('exitParty') self.ignore(self.partyDoneEvent) self.place.exit() self.place.unload() self.place = None base.cr.playGame.setPlace(self.place) base.cr.cache.flush() return def handlePartyDone(self, doneStatus=None): PartyLoader.notify.debug('handlePartyDone doneStatus = %s' % doneStatus) if not doneStatus: doneStatus = self.place.getDoneStatus() how = doneStatus['how'] shardId = doneStatus['shardId'] hoodId = doneStatus['hoodId'] zoneId = doneStatus['zoneId'] avId = doneStatus.get('avId', -1) ownerId = doneStatus.get('ownerId', -1) self.notify.debug('hoodId = %s, avId = %s' % (hoodId, avId)) self.doneStatus = doneStatus messenger.send(self.doneEvent) def handleQuietZoneDone(self): status = self.quietZoneStateData.getRequestStatus() self.fsm.request(status['where'], [status]) def atMyParty(self): if self.partyOwnerId != None: if self.partyOwnerId == base.localAvatar.getDoId(): return 1 return 0 else: self.notify.warning("We aren't in an party") return def startCloudPlatforms(self): if len(self.clouds): self.cloudTrack = self.__cloudTrack() self.cloudTrack.loop() def stopCloudPlatforms(self): if self.cloudTrack: self.cloudTrack.pause() del self.cloudTrack self.cloudTrack = None return def __cloudTrack(self): track = Parallel() for cloud in self.clouds: axis = cloud[1] pos = cloud[0].getPos(render) newPos = pos + axis * 30 reversePos = pos - axis * 30 track.append(Sequence(LerpPosInterval(cloud[0], 10, newPos), LerpPosInterval(cloud[0], 20, reversePos), LerpPosInterval(cloud[0], 10, pos))) return track def debugGeom(self, decomposed): print 'numPrimitives = %d' % decomposed.getNumPrimitives() for primIndex in range(decomposed.getNumPrimitives()): prim = decomposed.getPrimitive(primIndex) print 'prim = %s' % prim print 'isIndexed = %d' % prim.isIndexed() print 'prim.getNumPrimitives = %d' % prim.getNumPrimitives() for basicPrim in range(prim.getNumPrimitives()): print '%d start=%d' % (basicPrim, prim.getPrimitiveStart(basicPrim)) print '%d end=%d' % (basicPrim, prim.getPrimitiveEnd(basicPrim)) def loadCloud(self, version, radius, zOffset): self.notify.debug('loadOnePlatform version=%d' % version) cloud = NodePath('cloud-%d%d' % (radius, version)) cloudModel = loader.loadModel('phase_5.5/models/estate/bumper_cloud') cc = cloudModel.copyTo(cloud) colCube = cc.find('**/collision') colCube.setName('cloudSphere-0') dTheta = 2.0 * math.pi / self.numClouds cloud.reparentTo(self.cloudOrigin) axes = [Vec3(1, 0, 0), Vec3(0, 1, 0), Vec3(0, 0, 1)] cloud.setPos(radius * math.cos(version * dTheta), radius * math.sin(version * dTheta), 4 * random.random() + zOffset) cloud.setScale(4.0) cloud.setTag('number', '%d%d' % (radius, version)) self.clouds.append([cloud, random.choice(axes)]) def loadSkyCollision(self): plane = CollisionPlane(Plane(Vec3(0, 0, -1), Point3(0, 0, 200))) plane.setTangible(0) planeNode = CollisionNode('sky_collision') planeNode.addSolid(plane) self.cloudOrigin.attachNewNode(planeNode) def loadCloudPlatforms(self): self.cloudOrigin = self.geom.attachNewNode('cloudOrigin') self.cloudOrigin.setZ(30) self.loadSkyCollision() self.numClouds = 12 for i in range(self.numClouds): self.loadCloud(i, 50, 0) for i in range(self.numClouds): self.loadCloud(i, 70, 30) for i in range(self.numClouds): self.loadCloud(i, 30, 60) self.cloudOrigin.stash() def __cleanupCloudFadeInterval(self): if hasattr(self, 'cloudFadeInterval'): self.cloudFadeInterval.pause() self.cloudFadeInterval = None return def fadeClouds(self): self.__cleanupCloudFadeInterval() self.cloudOrigin.setTransparency(1) self.cloudFadeInterval = self.cloudOrigin.colorInterval(0.5, Vec4(1, 1, 1, int(self.cloudOrigin.isStashed())), blendType='easeIn') if self.cloudOrigin.isStashed(): self.cloudOrigin.setColor(Vec4(1, 1, 1, 0)) self.setCloudSwitch(1) else: self.cloudFadeInterval = Sequence(self.cloudFadeInterval, Func(self.setCloudSwitch, 0), Func(self.cloudOrigin.setTransparency, 0)) self.cloudFadeInterval.start() def setCloudSwitch(self, on): self.cloudSwitch = on if hasattr(self, 'cloudOrigin'): if on: self.cloudOrigin.unstash() else: self.cloudOrigin.stash() def _clearDayChangeInterval(self): if hasattr(self, 'dayChangeInterval'): self.dayChangeInterval.pause() self.dayChangeInterval = None return def switchToNight(self): self._clearDayChangeInterval() self.dayChangeInterval = Sequence(self.sunMoonNode.hprInterval(5.0, Point3(0, -30, 0), blendType='easeInOut'), Func(base.win.setClearColor, Vec4(0.15, 0.22, 0.14, 1.0))) self.dayChangeInterval.start() def switchToDay(self): self.dayChangeInterval = Sequence(Func(base.win.setClearColor, Vec4(0.47, 0.69, 0.3, 1.0)), self.sunMoonNode.hprInterval(5.0, Point3(0, 30, 0), blendType='easeInOut')) self.dayChangeInterval.start() def __handleFireworksStarted(self): self.sunMoonNode.hide() def __handleFireworksFinished(self): self.sunMoonNode.show()
40.513423
177
0.638946
b2dc7a9d1d2e3de25994b9ce7d85434696efedc9
2,780
py
Python
install.py
douglashowroyd/wallpaper-manager
cec056f15365deb9cb7a6c330d5cab6561341940
[ "MIT" ]
null
null
null
install.py
douglashowroyd/wallpaper-manager
cec056f15365deb9cb7a6c330d5cab6561341940
[ "MIT" ]
null
null
null
install.py
douglashowroyd/wallpaper-manager
cec056f15365deb9cb7a6c330d5cab6561341940
[ "MIT" ]
null
null
null
#ask for main path with warnings and all #sort folder #run random wallpaper once and record resulting image in txt file #place wallpaper_manager file as exe in startup folder (google this) # To run on setup in general: (This just puts a bat file in startup folder saying run this script) # import getpass # USER_NAME = getpass.getuser() # def add_to_startup(file_path=""): # if file_path == "": # file_path = os.path.dirname(os.path.realpath(__file__)) # bat_path = r'C:\Users\%s\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup' % USER_NAME # with open(bat_path + '\\' + "open.bat", "w+") as bat_file: # bat_file.write(r'start "" %s' % file_path) # or set through start manager # https://www.sevenforums.com/tutorials/67503-task-create-run-program-startup-log.html # need extra col in df to say if in new or old, then take weights in wm not as 1 but as weights from df over files in new #Use installer to do this, need an exe file to run during installation to create spec file and run random wallpaper once import ctypes import os import Folder_Sorter as fs import Wallpaper_Manager as wm main_path = input("Where is your wallpaper folder?:",).replace("\\","\\\\") #Add checks in here os.isdir warning = ' ' print('Warning: this program will greatly modify the given folder.') warning = input('If you would like to keep a copy please do so now. When ready to run the program please type: ready. If you would like to exit the program type: cancel',) while warning != 'ready': if warning == 'cancel': print('Cancelling...') sys.exit() print('Command not recognised, please enter either ready or cancel\n') print('Warning: this program will greatly modify the given folder.') warning = input('If you would like to keep a copy please do so now then type: ready. If you would like to exit the program type: cancel',) os.chdir(main_path) # Sort the folder fs.Move_Into_Temp() fs.Temp_To_New() fs.DataFrame_Populate() fs.Check_Errors_Folder(main_path) #Add functionality to dataframe_populate open('specs.txt', 'a').close() with open('specs.txt', 'r') as file: # read a list of lines into data specs = file.readlines() #save path to folder, current wallpaper and number of different wallpapers seen main_path = main_path.replace("\\\\","\\") specs.append(main_path+'\n') specs.append('\n') specs.append(str(0)+'\n') # and write everything back with open('specs.txt', 'w') as file: file.writelines(specs) #Just have to put run file in right place # run random wallpaper once wm.Random_Wallpaper()
26.226415
171
0.671223
75d35e6c604361dcc994eec0b9fcd391322f65d2
5,119
py
Python
test/functional/wallet-accounts.py
BayerTM/DraftCoinZ
217db2822a320d278d93dda4d3cd5dc4d01764f2
[ "MIT" ]
3
2021-03-13T23:51:40.000Z
2021-07-09T19:15:32.000Z
test/functional/wallet-accounts.py
BayerTM/DraftCoinZ
217db2822a320d278d93dda4d3cd5dc4d01764f2
[ "MIT" ]
null
null
null
test/functional/wallet-accounts.py
BayerTM/DraftCoinZ
217db2822a320d278d93dda4d3cd5dc4d01764f2
[ "MIT" ]
1
2021-04-27T21:33:59.000Z
2021-04-27T21:33:59.000Z
#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test account RPCs. RPCs tested are: - getaccountaddress - getaddressesbyaccount - listaddressgroupings - setaccount - sendfrom (with account arguments) - move (with account arguments) """ from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_equal class WalletAccountsTest(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 self.extra_args = [["-paytxfee=0.0001"]] def run_test(self): node = self.nodes[0] # Check that there's no UTXO on any of the nodes assert_equal(len(node.listunspent()), 0) # Note each time we call generate, all generated coins go into # the same address, so we call twice to get two addresses w/500 each node.generate(1) node.generate(101) assert_equal(node.getbalance(), 1000) # there should be 2 address groups # each with 1 address with a balance of 500 DFTz address_groups = node.listaddressgroupings() assert_equal(len(address_groups), 2) # the addresses aren't linked now, but will be after we send to the # common address linked_addresses = set() for address_group in address_groups: assert_equal(len(address_group), 1) assert_equal(len(address_group[0]), 2) assert_equal(address_group[0][1], 500) linked_addresses.add(address_group[0][0]) # send 500 from each address to a third address not in this wallet # There's some fee that will come back to us when the miner reward # matures. common_address = "yd5KMREs3GLMe6mTJYr3YrH1juwNwrFCfB" txid = node.sendmany( fromaccount="", amounts={common_address: 1000}, minconf=1, addlocked=False, comment="", subtractfeefrom=[common_address], ) tx_details = node.gettransaction(txid) fee = -tx_details['details'][0]['fee'] # there should be 1 address group, with the previously # unlinked addresses now linked (they both have 0 balance) address_groups = node.listaddressgroupings() assert_equal(len(address_groups), 1) assert_equal(len(address_groups[0]), 2) assert_equal(set([a[0] for a in address_groups[0]]), linked_addresses) assert_equal([a[1] for a in address_groups[0]], [0, 0]) node.generate(1) # we want to reset so that the "" account has what's expected. # otherwise we're off by exactly the fee amount as that's mined # and matures in the next 100 blocks node.sendfrom("", common_address, fee) accounts = ["a", "b", "c", "d", "e"] amount_to_send = 1.0 account_addresses = dict() for account in accounts: address = node.getaccountaddress(account) account_addresses[account] = address node.getnewaddress(account) assert_equal(node.getaccount(address), account) assert(address in node.getaddressesbyaccount(account)) node.sendfrom("", address, amount_to_send) node.generate(1) for i in range(len(accounts)): from_account = accounts[i] to_account = accounts[(i+1) % len(accounts)] to_address = account_addresses[to_account] node.sendfrom(from_account, to_address, amount_to_send) node.generate(1) for account in accounts: address = node.getaccountaddress(account) assert(address != account_addresses[account]) assert_equal(node.getreceivedbyaccount(account), 2) node.move(account, "", node.getbalance(account)) node.generate(101) expected_account_balances = {"": 52000} for account in accounts: expected_account_balances[account] = 0 assert_equal(node.listaccounts(), expected_account_balances) assert_equal(node.getbalance(""), 52000) for account in accounts: address = node.getaccountaddress("") node.setaccount(address, account) assert(address in node.getaddressesbyaccount(account)) assert(address not in node.getaddressesbyaccount("")) for account in accounts: addresses = [] for x in range(10): addresses.append(node.getnewaddress()) multisig_address = node.addmultisigaddress(5, addresses, account) node.sendfrom("", multisig_address, 50) node.generate(101) for account in accounts: assert_equal(node.getbalance(account), 50) if __name__ == '__main__': WalletAccountsTest().main()
37.639706
78
0.622387
4d01d3dda86c232dfa4dc0e8edbf5e620b1158ce
1,431
py
Python
pylibftdi/util.py
wrigby/pylibftdi
4662ebe069eefd5a89709d4165e3be808cad636c
[ "MIT" ]
14
2016-12-30T09:50:03.000Z
2022-02-11T11:07:15.000Z
pylibftdi/util.py
wrigby/pylibftdi
4662ebe069eefd5a89709d4165e3be808cad636c
[ "MIT" ]
7
2018-10-29T16:49:26.000Z
2022-01-20T22:57:59.000Z
pylibftdi/util.py
wrigby/pylibftdi
4662ebe069eefd5a89709d4165e3be808cad636c
[ "MIT" ]
8
2016-06-30T15:16:36.000Z
2022-01-31T12:36:37.000Z
""" pylibftdi - python wrapper for libftdi Copyright (c) 2010-2014 Ben Bass <benbass@codedstructure.net> See LICENSE file for details and (absence of) warranty pylibftdi: https://github.com/codedstructure/pylibftdi """ # The Bus descriptor class is probably useful outside of # pylibftdi. It tries to be to Python what bitfields are # to C. Its only requirement (which is fairly pylibftdi-ish) # is a 'device' attribute on the object this is attached # to, which has a 'port' property which is readable and # writable. class Bus(object): """ This class is a descriptor for a bus of a given width starting at a given offset (0 = LSB). The device which does the actual reading and writing is assumed to be a BitBangDevice instance in the 'device' attribute of the object to which this is attached. """ def __init__(self, offset, width=1): self.offset = offset self.width = width self._mask = ((1 << width) - 1) def __get__(self, obj, type_): val = obj.device.port return (val >> self.offset) & self._mask def __set__(self, obj, value): value = value & self._mask # in a multi-threaded environment, would # want to ensure following was locked, eg # by acquiring a device lock val = obj.device.port val &= ~(self._mask << self.offset) val |= value << self.offset obj.device.port = val
32.522727
70
0.663871
92cf15cf512bf2cdec3f2e8a3d941b54c5133f3e
187
py
Python
1064.py
heltonricardo/URI
160cca22d94aa667177c9ebf2a1c9864c5e55b41
[ "MIT" ]
6
2021-04-13T00:33:43.000Z
2022-02-10T10:23:59.000Z
1064.py
heltonricardo/URI
160cca22d94aa667177c9ebf2a1c9864c5e55b41
[ "MIT" ]
null
null
null
1064.py
heltonricardo/URI
160cca22d94aa667177c9ebf2a1c9864c5e55b41
[ "MIT" ]
3
2021-03-23T18:42:24.000Z
2022-02-10T10:24:07.000Z
s = 0 q = 0 for i in range(6): n = float(input()) if n > 0: q += 1 s += n if q != 0: m = s / q else: m = 0 print(q, 'valores positivos') print('{:.1f}'.format(m))
15.583333
29
0.449198
de79ea6b2b2da5fd58421b3b66dc93895810a488
36
py
Python
pystock/storage/__init__.py
svdh2/PyStock
d5b36bcf78f94b527d3ea27a3ce1652652bb73e5
[ "MIT" ]
null
null
null
pystock/storage/__init__.py
svdh2/PyStock
d5b36bcf78f94b527d3ea27a3ce1652652bb73e5
[ "MIT" ]
null
null
null
pystock/storage/__init__.py
svdh2/PyStock
d5b36bcf78f94b527d3ea27a3ce1652652bb73e5
[ "MIT" ]
null
null
null
print("init module storage engine")
18
35
0.777778
93d2ddfba5d048f826f7b200f6dd53df31184afc
690,318
py
Python
Lib/pydoc_data/topics.py
zyxue/cpython
ce23914d8e9b6133fd87b82c8f44ea677afb4d7d
[ "0BSD" ]
2
2017-02-27T05:22:39.000Z
2019-02-27T08:07:04.000Z
Lib/pydoc_data/topics.py
zyxue/cpython
ce23914d8e9b6133fd87b82c8f44ea677afb4d7d
[ "0BSD" ]
16
2020-10-23T21:31:06.000Z
2022-03-01T05:00:45.000Z
Lib/pydoc_data/topics.py
zyxue/cpython
ce23914d8e9b6133fd87b82c8f44ea677afb4d7d
[ "0BSD" ]
1
2021-02-23T13:37:48.000Z
2021-02-23T13:37:48.000Z
# -*- coding: utf-8 -*- # Autogenerated by Sphinx on Mon Jan 4 17:25:50 2021 topics = {'assert': 'The "assert" statement\n' '**********************\n' '\n' 'Assert statements are a convenient way to insert debugging ' 'assertions\n' 'into a program:\n' '\n' ' assert_stmt ::= "assert" expression ["," expression]\n' '\n' 'The simple form, "assert expression", is equivalent to\n' '\n' ' if __debug__:\n' ' if not expression: raise AssertionError\n' '\n' 'The extended form, "assert expression1, expression2", is ' 'equivalent to\n' '\n' ' if __debug__:\n' ' if not expression1: raise AssertionError(expression2)\n' '\n' 'These equivalences assume that "__debug__" and "AssertionError" ' 'refer\n' 'to the built-in variables with those names. In the current\n' 'implementation, the built-in variable "__debug__" is "True" under\n' 'normal circumstances, "False" when optimization is requested ' '(command\n' 'line option "-O"). The current code generator emits no code for ' 'an\n' 'assert statement when optimization is requested at compile time. ' 'Note\n' 'that it is unnecessary to include the source code for the ' 'expression\n' 'that failed in the error message; it will be displayed as part of ' 'the\n' 'stack trace.\n' '\n' 'Assignments to "__debug__" are illegal. The value for the ' 'built-in\n' 'variable is determined when the interpreter starts.\n', 'assignment': 'Assignment statements\n' '*********************\n' '\n' 'Assignment statements are used to (re)bind names to values and ' 'to\n' 'modify attributes or items of mutable objects:\n' '\n' ' assignment_stmt ::= (target_list "=")+ (starred_expression ' '| yield_expression)\n' ' target_list ::= target ("," target)* [","]\n' ' target ::= identifier\n' ' | "(" [target_list] ")"\n' ' | "[" [target_list] "]"\n' ' | attributeref\n' ' | subscription\n' ' | slicing\n' ' | "*" target\n' '\n' '(See section Primaries for the syntax definitions for ' '*attributeref*,\n' '*subscription*, and *slicing*.)\n' '\n' 'An assignment statement evaluates the expression list ' '(remember that\n' 'this can be a single expression or a comma-separated list, the ' 'latter\n' 'yielding a tuple) and assigns the single resulting object to ' 'each of\n' 'the target lists, from left to right.\n' '\n' 'Assignment is defined recursively depending on the form of the ' 'target\n' '(list). When a target is part of a mutable object (an ' 'attribute\n' 'reference, subscription or slicing), the mutable object must\n' 'ultimately perform the assignment and decide about its ' 'validity, and\n' 'may raise an exception if the assignment is unacceptable. The ' 'rules\n' 'observed by various types and the exceptions raised are given ' 'with the\n' 'definition of the object types (see section The standard type\n' 'hierarchy).\n' '\n' 'Assignment of an object to a target list, optionally enclosed ' 'in\n' 'parentheses or square brackets, is recursively defined as ' 'follows.\n' '\n' '* If the target list is a single target with no trailing ' 'comma,\n' ' optionally in parentheses, the object is assigned to that ' 'target.\n' '\n' '* Else: The object must be an iterable with the same number of ' 'items\n' ' as there are targets in the target list, and the items are ' 'assigned,\n' ' from left to right, to the corresponding targets.\n' '\n' ' * If the target list contains one target prefixed with an ' 'asterisk,\n' ' called a “starred” target: The object must be an iterable ' 'with at\n' ' least as many items as there are targets in the target ' 'list, minus\n' ' one. The first items of the iterable are assigned, from ' 'left to\n' ' right, to the targets before the starred target. The ' 'final items\n' ' of the iterable are assigned to the targets after the ' 'starred\n' ' target. A list of the remaining items in the iterable is ' 'then\n' ' assigned to the starred target (the list can be empty).\n' '\n' ' * Else: The object must be an iterable with the same number ' 'of items\n' ' as there are targets in the target list, and the items ' 'are\n' ' assigned, from left to right, to the corresponding ' 'targets.\n' '\n' 'Assignment of an object to a single target is recursively ' 'defined as\n' 'follows.\n' '\n' '* If the target is an identifier (name):\n' '\n' ' * If the name does not occur in a "global" or "nonlocal" ' 'statement\n' ' in the current code block: the name is bound to the object ' 'in the\n' ' current local namespace.\n' '\n' ' * Otherwise: the name is bound to the object in the global ' 'namespace\n' ' or the outer namespace determined by "nonlocal", ' 'respectively.\n' '\n' ' The name is rebound if it was already bound. This may cause ' 'the\n' ' reference count for the object previously bound to the name ' 'to reach\n' ' zero, causing the object to be deallocated and its ' 'destructor (if it\n' ' has one) to be called.\n' '\n' '* If the target is an attribute reference: The primary ' 'expression in\n' ' the reference is evaluated. It should yield an object with\n' ' assignable attributes; if this is not the case, "TypeError" ' 'is\n' ' raised. That object is then asked to assign the assigned ' 'object to\n' ' the given attribute; if it cannot perform the assignment, it ' 'raises\n' ' an exception (usually but not necessarily ' '"AttributeError").\n' '\n' ' Note: If the object is a class instance and the attribute ' 'reference\n' ' occurs on both sides of the assignment operator, the ' 'right-hand side\n' ' expression, "a.x" can access either an instance attribute or ' '(if no\n' ' instance attribute exists) a class attribute. The left-hand ' 'side\n' ' target "a.x" is always set as an instance attribute, ' 'creating it if\n' ' necessary. Thus, the two occurrences of "a.x" do not ' 'necessarily\n' ' refer to the same attribute: if the right-hand side ' 'expression\n' ' refers to a class attribute, the left-hand side creates a ' 'new\n' ' instance attribute as the target of the assignment:\n' '\n' ' class Cls:\n' ' x = 3 # class variable\n' ' inst = Cls()\n' ' inst.x = inst.x + 1 # writes inst.x as 4 leaving Cls.x ' 'as 3\n' '\n' ' This description does not necessarily apply to descriptor\n' ' attributes, such as properties created with "property()".\n' '\n' '* If the target is a subscription: The primary expression in ' 'the\n' ' reference is evaluated. It should yield either a mutable ' 'sequence\n' ' object (such as a list) or a mapping object (such as a ' 'dictionary).\n' ' Next, the subscript expression is evaluated.\n' '\n' ' If the primary is a mutable sequence object (such as a ' 'list), the\n' ' subscript must yield an integer. If it is negative, the ' 'sequence’s\n' ' length is added to it. The resulting value must be a ' 'nonnegative\n' ' integer less than the sequence’s length, and the sequence is ' 'asked\n' ' to assign the assigned object to its item with that index. ' 'If the\n' ' index is out of range, "IndexError" is raised (assignment to ' 'a\n' ' subscripted sequence cannot add new items to a list).\n' '\n' ' If the primary is a mapping object (such as a dictionary), ' 'the\n' ' subscript must have a type compatible with the mapping’s key ' 'type,\n' ' and the mapping is then asked to create a key/datum pair ' 'which maps\n' ' the subscript to the assigned object. This can either ' 'replace an\n' ' existing key/value pair with the same key value, or insert a ' 'new\n' ' key/value pair (if no key with the same value existed).\n' '\n' ' For user-defined objects, the "__setitem__()" method is ' 'called with\n' ' appropriate arguments.\n' '\n' '* If the target is a slicing: The primary expression in the ' 'reference\n' ' is evaluated. It should yield a mutable sequence object ' '(such as a\n' ' list). The assigned object should be a sequence object of ' 'the same\n' ' type. Next, the lower and upper bound expressions are ' 'evaluated,\n' ' insofar they are present; defaults are zero and the ' 'sequence’s\n' ' length. The bounds should evaluate to integers. If either ' 'bound is\n' ' negative, the sequence’s length is added to it. The ' 'resulting\n' ' bounds are clipped to lie between zero and the sequence’s ' 'length,\n' ' inclusive. Finally, the sequence object is asked to replace ' 'the\n' ' slice with the items of the assigned sequence. The length ' 'of the\n' ' slice may be different from the length of the assigned ' 'sequence,\n' ' thus changing the length of the target sequence, if the ' 'target\n' ' sequence allows it.\n' '\n' '**CPython implementation detail:** In the current ' 'implementation, the\n' 'syntax for targets is taken to be the same as for expressions, ' 'and\n' 'invalid syntax is rejected during the code generation phase, ' 'causing\n' 'less detailed error messages.\n' '\n' 'Although the definition of assignment implies that overlaps ' 'between\n' 'the left-hand side and the right-hand side are ‘simultaneous’ ' '(for\n' 'example "a, b = b, a" swaps two variables), overlaps *within* ' 'the\n' 'collection of assigned-to variables occur left-to-right, ' 'sometimes\n' 'resulting in confusion. For instance, the following program ' 'prints\n' '"[0, 2]":\n' '\n' ' x = [0, 1]\n' ' i = 0\n' ' i, x[i] = 1, 2 # i is updated, then x[i] is ' 'updated\n' ' print(x)\n' '\n' 'See also:\n' '\n' ' **PEP 3132** - Extended Iterable Unpacking\n' ' The specification for the "*target" feature.\n' '\n' '\n' 'Augmented assignment statements\n' '===============================\n' '\n' 'Augmented assignment is the combination, in a single ' 'statement, of a\n' 'binary operation and an assignment statement:\n' '\n' ' augmented_assignment_stmt ::= augtarget augop ' '(expression_list | yield_expression)\n' ' augtarget ::= identifier | attributeref | ' 'subscription | slicing\n' ' augop ::= "+=" | "-=" | "*=" | "@=" | ' '"/=" | "//=" | "%=" | "**="\n' ' | ">>=" | "<<=" | "&=" | "^=" | "|="\n' '\n' '(See section Primaries for the syntax definitions of the last ' 'three\n' 'symbols.)\n' '\n' 'An augmented assignment evaluates the target (which, unlike ' 'normal\n' 'assignment statements, cannot be an unpacking) and the ' 'expression\n' 'list, performs the binary operation specific to the type of ' 'assignment\n' 'on the two operands, and assigns the result to the original ' 'target.\n' 'The target is only evaluated once.\n' '\n' 'An augmented assignment expression like "x += 1" can be ' 'rewritten as\n' '"x = x + 1" to achieve a similar, but not exactly equal ' 'effect. In the\n' 'augmented version, "x" is only evaluated once. Also, when ' 'possible,\n' 'the actual operation is performed *in-place*, meaning that ' 'rather than\n' 'creating a new object and assigning that to the target, the ' 'old object\n' 'is modified instead.\n' '\n' 'Unlike normal assignments, augmented assignments evaluate the ' 'left-\n' 'hand side *before* evaluating the right-hand side. For ' 'example, "a[i]\n' '+= f(x)" first looks-up "a[i]", then it evaluates "f(x)" and ' 'performs\n' 'the addition, and lastly, it writes the result back to ' '"a[i]".\n' '\n' 'With the exception of assigning to tuples and multiple targets ' 'in a\n' 'single statement, the assignment done by augmented assignment\n' 'statements is handled the same way as normal assignments. ' 'Similarly,\n' 'with the exception of the possible *in-place* behavior, the ' 'binary\n' 'operation performed by augmented assignment is the same as the ' 'normal\n' 'binary operations.\n' '\n' 'For targets which are attribute references, the same caveat ' 'about\n' 'class and instance attributes applies as for regular ' 'assignments.\n' '\n' '\n' 'Annotated assignment statements\n' '===============================\n' '\n' '*Annotation* assignment is the combination, in a single ' 'statement, of\n' 'a variable or attribute annotation and an optional assignment\n' 'statement:\n' '\n' ' annotated_assignment_stmt ::= augtarget ":" expression\n' ' ["=" (starred_expression | ' 'yield_expression)]\n' '\n' 'The difference from normal Assignment statements is that only ' 'single\n' 'target is allowed.\n' '\n' 'For simple names as assignment targets, if in class or module ' 'scope,\n' 'the annotations are evaluated and stored in a special class or ' 'module\n' 'attribute "__annotations__" that is a dictionary mapping from ' 'variable\n' 'names (mangled if private) to evaluated annotations. This ' 'attribute is\n' 'writable and is automatically created at the start of class or ' 'module\n' 'body execution, if annotations are found statically.\n' '\n' 'For expressions as assignment targets, the annotations are ' 'evaluated\n' 'if in class or module scope, but not stored.\n' '\n' 'If a name is annotated in a function scope, then this name is ' 'local\n' 'for that scope. Annotations are never evaluated and stored in ' 'function\n' 'scopes.\n' '\n' 'If the right hand side is present, an annotated assignment ' 'performs\n' 'the actual assignment before evaluating annotations (where\n' 'applicable). If the right hand side is not present for an ' 'expression\n' 'target, then the interpreter evaluates the target except for ' 'the last\n' '"__setitem__()" or "__setattr__()" call.\n' '\n' 'See also:\n' '\n' ' **PEP 526** - Syntax for Variable Annotations\n' ' The proposal that added syntax for annotating the types ' 'of\n' ' variables (including class variables and instance ' 'variables),\n' ' instead of expressing them through comments.\n' '\n' ' **PEP 484** - Type hints\n' ' The proposal that added the "typing" module to provide a ' 'standard\n' ' syntax for type annotations that can be used in static ' 'analysis\n' ' tools and IDEs.\n' '\n' 'Changed in version 3.8: Now annotated assignments allow same\n' 'expressions in the right hand side as the regular ' 'assignments.\n' 'Previously, some expressions (like un-parenthesized tuple ' 'expressions)\n' 'caused a syntax error.\n', 'async': 'Coroutines\n' '**********\n' '\n' 'New in version 3.5.\n' '\n' '\n' 'Coroutine function definition\n' '=============================\n' '\n' ' async_funcdef ::= [decorators] "async" "def" funcname "(" ' '[parameter_list] ")"\n' ' ["->" expression] ":" suite\n' '\n' 'Execution of Python coroutines can be suspended and resumed at ' 'many\n' 'points (see *coroutine*). "await" expressions, "async for" and ' '"async\n' 'with" can only be used in the body of a coroutine function.\n' '\n' 'Functions defined with "async def" syntax are always coroutine\n' 'functions, even if they do not contain "await" or "async" ' 'keywords.\n' '\n' 'It is a "SyntaxError" to use a "yield from" expression inside the ' 'body\n' 'of a coroutine function.\n' '\n' 'An example of a coroutine function:\n' '\n' ' async def func(param1, param2):\n' ' do_stuff()\n' ' await some_coroutine()\n' '\n' 'Changed in version 3.7: "await" and "async" are now keywords;\n' 'previously they were only treated as such inside the body of a\n' 'coroutine function.\n' '\n' '\n' 'The "async for" statement\n' '=========================\n' '\n' ' async_for_stmt ::= "async" for_stmt\n' '\n' 'An *asynchronous iterable* provides an "__aiter__" method that\n' 'directly returns an *asynchronous iterator*, which can call\n' 'asynchronous code in its "__anext__" method.\n' '\n' 'The "async for" statement allows convenient iteration over\n' 'asynchronous iterables.\n' '\n' 'The following code:\n' '\n' ' async for TARGET in ITER:\n' ' SUITE\n' ' else:\n' ' SUITE2\n' '\n' 'Is semantically equivalent to:\n' '\n' ' iter = (ITER)\n' ' iter = type(iter).__aiter__(iter)\n' ' running = True\n' '\n' ' while running:\n' ' try:\n' ' TARGET = await type(iter).__anext__(iter)\n' ' except StopAsyncIteration:\n' ' running = False\n' ' else:\n' ' SUITE\n' ' else:\n' ' SUITE2\n' '\n' 'See also "__aiter__()" and "__anext__()" for details.\n' '\n' 'It is a "SyntaxError" to use an "async for" statement outside the ' 'body\n' 'of a coroutine function.\n' '\n' '\n' 'The "async with" statement\n' '==========================\n' '\n' ' async_with_stmt ::= "async" with_stmt\n' '\n' 'An *asynchronous context manager* is a *context manager* that is ' 'able\n' 'to suspend execution in its *enter* and *exit* methods.\n' '\n' 'The following code:\n' '\n' ' async with EXPRESSION as TARGET:\n' ' SUITE\n' '\n' 'is semantically equivalent to:\n' '\n' ' manager = (EXPRESSION)\n' ' aenter = type(manager).__aenter__\n' ' aexit = type(manager).__aexit__\n' ' value = await aenter(manager)\n' ' hit_except = False\n' '\n' ' try:\n' ' TARGET = value\n' ' SUITE\n' ' except:\n' ' hit_except = True\n' ' if not await aexit(manager, *sys.exc_info()):\n' ' raise\n' ' finally:\n' ' if not hit_except:\n' ' await aexit(manager, None, None, None)\n' '\n' 'See also "__aenter__()" and "__aexit__()" for details.\n' '\n' 'It is a "SyntaxError" to use an "async with" statement outside the\n' 'body of a coroutine function.\n' '\n' 'See also:\n' '\n' ' **PEP 492** - Coroutines with async and await syntax\n' ' The proposal that made coroutines a proper standalone concept ' 'in\n' ' Python, and added supporting syntax.\n' '\n' '-[ Footnotes ]-\n' '\n' '[1] The exception is propagated to the invocation stack unless ' 'there\n' ' is a "finally" clause which happens to raise another ' 'exception.\n' ' That new exception causes the old one to be lost.\n' '\n' '[2] A string literal appearing as the first statement in the ' 'function\n' ' body is transformed into the function’s "__doc__" attribute ' 'and\n' ' therefore the function’s *docstring*.\n' '\n' '[3] A string literal appearing as the first statement in the class\n' ' body is transformed into the namespace’s "__doc__" item and\n' ' therefore the class’s *docstring*.\n', 'atom-identifiers': 'Identifiers (Names)\n' '*******************\n' '\n' 'An identifier occurring as an atom is a name. See ' 'section Identifiers\n' 'and keywords for lexical definition and section Naming ' 'and binding for\n' 'documentation of naming and binding.\n' '\n' 'When the name is bound to an object, evaluation of the ' 'atom yields\n' 'that object. When a name is not bound, an attempt to ' 'evaluate it\n' 'raises a "NameError" exception.\n' '\n' '**Private name mangling:** When an identifier that ' 'textually occurs in\n' 'a class definition begins with two or more underscore ' 'characters and\n' 'does not end in two or more underscores, it is ' 'considered a *private\n' 'name* of that class. Private names are transformed to a ' 'longer form\n' 'before code is generated for them. The transformation ' 'inserts the\n' 'class name, with leading underscores removed and a ' 'single underscore\n' 'inserted, in front of the name. For example, the ' 'identifier "__spam"\n' 'occurring in a class named "Ham" will be transformed to ' '"_Ham__spam".\n' 'This transformation is independent of the syntactical ' 'context in which\n' 'the identifier is used. If the transformed name is ' 'extremely long\n' '(longer than 255 characters), implementation defined ' 'truncation may\n' 'happen. If the class name consists only of underscores, ' 'no\n' 'transformation is done.\n', 'atom-literals': 'Literals\n' '********\n' '\n' 'Python supports string and bytes literals and various ' 'numeric\n' 'literals:\n' '\n' ' literal ::= stringliteral | bytesliteral\n' ' | integer | floatnumber | imagnumber\n' '\n' 'Evaluation of a literal yields an object of the given type ' '(string,\n' 'bytes, integer, floating point number, complex number) with ' 'the given\n' 'value. The value may be approximated in the case of ' 'floating point\n' 'and imaginary (complex) literals. See section Literals for ' 'details.\n' '\n' 'All literals correspond to immutable data types, and hence ' 'the\n' 'object’s identity is less important than its value. ' 'Multiple\n' 'evaluations of literals with the same value (either the ' 'same\n' 'occurrence in the program text or a different occurrence) ' 'may obtain\n' 'the same object or a different object with the same ' 'value.\n', 'attribute-access': 'Customizing attribute access\n' '****************************\n' '\n' 'The following methods can be defined to customize the ' 'meaning of\n' 'attribute access (use of, assignment to, or deletion of ' '"x.name") for\n' 'class instances.\n' '\n' 'object.__getattr__(self, name)\n' '\n' ' Called when the default attribute access fails with ' 'an\n' ' "AttributeError" (either "__getattribute__()" raises ' 'an\n' ' "AttributeError" because *name* is not an instance ' 'attribute or an\n' ' attribute in the class tree for "self"; or ' '"__get__()" of a *name*\n' ' property raises "AttributeError"). This method ' 'should either\n' ' return the (computed) attribute value or raise an ' '"AttributeError"\n' ' exception.\n' '\n' ' Note that if the attribute is found through the ' 'normal mechanism,\n' ' "__getattr__()" is not called. (This is an ' 'intentional asymmetry\n' ' between "__getattr__()" and "__setattr__()".) This is ' 'done both for\n' ' efficiency reasons and because otherwise ' '"__getattr__()" would have\n' ' no way to access other attributes of the instance. ' 'Note that at\n' ' least for instance variables, you can fake total ' 'control by not\n' ' inserting any values in the instance attribute ' 'dictionary (but\n' ' instead inserting them in another object). See the\n' ' "__getattribute__()" method below for a way to ' 'actually get total\n' ' control over attribute access.\n' '\n' 'object.__getattribute__(self, name)\n' '\n' ' Called unconditionally to implement attribute ' 'accesses for\n' ' instances of the class. If the class also defines ' '"__getattr__()",\n' ' the latter will not be called unless ' '"__getattribute__()" either\n' ' calls it explicitly or raises an "AttributeError". ' 'This method\n' ' should return the (computed) attribute value or raise ' 'an\n' ' "AttributeError" exception. In order to avoid ' 'infinite recursion in\n' ' this method, its implementation should always call ' 'the base class\n' ' method with the same name to access any attributes it ' 'needs, for\n' ' example, "object.__getattribute__(self, name)".\n' '\n' ' Note:\n' '\n' ' This method may still be bypassed when looking up ' 'special methods\n' ' as the result of implicit invocation via language ' 'syntax or\n' ' built-in functions. See Special method lookup.\n' '\n' ' For certain sensitive attribute accesses, raises an ' 'auditing event\n' ' "object.__getattr__" with arguments "obj" and ' '"name".\n' '\n' 'object.__setattr__(self, name, value)\n' '\n' ' Called when an attribute assignment is attempted. ' 'This is called\n' ' instead of the normal mechanism (i.e. store the value ' 'in the\n' ' instance dictionary). *name* is the attribute name, ' '*value* is the\n' ' value to be assigned to it.\n' '\n' ' If "__setattr__()" wants to assign to an instance ' 'attribute, it\n' ' should call the base class method with the same name, ' 'for example,\n' ' "object.__setattr__(self, name, value)".\n' '\n' ' For certain sensitive attribute assignments, raises ' 'an auditing\n' ' event "object.__setattr__" with arguments "obj", ' '"name", "value".\n' '\n' 'object.__delattr__(self, name)\n' '\n' ' Like "__setattr__()" but for attribute deletion ' 'instead of\n' ' assignment. This should only be implemented if "del ' 'obj.name" is\n' ' meaningful for the object.\n' '\n' ' For certain sensitive attribute deletions, raises an ' 'auditing event\n' ' "object.__delattr__" with arguments "obj" and ' '"name".\n' '\n' 'object.__dir__(self)\n' '\n' ' Called when "dir()" is called on the object. A ' 'sequence must be\n' ' returned. "dir()" converts the returned sequence to a ' 'list and\n' ' sorts it.\n' '\n' '\n' 'Customizing module attribute access\n' '===================================\n' '\n' 'Special names "__getattr__" and "__dir__" can be also ' 'used to\n' 'customize access to module attributes. The "__getattr__" ' 'function at\n' 'the module level should accept one argument which is the ' 'name of an\n' 'attribute and return the computed value or raise an ' '"AttributeError".\n' 'If an attribute is not found on a module object through ' 'the normal\n' 'lookup, i.e. "object.__getattribute__()", then ' '"__getattr__" is\n' 'searched in the module "__dict__" before raising an ' '"AttributeError".\n' 'If found, it is called with the attribute name and the ' 'result is\n' 'returned.\n' '\n' 'The "__dir__" function should accept no arguments, and ' 'return a\n' 'sequence of strings that represents the names accessible ' 'on module. If\n' 'present, this function overrides the standard "dir()" ' 'search on a\n' 'module.\n' '\n' 'For a more fine grained customization of the module ' 'behavior (setting\n' 'attributes, properties, etc.), one can set the ' '"__class__" attribute\n' 'of a module object to a subclass of "types.ModuleType". ' 'For example:\n' '\n' ' import sys\n' ' from types import ModuleType\n' '\n' ' class VerboseModule(ModuleType):\n' ' def __repr__(self):\n' " return f'Verbose {self.__name__}'\n" '\n' ' def __setattr__(self, attr, value):\n' " print(f'Setting {attr}...')\n" ' super().__setattr__(attr, value)\n' '\n' ' sys.modules[__name__].__class__ = VerboseModule\n' '\n' 'Note:\n' '\n' ' Defining module "__getattr__" and setting module ' '"__class__" only\n' ' affect lookups made using the attribute access syntax ' '– directly\n' ' accessing the module globals (whether by code within ' 'the module, or\n' ' via a reference to the module’s globals dictionary) is ' 'unaffected.\n' '\n' 'Changed in version 3.5: "__class__" module attribute is ' 'now writable.\n' '\n' 'New in version 3.7: "__getattr__" and "__dir__" module ' 'attributes.\n' '\n' 'See also:\n' '\n' ' **PEP 562** - Module __getattr__ and __dir__\n' ' Describes the "__getattr__" and "__dir__" functions ' 'on modules.\n' '\n' '\n' 'Implementing Descriptors\n' '========================\n' '\n' 'The following methods only apply when an instance of the ' 'class\n' 'containing the method (a so-called *descriptor* class) ' 'appears in an\n' '*owner* class (the descriptor must be in either the ' 'owner’s class\n' 'dictionary or in the class dictionary for one of its ' 'parents). In the\n' 'examples below, “the attribute” refers to the attribute ' 'whose name is\n' 'the key of the property in the owner class’ "__dict__".\n' '\n' 'object.__get__(self, instance, owner=None)\n' '\n' ' Called to get the attribute of the owner class (class ' 'attribute\n' ' access) or of an instance of that class (instance ' 'attribute\n' ' access). The optional *owner* argument is the owner ' 'class, while\n' ' *instance* is the instance that the attribute was ' 'accessed through,\n' ' or "None" when the attribute is accessed through the ' '*owner*.\n' '\n' ' This method should return the computed attribute ' 'value or raise an\n' ' "AttributeError" exception.\n' '\n' ' **PEP 252** specifies that "__get__()" is callable ' 'with one or two\n' ' arguments. Python’s own built-in descriptors support ' 'this\n' ' specification; however, it is likely that some ' 'third-party tools\n' ' have descriptors that require both arguments. ' 'Python’s own\n' ' "__getattribute__()" implementation always passes in ' 'both arguments\n' ' whether they are required or not.\n' '\n' 'object.__set__(self, instance, value)\n' '\n' ' Called to set the attribute on an instance *instance* ' 'of the owner\n' ' class to a new value, *value*.\n' '\n' ' Note, adding "__set__()" or "__delete__()" changes ' 'the kind of\n' ' descriptor to a “data descriptor”. See Invoking ' 'Descriptors for\n' ' more details.\n' '\n' 'object.__delete__(self, instance)\n' '\n' ' Called to delete the attribute on an instance ' '*instance* of the\n' ' owner class.\n' '\n' 'object.__set_name__(self, owner, name)\n' '\n' ' Called at the time the owning class *owner* is ' 'created. The\n' ' descriptor has been assigned to *name*.\n' '\n' ' Note:\n' '\n' ' "__set_name__()" is only called implicitly as part ' 'of the "type"\n' ' constructor, so it will need to be called ' 'explicitly with the\n' ' appropriate parameters when a descriptor is added ' 'to a class\n' ' after initial creation:\n' '\n' ' class A:\n' ' pass\n' ' descr = custom_descriptor()\n' ' A.attr = descr\n' " descr.__set_name__(A, 'attr')\n" '\n' ' See Creating the class object for more details.\n' '\n' ' New in version 3.6.\n' '\n' 'The attribute "__objclass__" is interpreted by the ' '"inspect" module as\n' 'specifying the class where this object was defined ' '(setting this\n' 'appropriately can assist in runtime introspection of ' 'dynamic class\n' 'attributes). For callables, it may indicate that an ' 'instance of the\n' 'given type (or a subclass) is expected or required as ' 'the first\n' 'positional argument (for example, CPython sets this ' 'attribute for\n' 'unbound methods that are implemented in C).\n' '\n' '\n' 'Invoking Descriptors\n' '====================\n' '\n' 'In general, a descriptor is an object attribute with ' '“binding\n' 'behavior”, one whose attribute access has been ' 'overridden by methods\n' 'in the descriptor protocol: "__get__()", "__set__()", ' 'and\n' '"__delete__()". If any of those methods are defined for ' 'an object, it\n' 'is said to be a descriptor.\n' '\n' 'The default behavior for attribute access is to get, ' 'set, or delete\n' 'the attribute from an object’s dictionary. For instance, ' '"a.x" has a\n' 'lookup chain starting with "a.__dict__[\'x\']", then\n' '"type(a).__dict__[\'x\']", and continuing through the ' 'base classes of\n' '"type(a)" excluding metaclasses.\n' '\n' 'However, if the looked-up value is an object defining ' 'one of the\n' 'descriptor methods, then Python may override the default ' 'behavior and\n' 'invoke the descriptor method instead. Where this occurs ' 'in the\n' 'precedence chain depends on which descriptor methods ' 'were defined and\n' 'how they were called.\n' '\n' 'The starting point for descriptor invocation is a ' 'binding, "a.x". How\n' 'the arguments are assembled depends on "a":\n' '\n' 'Direct Call\n' ' The simplest and least common call is when user code ' 'directly\n' ' invokes a descriptor method: "x.__get__(a)".\n' '\n' 'Instance Binding\n' ' If binding to an object instance, "a.x" is ' 'transformed into the\n' ' call: "type(a).__dict__[\'x\'].__get__(a, type(a))".\n' '\n' 'Class Binding\n' ' If binding to a class, "A.x" is transformed into the ' 'call:\n' ' "A.__dict__[\'x\'].__get__(None, A)".\n' '\n' 'Super Binding\n' ' If "a" is an instance of "super", then the binding ' '"super(B,\n' ' obj).m()" searches "obj.__class__.__mro__" for the ' 'base class "A"\n' ' immediately preceding "B" and then invokes the ' 'descriptor with the\n' ' call: "A.__dict__[\'m\'].__get__(obj, ' 'obj.__class__)".\n' '\n' 'For instance bindings, the precedence of descriptor ' 'invocation depends\n' 'on the which descriptor methods are defined. A ' 'descriptor can define\n' 'any combination of "__get__()", "__set__()" and ' '"__delete__()". If it\n' 'does not define "__get__()", then accessing the ' 'attribute will return\n' 'the descriptor object itself unless there is a value in ' 'the object’s\n' 'instance dictionary. If the descriptor defines ' '"__set__()" and/or\n' '"__delete__()", it is a data descriptor; if it defines ' 'neither, it is\n' 'a non-data descriptor. Normally, data descriptors ' 'define both\n' '"__get__()" and "__set__()", while non-data descriptors ' 'have just the\n' '"__get__()" method. Data descriptors with "__get__()" ' 'and "__set__()"\n' '(and/or "__delete__()") defined always override a ' 'redefinition in an\n' 'instance dictionary. In contrast, non-data descriptors ' 'can be\n' 'overridden by instances.\n' '\n' 'Python methods (including "staticmethod()" and ' '"classmethod()") are\n' 'implemented as non-data descriptors. Accordingly, ' 'instances can\n' 'redefine and override methods. This allows individual ' 'instances to\n' 'acquire behaviors that differ from other instances of ' 'the same class.\n' '\n' 'The "property()" function is implemented as a data ' 'descriptor.\n' 'Accordingly, instances cannot override the behavior of a ' 'property.\n' '\n' '\n' '__slots__\n' '=========\n' '\n' '*__slots__* allow us to explicitly declare data members ' '(like\n' 'properties) and deny the creation of *__dict__* and ' '*__weakref__*\n' '(unless explicitly declared in *__slots__* or available ' 'in a parent.)\n' '\n' 'The space saved over using *__dict__* can be ' 'significant. Attribute\n' 'lookup speed can be significantly improved as well.\n' '\n' 'object.__slots__\n' '\n' ' This class variable can be assigned a string, ' 'iterable, or sequence\n' ' of strings with variable names used by instances. ' '*__slots__*\n' ' reserves space for the declared variables and ' 'prevents the\n' ' automatic creation of *__dict__* and *__weakref__* ' 'for each\n' ' instance.\n' '\n' '\n' 'Notes on using *__slots__*\n' '--------------------------\n' '\n' '* When inheriting from a class without *__slots__*, the ' '*__dict__* and\n' ' *__weakref__* attribute of the instances will always ' 'be accessible.\n' '\n' '* Without a *__dict__* variable, instances cannot be ' 'assigned new\n' ' variables not listed in the *__slots__* definition. ' 'Attempts to\n' ' assign to an unlisted variable name raises ' '"AttributeError". If\n' ' dynamic assignment of new variables is desired, then ' 'add\n' ' "\'__dict__\'" to the sequence of strings in the ' '*__slots__*\n' ' declaration.\n' '\n' '* Without a *__weakref__* variable for each instance, ' 'classes defining\n' ' *__slots__* do not support weak references to its ' 'instances. If weak\n' ' reference support is needed, then add ' '"\'__weakref__\'" to the\n' ' sequence of strings in the *__slots__* declaration.\n' '\n' '* *__slots__* are implemented at the class level by ' 'creating\n' ' descriptors (Implementing Descriptors) for each ' 'variable name. As a\n' ' result, class attributes cannot be used to set default ' 'values for\n' ' instance variables defined by *__slots__*; otherwise, ' 'the class\n' ' attribute would overwrite the descriptor assignment.\n' '\n' '* The action of a *__slots__* declaration is not limited ' 'to the class\n' ' where it is defined. *__slots__* declared in parents ' 'are available\n' ' in child classes. However, child subclasses will get a ' '*__dict__*\n' ' and *__weakref__* unless they also define *__slots__* ' '(which should\n' ' only contain names of any *additional* slots).\n' '\n' '* If a class defines a slot also defined in a base ' 'class, the instance\n' ' variable defined by the base class slot is ' 'inaccessible (except by\n' ' retrieving its descriptor directly from the base ' 'class). This\n' ' renders the meaning of the program undefined. In the ' 'future, a\n' ' check may be added to prevent this.\n' '\n' '* Nonempty *__slots__* does not work for classes derived ' 'from\n' ' “variable-length” built-in types such as "int", ' '"bytes" and "tuple".\n' '\n' '* Any non-string iterable may be assigned to ' '*__slots__*. Mappings may\n' ' also be used; however, in the future, special meaning ' 'may be\n' ' assigned to the values corresponding to each key.\n' '\n' '* *__class__* assignment works only if both classes have ' 'the same\n' ' *__slots__*.\n' '\n' '* Multiple inheritance with multiple slotted parent ' 'classes can be\n' ' used, but only one parent is allowed to have ' 'attributes created by\n' ' slots (the other bases must have empty slot layouts) - ' 'violations\n' ' raise "TypeError".\n' '\n' '* If an iterator is used for *__slots__* then a ' 'descriptor is created\n' ' for each of the iterator’s values. However, the ' '*__slots__*\n' ' attribute will be an empty iterator.\n', 'attribute-references': 'Attribute references\n' '********************\n' '\n' 'An attribute reference is a primary followed by a ' 'period and a name:\n' '\n' ' attributeref ::= primary "." identifier\n' '\n' 'The primary must evaluate to an object of a type ' 'that supports\n' 'attribute references, which most objects do. This ' 'object is then\n' 'asked to produce the attribute whose name is the ' 'identifier. This\n' 'production can be customized by overriding the ' '"__getattr__()" method.\n' 'If this attribute is not available, the exception ' '"AttributeError" is\n' 'raised. Otherwise, the type and value of the object ' 'produced is\n' 'determined by the object. Multiple evaluations of ' 'the same attribute\n' 'reference may yield different objects.\n', 'augassign': 'Augmented assignment statements\n' '*******************************\n' '\n' 'Augmented assignment is the combination, in a single statement, ' 'of a\n' 'binary operation and an assignment statement:\n' '\n' ' augmented_assignment_stmt ::= augtarget augop ' '(expression_list | yield_expression)\n' ' augtarget ::= identifier | attributeref | ' 'subscription | slicing\n' ' augop ::= "+=" | "-=" | "*=" | "@=" | ' '"/=" | "//=" | "%=" | "**="\n' ' | ">>=" | "<<=" | "&=" | "^=" | "|="\n' '\n' '(See section Primaries for the syntax definitions of the last ' 'three\n' 'symbols.)\n' '\n' 'An augmented assignment evaluates the target (which, unlike ' 'normal\n' 'assignment statements, cannot be an unpacking) and the ' 'expression\n' 'list, performs the binary operation specific to the type of ' 'assignment\n' 'on the two operands, and assigns the result to the original ' 'target.\n' 'The target is only evaluated once.\n' '\n' 'An augmented assignment expression like "x += 1" can be ' 'rewritten as\n' '"x = x + 1" to achieve a similar, but not exactly equal effect. ' 'In the\n' 'augmented version, "x" is only evaluated once. Also, when ' 'possible,\n' 'the actual operation is performed *in-place*, meaning that ' 'rather than\n' 'creating a new object and assigning that to the target, the old ' 'object\n' 'is modified instead.\n' '\n' 'Unlike normal assignments, augmented assignments evaluate the ' 'left-\n' 'hand side *before* evaluating the right-hand side. For ' 'example, "a[i]\n' '+= f(x)" first looks-up "a[i]", then it evaluates "f(x)" and ' 'performs\n' 'the addition, and lastly, it writes the result back to "a[i]".\n' '\n' 'With the exception of assigning to tuples and multiple targets ' 'in a\n' 'single statement, the assignment done by augmented assignment\n' 'statements is handled the same way as normal assignments. ' 'Similarly,\n' 'with the exception of the possible *in-place* behavior, the ' 'binary\n' 'operation performed by augmented assignment is the same as the ' 'normal\n' 'binary operations.\n' '\n' 'For targets which are attribute references, the same caveat ' 'about\n' 'class and instance attributes applies as for regular ' 'assignments.\n', 'await': 'Await expression\n' '****************\n' '\n' 'Suspend the execution of *coroutine* on an *awaitable* object. Can\n' 'only be used inside a *coroutine function*.\n' '\n' ' await_expr ::= "await" primary\n' '\n' 'New in version 3.5.\n', 'binary': 'Binary arithmetic operations\n' '****************************\n' '\n' 'The binary arithmetic operations have the conventional priority\n' 'levels. Note that some of these operations also apply to certain ' 'non-\n' 'numeric types. Apart from the power operator, there are only two\n' 'levels, one for multiplicative operators and one for additive\n' 'operators:\n' '\n' ' m_expr ::= u_expr | m_expr "*" u_expr | m_expr "@" m_expr |\n' ' m_expr "//" u_expr | m_expr "/" u_expr |\n' ' m_expr "%" u_expr\n' ' a_expr ::= m_expr | a_expr "+" m_expr | a_expr "-" m_expr\n' '\n' 'The "*" (multiplication) operator yields the product of its ' 'arguments.\n' 'The arguments must either both be numbers, or one argument must be ' 'an\n' 'integer and the other must be a sequence. In the former case, the\n' 'numbers are converted to a common type and then multiplied ' 'together.\n' 'In the latter case, sequence repetition is performed; a negative\n' 'repetition factor yields an empty sequence.\n' '\n' 'The "@" (at) operator is intended to be used for matrix\n' 'multiplication. No builtin Python types implement this operator.\n' '\n' 'New in version 3.5.\n' '\n' 'The "/" (division) and "//" (floor division) operators yield the\n' 'quotient of their arguments. The numeric arguments are first\n' 'converted to a common type. Division of integers yields a float, ' 'while\n' 'floor division of integers results in an integer; the result is ' 'that\n' 'of mathematical division with the ‘floor’ function applied to the\n' 'result. Division by zero raises the "ZeroDivisionError" ' 'exception.\n' '\n' 'The "%" (modulo) operator yields the remainder from the division ' 'of\n' 'the first argument by the second. The numeric arguments are ' 'first\n' 'converted to a common type. A zero right argument raises the\n' '"ZeroDivisionError" exception. The arguments may be floating ' 'point\n' 'numbers, e.g., "3.14%0.7" equals "0.34" (since "3.14" equals ' '"4*0.7 +\n' '0.34".) The modulo operator always yields a result with the same ' 'sign\n' 'as its second operand (or zero); the absolute value of the result ' 'is\n' 'strictly smaller than the absolute value of the second operand ' '[1].\n' '\n' 'The floor division and modulo operators are connected by the ' 'following\n' 'identity: "x == (x//y)*y + (x%y)". Floor division and modulo are ' 'also\n' 'connected with the built-in function "divmod()": "divmod(x, y) ==\n' '(x//y, x%y)". [2].\n' '\n' 'In addition to performing the modulo operation on numbers, the ' '"%"\n' 'operator is also overloaded by string objects to perform ' 'old-style\n' 'string formatting (also known as interpolation). The syntax for\n' 'string formatting is described in the Python Library Reference,\n' 'section printf-style String Formatting.\n' '\n' 'The floor division operator, the modulo operator, and the ' '"divmod()"\n' 'function are not defined for complex numbers. Instead, convert to ' 'a\n' 'floating point number using the "abs()" function if appropriate.\n' '\n' 'The "+" (addition) operator yields the sum of its arguments. The\n' 'arguments must either both be numbers or both be sequences of the ' 'same\n' 'type. In the former case, the numbers are converted to a common ' 'type\n' 'and then added together. In the latter case, the sequences are\n' 'concatenated.\n' '\n' 'The "-" (subtraction) operator yields the difference of its ' 'arguments.\n' 'The numeric arguments are first converted to a common type.\n', 'bitwise': 'Binary bitwise operations\n' '*************************\n' '\n' 'Each of the three bitwise operations has a different priority ' 'level:\n' '\n' ' and_expr ::= shift_expr | and_expr "&" shift_expr\n' ' xor_expr ::= and_expr | xor_expr "^" and_expr\n' ' or_expr ::= xor_expr | or_expr "|" xor_expr\n' '\n' 'The "&" operator yields the bitwise AND of its arguments, which ' 'must\n' 'be integers.\n' '\n' 'The "^" operator yields the bitwise XOR (exclusive OR) of its\n' 'arguments, which must be integers.\n' '\n' 'The "|" operator yields the bitwise (inclusive) OR of its ' 'arguments,\n' 'which must be integers.\n', 'bltin-code-objects': 'Code Objects\n' '************\n' '\n' 'Code objects are used by the implementation to ' 'represent “pseudo-\n' 'compiled” executable Python code such as a function ' 'body. They differ\n' 'from function objects because they don’t contain a ' 'reference to their\n' 'global execution environment. Code objects are ' 'returned by the built-\n' 'in "compile()" function and can be extracted from ' 'function objects\n' 'through their "__code__" attribute. See also the ' '"code" module.\n' '\n' 'A code object can be executed or evaluated by passing ' 'it (instead of a\n' 'source string) to the "exec()" or "eval()" built-in ' 'functions.\n' '\n' 'See The standard type hierarchy for more ' 'information.\n', 'bltin-ellipsis-object': 'The Ellipsis Object\n' '*******************\n' '\n' 'This object is commonly used by slicing (see ' 'Slicings). It supports\n' 'no special operations. There is exactly one ' 'ellipsis object, named\n' '"Ellipsis" (a built-in name). "type(Ellipsis)()" ' 'produces the\n' '"Ellipsis" singleton.\n' '\n' 'It is written as "Ellipsis" or "...".\n', 'bltin-null-object': 'The Null Object\n' '***************\n' '\n' 'This object is returned by functions that don’t ' 'explicitly return a\n' 'value. It supports no special operations. There is ' 'exactly one null\n' 'object, named "None" (a built-in name). "type(None)()" ' 'produces the\n' 'same singleton.\n' '\n' 'It is written as "None".\n', 'bltin-type-objects': 'Type Objects\n' '************\n' '\n' 'Type objects represent the various object types. An ' 'object’s type is\n' 'accessed by the built-in function "type()". There are ' 'no special\n' 'operations on types. The standard module "types" ' 'defines names for\n' 'all standard built-in types.\n' '\n' 'Types are written like this: "<class \'int\'>".\n', 'booleans': 'Boolean operations\n' '******************\n' '\n' ' or_test ::= and_test | or_test "or" and_test\n' ' and_test ::= not_test | and_test "and" not_test\n' ' not_test ::= comparison | "not" not_test\n' '\n' 'In the context of Boolean operations, and also when expressions ' 'are\n' 'used by control flow statements, the following values are ' 'interpreted\n' 'as false: "False", "None", numeric zero of all types, and empty\n' 'strings and containers (including strings, tuples, lists,\n' 'dictionaries, sets and frozensets). All other values are ' 'interpreted\n' 'as true. User-defined objects can customize their truth value ' 'by\n' 'providing a "__bool__()" method.\n' '\n' 'The operator "not" yields "True" if its argument is false, ' '"False"\n' 'otherwise.\n' '\n' 'The expression "x and y" first evaluates *x*; if *x* is false, ' 'its\n' 'value is returned; otherwise, *y* is evaluated and the resulting ' 'value\n' 'is returned.\n' '\n' 'The expression "x or y" first evaluates *x*; if *x* is true, its ' 'value\n' 'is returned; otherwise, *y* is evaluated and the resulting value ' 'is\n' 'returned.\n' '\n' 'Note that neither "and" nor "or" restrict the value and type ' 'they\n' 'return to "False" and "True", but rather return the last ' 'evaluated\n' 'argument. This is sometimes useful, e.g., if "s" is a string ' 'that\n' 'should be replaced by a default value if it is empty, the ' 'expression\n' '"s or \'foo\'" yields the desired value. Because "not" has to ' 'create a\n' 'new value, it returns a boolean value regardless of the type of ' 'its\n' 'argument (for example, "not \'foo\'" produces "False" rather ' 'than "\'\'".)\n', 'break': 'The "break" statement\n' '*********************\n' '\n' ' break_stmt ::= "break"\n' '\n' '"break" may only occur syntactically nested in a "for" or "while"\n' 'loop, but not nested in a function or class definition within that\n' 'loop.\n' '\n' 'It terminates the nearest enclosing loop, skipping the optional ' '"else"\n' 'clause if the loop has one.\n' '\n' 'If a "for" loop is terminated by "break", the loop control target\n' 'keeps its current value.\n' '\n' 'When "break" passes control out of a "try" statement with a ' '"finally"\n' 'clause, that "finally" clause is executed before really leaving ' 'the\n' 'loop.\n', 'callable-types': 'Emulating callable objects\n' '**************************\n' '\n' 'object.__call__(self[, args...])\n' '\n' ' Called when the instance is “called” as a function; if ' 'this method\n' ' is defined, "x(arg1, arg2, ...)" roughly translates to\n' ' "type(x).__call__(x, arg1, ...)".\n', 'calls': 'Calls\n' '*****\n' '\n' 'A call calls a callable object (e.g., a *function*) with a ' 'possibly\n' 'empty series of *arguments*:\n' '\n' ' call ::= primary "(" [argument_list [","] | ' 'comprehension] ")"\n' ' argument_list ::= positional_arguments ["," ' 'starred_and_keywords]\n' ' ["," keywords_arguments]\n' ' | starred_and_keywords ["," ' 'keywords_arguments]\n' ' | keywords_arguments\n' ' positional_arguments ::= positional_item ("," positional_item)*\n' ' positional_item ::= assignment_expression | "*" expression\n' ' starred_and_keywords ::= ("*" expression | keyword_item)\n' ' ("," "*" expression | "," ' 'keyword_item)*\n' ' keywords_arguments ::= (keyword_item | "**" expression)\n' ' ("," keyword_item | "," "**" ' 'expression)*\n' ' keyword_item ::= identifier "=" expression\n' '\n' 'An optional trailing comma may be present after the positional and\n' 'keyword arguments but does not affect the semantics.\n' '\n' 'The primary must evaluate to a callable object (user-defined\n' 'functions, built-in functions, methods of built-in objects, class\n' 'objects, methods of class instances, and all objects having a\n' '"__call__()" method are callable). All argument expressions are\n' 'evaluated before the call is attempted. Please refer to section\n' 'Function definitions for the syntax of formal *parameter* lists.\n' '\n' 'If keyword arguments are present, they are first converted to\n' 'positional arguments, as follows. First, a list of unfilled slots ' 'is\n' 'created for the formal parameters. If there are N positional\n' 'arguments, they are placed in the first N slots. Next, for each\n' 'keyword argument, the identifier is used to determine the\n' 'corresponding slot (if the identifier is the same as the first ' 'formal\n' 'parameter name, the first slot is used, and so on). If the slot ' 'is\n' 'already filled, a "TypeError" exception is raised. Otherwise, the\n' 'value of the argument is placed in the slot, filling it (even if ' 'the\n' 'expression is "None", it fills the slot). When all arguments have\n' 'been processed, the slots that are still unfilled are filled with ' 'the\n' 'corresponding default value from the function definition. ' '(Default\n' 'values are calculated, once, when the function is defined; thus, a\n' 'mutable object such as a list or dictionary used as default value ' 'will\n' 'be shared by all calls that don’t specify an argument value for ' 'the\n' 'corresponding slot; this should usually be avoided.) If there are ' 'any\n' 'unfilled slots for which no default value is specified, a ' '"TypeError"\n' 'exception is raised. Otherwise, the list of filled slots is used ' 'as\n' 'the argument list for the call.\n' '\n' '**CPython implementation detail:** An implementation may provide\n' 'built-in functions whose positional parameters do not have names, ' 'even\n' 'if they are ‘named’ for the purpose of documentation, and which\n' 'therefore cannot be supplied by keyword. In CPython, this is the ' 'case\n' 'for functions implemented in C that use "PyArg_ParseTuple()" to ' 'parse\n' 'their arguments.\n' '\n' 'If there are more positional arguments than there are formal ' 'parameter\n' 'slots, a "TypeError" exception is raised, unless a formal ' 'parameter\n' 'using the syntax "*identifier" is present; in this case, that ' 'formal\n' 'parameter receives a tuple containing the excess positional ' 'arguments\n' '(or an empty tuple if there were no excess positional arguments).\n' '\n' 'If any keyword argument does not correspond to a formal parameter\n' 'name, a "TypeError" exception is raised, unless a formal parameter\n' 'using the syntax "**identifier" is present; in this case, that ' 'formal\n' 'parameter receives a dictionary containing the excess keyword\n' 'arguments (using the keywords as keys and the argument values as\n' 'corresponding values), or a (new) empty dictionary if there were ' 'no\n' 'excess keyword arguments.\n' '\n' 'If the syntax "*expression" appears in the function call, ' '"expression"\n' 'must evaluate to an *iterable*. Elements from these iterables are\n' 'treated as if they were additional positional arguments. For the ' 'call\n' '"f(x1, x2, *y, x3, x4)", if *y* evaluates to a sequence *y1*, …, ' '*yM*,\n' 'this is equivalent to a call with M+4 positional arguments *x1*, ' '*x2*,\n' '*y1*, …, *yM*, *x3*, *x4*.\n' '\n' 'A consequence of this is that although the "*expression" syntax ' 'may\n' 'appear *after* explicit keyword arguments, it is processed ' '*before*\n' 'the keyword arguments (and any "**expression" arguments – see ' 'below).\n' 'So:\n' '\n' ' >>> def f(a, b):\n' ' ... print(a, b)\n' ' ...\n' ' >>> f(b=1, *(2,))\n' ' 2 1\n' ' >>> f(a=1, *(2,))\n' ' Traceback (most recent call last):\n' ' File "<stdin>", line 1, in <module>\n' " TypeError: f() got multiple values for keyword argument 'a'\n" ' >>> f(1, *(2,))\n' ' 1 2\n' '\n' 'It is unusual for both keyword arguments and the "*expression" ' 'syntax\n' 'to be used in the same call, so in practice this confusion does ' 'not\n' 'arise.\n' '\n' 'If the syntax "**expression" appears in the function call,\n' '"expression" must evaluate to a *mapping*, the contents of which ' 'are\n' 'treated as additional keyword arguments. If a keyword is already\n' 'present (as an explicit keyword argument, or from another ' 'unpacking),\n' 'a "TypeError" exception is raised.\n' '\n' 'Formal parameters using the syntax "*identifier" or "**identifier"\n' 'cannot be used as positional argument slots or as keyword argument\n' 'names.\n' '\n' 'Changed in version 3.5: Function calls accept any number of "*" ' 'and\n' '"**" unpackings, positional arguments may follow iterable ' 'unpackings\n' '("*"), and keyword arguments may follow dictionary unpackings ' '("**").\n' 'Originally proposed by **PEP 448**.\n' '\n' 'A call always returns some value, possibly "None", unless it raises ' 'an\n' 'exception. How this value is computed depends on the type of the\n' 'callable object.\n' '\n' 'If it is—\n' '\n' 'a user-defined function:\n' ' The code block for the function is executed, passing it the\n' ' argument list. The first thing the code block will do is bind ' 'the\n' ' formal parameters to the arguments; this is described in ' 'section\n' ' Function definitions. When the code block executes a "return"\n' ' statement, this specifies the return value of the function ' 'call.\n' '\n' 'a built-in function or method:\n' ' The result is up to the interpreter; see Built-in Functions for ' 'the\n' ' descriptions of built-in functions and methods.\n' '\n' 'a class object:\n' ' A new instance of that class is returned.\n' '\n' 'a class instance method:\n' ' The corresponding user-defined function is called, with an ' 'argument\n' ' list that is one longer than the argument list of the call: the\n' ' instance becomes the first argument.\n' '\n' 'a class instance:\n' ' The class must define a "__call__()" method; the effect is then ' 'the\n' ' same as if that method was called.\n', 'class': 'Class definitions\n' '*****************\n' '\n' 'A class definition defines a class object (see section The ' 'standard\n' 'type hierarchy):\n' '\n' ' classdef ::= [decorators] "class" classname [inheritance] ":" ' 'suite\n' ' inheritance ::= "(" [argument_list] ")"\n' ' classname ::= identifier\n' '\n' 'A class definition is an executable statement. The inheritance ' 'list\n' 'usually gives a list of base classes (see Metaclasses for more\n' 'advanced uses), so each item in the list should evaluate to a ' 'class\n' 'object which allows subclassing. Classes without an inheritance ' 'list\n' 'inherit, by default, from the base class "object"; hence,\n' '\n' ' class Foo:\n' ' pass\n' '\n' 'is equivalent to\n' '\n' ' class Foo(object):\n' ' pass\n' '\n' 'The class’s suite is then executed in a new execution frame (see\n' 'Naming and binding), using a newly created local namespace and the\n' 'original global namespace. (Usually, the suite contains mostly\n' 'function definitions.) When the class’s suite finishes execution, ' 'its\n' 'execution frame is discarded but its local namespace is saved. [3] ' 'A\n' 'class object is then created using the inheritance list for the ' 'base\n' 'classes and the saved local namespace for the attribute ' 'dictionary.\n' 'The class name is bound to this class object in the original local\n' 'namespace.\n' '\n' 'The order in which attributes are defined in the class body is\n' 'preserved in the new class’s "__dict__". Note that this is ' 'reliable\n' 'only right after the class is created and only for classes that ' 'were\n' 'defined using the definition syntax.\n' '\n' 'Class creation can be customized heavily using metaclasses.\n' '\n' 'Classes can also be decorated: just like when decorating ' 'functions,\n' '\n' ' @f1(arg)\n' ' @f2\n' ' class Foo: pass\n' '\n' 'is roughly equivalent to\n' '\n' ' class Foo: pass\n' ' Foo = f1(arg)(f2(Foo))\n' '\n' 'The evaluation rules for the decorator expressions are the same as ' 'for\n' 'function decorators. The result is then bound to the class name.\n' '\n' 'Changed in version 3.9: Classes may be decorated with any valid\n' '"assignment_expression". Previously, the grammar was much more\n' 'restrictive; see **PEP 614** for details.\n' '\n' '**Programmer’s note:** Variables defined in the class definition ' 'are\n' 'class attributes; they are shared by instances. Instance ' 'attributes\n' 'can be set in a method with "self.name = value". Both class and\n' 'instance attributes are accessible through the notation ' '“"self.name"”,\n' 'and an instance attribute hides a class attribute with the same ' 'name\n' 'when accessed in this way. Class attributes can be used as ' 'defaults\n' 'for instance attributes, but using mutable values there can lead ' 'to\n' 'unexpected results. Descriptors can be used to create instance\n' 'variables with different implementation details.\n' '\n' 'See also:\n' '\n' ' **PEP 3115** - Metaclasses in Python 3000\n' ' The proposal that changed the declaration of metaclasses to ' 'the\n' ' current syntax, and the semantics for how classes with\n' ' metaclasses are constructed.\n' '\n' ' **PEP 3129** - Class Decorators\n' ' The proposal that added class decorators. Function and ' 'method\n' ' decorators were introduced in **PEP 318**.\n', 'comparisons': 'Comparisons\n' '***********\n' '\n' 'Unlike C, all comparison operations in Python have the same ' 'priority,\n' 'which is lower than that of any arithmetic, shifting or ' 'bitwise\n' 'operation. Also unlike C, expressions like "a < b < c" have ' 'the\n' 'interpretation that is conventional in mathematics:\n' '\n' ' comparison ::= or_expr (comp_operator or_expr)*\n' ' comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!="\n' ' | "is" ["not"] | ["not"] "in"\n' '\n' 'Comparisons yield boolean values: "True" or "False".\n' '\n' 'Comparisons can be chained arbitrarily, e.g., "x < y <= z" ' 'is\n' 'equivalent to "x < y and y <= z", except that "y" is ' 'evaluated only\n' 'once (but in both cases "z" is not evaluated at all when "x < ' 'y" is\n' 'found to be false).\n' '\n' 'Formally, if *a*, *b*, *c*, …, *y*, *z* are expressions and ' '*op1*,\n' '*op2*, …, *opN* are comparison operators, then "a op1 b op2 c ' '... y\n' 'opN z" is equivalent to "a op1 b and b op2 c and ... y opN ' 'z", except\n' 'that each expression is evaluated at most once.\n' '\n' 'Note that "a op1 b op2 c" doesn’t imply any kind of ' 'comparison between\n' '*a* and *c*, so that, e.g., "x < y > z" is perfectly legal ' '(though\n' 'perhaps not pretty).\n' '\n' '\n' 'Value comparisons\n' '=================\n' '\n' 'The operators "<", ">", "==", ">=", "<=", and "!=" compare ' 'the values\n' 'of two objects. The objects do not need to have the same ' 'type.\n' '\n' 'Chapter Objects, values and types states that objects have a ' 'value (in\n' 'addition to type and identity). The value of an object is a ' 'rather\n' 'abstract notion in Python: For example, there is no canonical ' 'access\n' 'method for an object’s value. Also, there is no requirement ' 'that the\n' 'value of an object should be constructed in a particular way, ' 'e.g.\n' 'comprised of all its data attributes. Comparison operators ' 'implement a\n' 'particular notion of what the value of an object is. One can ' 'think of\n' 'them as defining the value of an object indirectly, by means ' 'of their\n' 'comparison implementation.\n' '\n' 'Because all types are (direct or indirect) subtypes of ' '"object", they\n' 'inherit the default comparison behavior from "object". Types ' 'can\n' 'customize their comparison behavior by implementing *rich ' 'comparison\n' 'methods* like "__lt__()", described in Basic customization.\n' '\n' 'The default behavior for equality comparison ("==" and "!=") ' 'is based\n' 'on the identity of the objects. Hence, equality comparison ' 'of\n' 'instances with the same identity results in equality, and ' 'equality\n' 'comparison of instances with different identities results in\n' 'inequality. A motivation for this default behavior is the ' 'desire that\n' 'all objects should be reflexive (i.e. "x is y" implies "x == ' 'y").\n' '\n' 'A default order comparison ("<", ">", "<=", and ">=") is not ' 'provided;\n' 'an attempt raises "TypeError". A motivation for this default ' 'behavior\n' 'is the lack of a similar invariant as for equality.\n' '\n' 'The behavior of the default equality comparison, that ' 'instances with\n' 'different identities are always unequal, may be in contrast ' 'to what\n' 'types will need that have a sensible definition of object ' 'value and\n' 'value-based equality. Such types will need to customize ' 'their\n' 'comparison behavior, and in fact, a number of built-in types ' 'have done\n' 'that.\n' '\n' 'The following list describes the comparison behavior of the ' 'most\n' 'important built-in types.\n' '\n' '* Numbers of built-in numeric types (Numeric Types — int, ' 'float,\n' ' complex) and of the standard library types ' '"fractions.Fraction" and\n' ' "decimal.Decimal" can be compared within and across their ' 'types,\n' ' with the restriction that complex numbers do not support ' 'order\n' ' comparison. Within the limits of the types involved, they ' 'compare\n' ' mathematically (algorithmically) correct without loss of ' 'precision.\n' '\n' ' The not-a-number values "float(\'NaN\')" and ' '"decimal.Decimal(\'NaN\')"\n' ' are special. Any ordered comparison of a number to a ' 'not-a-number\n' ' value is false. A counter-intuitive implication is that ' 'not-a-number\n' ' values are not equal to themselves. For example, if "x =\n' ' float(\'NaN\')", "3 < x", "x < 3" and "x == x" are all ' 'false, while "x\n' ' != x" is true. This behavior is compliant with IEEE 754.\n' '\n' '* "None" and "NotImplemented" are singletons. **PEP 8** ' 'advises that\n' ' comparisons for singletons should always be done with "is" ' 'or "is\n' ' not", never the equality operators.\n' '\n' '* Binary sequences (instances of "bytes" or "bytearray") can ' 'be\n' ' compared within and across their types. They compare\n' ' lexicographically using the numeric values of their ' 'elements.\n' '\n' '* Strings (instances of "str") compare lexicographically ' 'using the\n' ' numerical Unicode code points (the result of the built-in ' 'function\n' ' "ord()") of their characters. [3]\n' '\n' ' Strings and binary sequences cannot be directly compared.\n' '\n' '* Sequences (instances of "tuple", "list", or "range") can be ' 'compared\n' ' only within each of their types, with the restriction that ' 'ranges do\n' ' not support order comparison. Equality comparison across ' 'these\n' ' types results in inequality, and ordering comparison across ' 'these\n' ' types raises "TypeError".\n' '\n' ' Sequences compare lexicographically using comparison of\n' ' corresponding elements. The built-in containers typically ' 'assume\n' ' identical objects are equal to themselves. That lets them ' 'bypass\n' ' equality tests for identical objects to improve performance ' 'and to\n' ' maintain their internal invariants.\n' '\n' ' Lexicographical comparison between built-in collections ' 'works as\n' ' follows:\n' '\n' ' * For two collections to compare equal, they must be of the ' 'same\n' ' type, have the same length, and each pair of ' 'corresponding\n' ' elements must compare equal (for example, "[1,2] == ' '(1,2)" is\n' ' false because the type is not the same).\n' '\n' ' * Collections that support order comparison are ordered the ' 'same as\n' ' their first unequal elements (for example, "[1,2,x] <= ' '[1,2,y]"\n' ' has the same value as "x <= y"). If a corresponding ' 'element does\n' ' not exist, the shorter collection is ordered first (for ' 'example,\n' ' "[1,2] < [1,2,3]" is true).\n' '\n' '* Mappings (instances of "dict") compare equal if and only if ' 'they\n' ' have equal *(key, value)* pairs. Equality comparison of the ' 'keys and\n' ' values enforces reflexivity.\n' '\n' ' Order comparisons ("<", ">", "<=", and ">=") raise ' '"TypeError".\n' '\n' '* Sets (instances of "set" or "frozenset") can be compared ' 'within and\n' ' across their types.\n' '\n' ' They define order comparison operators to mean subset and ' 'superset\n' ' tests. Those relations do not define total orderings (for ' 'example,\n' ' the two sets "{1,2}" and "{2,3}" are not equal, nor subsets ' 'of one\n' ' another, nor supersets of one another). Accordingly, sets ' 'are not\n' ' appropriate arguments for functions which depend on total ' 'ordering\n' ' (for example, "min()", "max()", and "sorted()" produce ' 'undefined\n' ' results given a list of sets as inputs).\n' '\n' ' Comparison of sets enforces reflexivity of its elements.\n' '\n' '* Most other built-in types have no comparison methods ' 'implemented, so\n' ' they inherit the default comparison behavior.\n' '\n' 'User-defined classes that customize their comparison behavior ' 'should\n' 'follow some consistency rules, if possible:\n' '\n' '* Equality comparison should be reflexive. In other words, ' 'identical\n' ' objects should compare equal:\n' '\n' ' "x is y" implies "x == y"\n' '\n' '* Comparison should be symmetric. In other words, the ' 'following\n' ' expressions should have the same result:\n' '\n' ' "x == y" and "y == x"\n' '\n' ' "x != y" and "y != x"\n' '\n' ' "x < y" and "y > x"\n' '\n' ' "x <= y" and "y >= x"\n' '\n' '* Comparison should be transitive. The following ' '(non-exhaustive)\n' ' examples illustrate that:\n' '\n' ' "x > y and y > z" implies "x > z"\n' '\n' ' "x < y and y <= z" implies "x < z"\n' '\n' '* Inverse comparison should result in the boolean negation. ' 'In other\n' ' words, the following expressions should have the same ' 'result:\n' '\n' ' "x == y" and "not x != y"\n' '\n' ' "x < y" and "not x >= y" (for total ordering)\n' '\n' ' "x > y" and "not x <= y" (for total ordering)\n' '\n' ' The last two expressions apply to totally ordered ' 'collections (e.g.\n' ' to sequences, but not to sets or mappings). See also the\n' ' "total_ordering()" decorator.\n' '\n' '* The "hash()" result should be consistent with equality. ' 'Objects that\n' ' are equal should either have the same hash value, or be ' 'marked as\n' ' unhashable.\n' '\n' 'Python does not enforce these consistency rules. In fact, ' 'the\n' 'not-a-number values are an example for not following these ' 'rules.\n' '\n' '\n' 'Membership test operations\n' '==========================\n' '\n' 'The operators "in" and "not in" test for membership. "x in ' 's"\n' 'evaluates to "True" if *x* is a member of *s*, and "False" ' 'otherwise.\n' '"x not in s" returns the negation of "x in s". All built-in ' 'sequences\n' 'and set types support this as well as dictionary, for which ' '"in" tests\n' 'whether the dictionary has a given key. For container types ' 'such as\n' 'list, tuple, set, frozenset, dict, or collections.deque, the\n' 'expression "x in y" is equivalent to "any(x is e or x == e ' 'for e in\n' 'y)".\n' '\n' 'For the string and bytes types, "x in y" is "True" if and ' 'only if *x*\n' 'is a substring of *y*. An equivalent test is "y.find(x) != ' '-1".\n' 'Empty strings are always considered to be a substring of any ' 'other\n' 'string, so """ in "abc"" will return "True".\n' '\n' 'For user-defined classes which define the "__contains__()" ' 'method, "x\n' 'in y" returns "True" if "y.__contains__(x)" returns a true ' 'value, and\n' '"False" otherwise.\n' '\n' 'For user-defined classes which do not define "__contains__()" ' 'but do\n' 'define "__iter__()", "x in y" is "True" if some value "z", ' 'for which\n' 'the expression "x is z or x == z" is true, is produced while ' 'iterating\n' 'over "y". If an exception is raised during the iteration, it ' 'is as if\n' '"in" raised that exception.\n' '\n' 'Lastly, the old-style iteration protocol is tried: if a class ' 'defines\n' '"__getitem__()", "x in y" is "True" if and only if there is a ' 'non-\n' 'negative integer index *i* such that "x is y[i] or x == ' 'y[i]", and no\n' 'lower integer index raises the "IndexError" exception. (If ' 'any other\n' 'exception is raised, it is as if "in" raised that ' 'exception).\n' '\n' 'The operator "not in" is defined to have the inverse truth ' 'value of\n' '"in".\n' '\n' '\n' 'Identity comparisons\n' '====================\n' '\n' 'The operators "is" and "is not" test for an object’s ' 'identity: "x is\n' 'y" is true if and only if *x* and *y* are the same object. ' 'An\n' 'Object’s identity is determined using the "id()" function. ' '"x is not\n' 'y" yields the inverse truth value. [4]\n', 'compound': 'Compound statements\n' '*******************\n' '\n' 'Compound statements contain (groups of) other statements; they ' 'affect\n' 'or control the execution of those other statements in some way. ' 'In\n' 'general, compound statements span multiple lines, although in ' 'simple\n' 'incarnations a whole compound statement may be contained in one ' 'line.\n' '\n' 'The "if", "while" and "for" statements implement traditional ' 'control\n' 'flow constructs. "try" specifies exception handlers and/or ' 'cleanup\n' 'code for a group of statements, while the "with" statement ' 'allows the\n' 'execution of initialization and finalization code around a block ' 'of\n' 'code. Function and class definitions are also syntactically ' 'compound\n' 'statements.\n' '\n' 'A compound statement consists of one or more ‘clauses.’ A ' 'clause\n' 'consists of a header and a ‘suite.’ The clause headers of a\n' 'particular compound statement are all at the same indentation ' 'level.\n' 'Each clause header begins with a uniquely identifying keyword ' 'and ends\n' 'with a colon. A suite is a group of statements controlled by a\n' 'clause. A suite can be one or more semicolon-separated simple\n' 'statements on the same line as the header, following the ' 'header’s\n' 'colon, or it can be one or more indented statements on ' 'subsequent\n' 'lines. Only the latter form of a suite can contain nested ' 'compound\n' 'statements; the following is illegal, mostly because it wouldn’t ' 'be\n' 'clear to which "if" clause a following "else" clause would ' 'belong:\n' '\n' ' if test1: if test2: print(x)\n' '\n' 'Also note that the semicolon binds tighter than the colon in ' 'this\n' 'context, so that in the following example, either all or none of ' 'the\n' '"print()" calls are executed:\n' '\n' ' if x < y < z: print(x); print(y); print(z)\n' '\n' 'Summarizing:\n' '\n' ' compound_stmt ::= if_stmt\n' ' | while_stmt\n' ' | for_stmt\n' ' | try_stmt\n' ' | with_stmt\n' ' | funcdef\n' ' | classdef\n' ' | async_with_stmt\n' ' | async_for_stmt\n' ' | async_funcdef\n' ' suite ::= stmt_list NEWLINE | NEWLINE INDENT ' 'statement+ DEDENT\n' ' statement ::= stmt_list NEWLINE | compound_stmt\n' ' stmt_list ::= simple_stmt (";" simple_stmt)* [";"]\n' '\n' 'Note that statements always end in a "NEWLINE" possibly followed ' 'by a\n' '"DEDENT". Also note that optional continuation clauses always ' 'begin\n' 'with a keyword that cannot start a statement, thus there are no\n' 'ambiguities (the ‘dangling "else"’ problem is solved in Python ' 'by\n' 'requiring nested "if" statements to be indented).\n' '\n' 'The formatting of the grammar rules in the following sections ' 'places\n' 'each clause on a separate line for clarity.\n' '\n' '\n' 'The "if" statement\n' '==================\n' '\n' 'The "if" statement is used for conditional execution:\n' '\n' ' if_stmt ::= "if" assignment_expression ":" suite\n' ' ("elif" assignment_expression ":" suite)*\n' ' ["else" ":" suite]\n' '\n' 'It selects exactly one of the suites by evaluating the ' 'expressions one\n' 'by one until one is found to be true (see section Boolean ' 'operations\n' 'for the definition of true and false); then that suite is ' 'executed\n' '(and no other part of the "if" statement is executed or ' 'evaluated).\n' 'If all expressions are false, the suite of the "else" clause, ' 'if\n' 'present, is executed.\n' '\n' '\n' 'The "while" statement\n' '=====================\n' '\n' 'The "while" statement is used for repeated execution as long as ' 'an\n' 'expression is true:\n' '\n' ' while_stmt ::= "while" assignment_expression ":" suite\n' ' ["else" ":" suite]\n' '\n' 'This repeatedly tests the expression and, if it is true, ' 'executes the\n' 'first suite; if the expression is false (which may be the first ' 'time\n' 'it is tested) the suite of the "else" clause, if present, is ' 'executed\n' 'and the loop terminates.\n' '\n' 'A "break" statement executed in the first suite terminates the ' 'loop\n' 'without executing the "else" clause’s suite. A "continue" ' 'statement\n' 'executed in the first suite skips the rest of the suite and goes ' 'back\n' 'to testing the expression.\n' '\n' '\n' 'The "for" statement\n' '===================\n' '\n' 'The "for" statement is used to iterate over the elements of a ' 'sequence\n' '(such as a string, tuple or list) or other iterable object:\n' '\n' ' for_stmt ::= "for" target_list "in" expression_list ":" ' 'suite\n' ' ["else" ":" suite]\n' '\n' 'The expression list is evaluated once; it should yield an ' 'iterable\n' 'object. An iterator is created for the result of the\n' '"expression_list". The suite is then executed once for each ' 'item\n' 'provided by the iterator, in the order returned by the ' 'iterator. Each\n' 'item in turn is assigned to the target list using the standard ' 'rules\n' 'for assignments (see Assignment statements), and then the suite ' 'is\n' 'executed. When the items are exhausted (which is immediately ' 'when the\n' 'sequence is empty or an iterator raises a "StopIteration" ' 'exception),\n' 'the suite in the "else" clause, if present, is executed, and the ' 'loop\n' 'terminates.\n' '\n' 'A "break" statement executed in the first suite terminates the ' 'loop\n' 'without executing the "else" clause’s suite. A "continue" ' 'statement\n' 'executed in the first suite skips the rest of the suite and ' 'continues\n' 'with the next item, or with the "else" clause if there is no ' 'next\n' 'item.\n' '\n' 'The for-loop makes assignments to the variables in the target ' 'list.\n' 'This overwrites all previous assignments to those variables ' 'including\n' 'those made in the suite of the for-loop:\n' '\n' ' for i in range(10):\n' ' print(i)\n' ' i = 5 # this will not affect the for-loop\n' ' # because i will be overwritten with ' 'the next\n' ' # index in the range\n' '\n' 'Names in the target list are not deleted when the loop is ' 'finished,\n' 'but if the sequence is empty, they will not have been assigned ' 'to at\n' 'all by the loop. Hint: the built-in function "range()" returns ' 'an\n' 'iterator of integers suitable to emulate the effect of Pascal’s ' '"for i\n' ':= a to b do"; e.g., "list(range(3))" returns the list "[0, 1, ' '2]".\n' '\n' 'Note:\n' '\n' ' There is a subtlety when the sequence is being modified by the ' 'loop\n' ' (this can only occur for mutable sequences, e.g. lists). An\n' ' internal counter is used to keep track of which item is used ' 'next,\n' ' and this is incremented on each iteration. When this counter ' 'has\n' ' reached the length of the sequence the loop terminates. This ' 'means\n' ' that if the suite deletes the current (or a previous) item ' 'from the\n' ' sequence, the next item will be skipped (since it gets the ' 'index of\n' ' the current item which has already been treated). Likewise, ' 'if the\n' ' suite inserts an item in the sequence before the current item, ' 'the\n' ' current item will be treated again the next time through the ' 'loop.\n' ' This can lead to nasty bugs that can be avoided by making a\n' ' temporary copy using a slice of the whole sequence, e.g.,\n' '\n' ' for x in a[:]:\n' ' if x < 0: a.remove(x)\n' '\n' '\n' 'The "try" statement\n' '===================\n' '\n' 'The "try" statement specifies exception handlers and/or cleanup ' 'code\n' 'for a group of statements:\n' '\n' ' try_stmt ::= try1_stmt | try2_stmt\n' ' try1_stmt ::= "try" ":" suite\n' ' ("except" [expression ["as" identifier]] ":" ' 'suite)+\n' ' ["else" ":" suite]\n' ' ["finally" ":" suite]\n' ' try2_stmt ::= "try" ":" suite\n' ' "finally" ":" suite\n' '\n' 'The "except" clause(s) specify one or more exception handlers. ' 'When no\n' 'exception occurs in the "try" clause, no exception handler is\n' 'executed. When an exception occurs in the "try" suite, a search ' 'for an\n' 'exception handler is started. This search inspects the except ' 'clauses\n' 'in turn until one is found that matches the exception. An ' 'expression-\n' 'less except clause, if present, must be last; it matches any\n' 'exception. For an except clause with an expression, that ' 'expression\n' 'is evaluated, and the clause matches the exception if the ' 'resulting\n' 'object is “compatible” with the exception. An object is ' 'compatible\n' 'with an exception if it is the class or a base class of the ' 'exception\n' 'object, or a tuple containing an item that is the class or a ' 'base\n' 'class of the exception object.\n' '\n' 'If no except clause matches the exception, the search for an ' 'exception\n' 'handler continues in the surrounding code and on the invocation ' 'stack.\n' '[1]\n' '\n' 'If the evaluation of an expression in the header of an except ' 'clause\n' 'raises an exception, the original search for a handler is ' 'canceled and\n' 'a search starts for the new exception in the surrounding code ' 'and on\n' 'the call stack (it is treated as if the entire "try" statement ' 'raised\n' 'the exception).\n' '\n' 'When a matching except clause is found, the exception is ' 'assigned to\n' 'the target specified after the "as" keyword in that except ' 'clause, if\n' 'present, and the except clause’s suite is executed. All except\n' 'clauses must have an executable block. When the end of this ' 'block is\n' 'reached, execution continues normally after the entire try ' 'statement.\n' '(This means that if two nested handlers exist for the same ' 'exception,\n' 'and the exception occurs in the try clause of the inner handler, ' 'the\n' 'outer handler will not handle the exception.)\n' '\n' 'When an exception has been assigned using "as target", it is ' 'cleared\n' 'at the end of the except clause. This is as if\n' '\n' ' except E as N:\n' ' foo\n' '\n' 'was translated to\n' '\n' ' except E as N:\n' ' try:\n' ' foo\n' ' finally:\n' ' del N\n' '\n' 'This means the exception must be assigned to a different name to ' 'be\n' 'able to refer to it after the except clause. Exceptions are ' 'cleared\n' 'because with the traceback attached to them, they form a ' 'reference\n' 'cycle with the stack frame, keeping all locals in that frame ' 'alive\n' 'until the next garbage collection occurs.\n' '\n' 'Before an except clause’s suite is executed, details about the\n' 'exception are stored in the "sys" module and can be accessed ' 'via\n' '"sys.exc_info()". "sys.exc_info()" returns a 3-tuple consisting ' 'of the\n' 'exception class, the exception instance and a traceback object ' '(see\n' 'section The standard type hierarchy) identifying the point in ' 'the\n' 'program where the exception occurred. The details about the ' 'exception\n' 'accessed via "sys.exc_info()" are restored to their previous ' 'values\n' 'when leaving an exception handler:\n' '\n' ' >>> print(sys.exc_info())\n' ' (None, None, None)\n' ' >>> try:\n' ' ... raise TypeError\n' ' ... except:\n' ' ... print(sys.exc_info())\n' ' ... try:\n' ' ... raise ValueError\n' ' ... except:\n' ' ... print(sys.exc_info())\n' ' ... print(sys.exc_info())\n' ' ...\n' " (<class 'TypeError'>, TypeError(), <traceback object at " '0x10efad080>)\n' " (<class 'ValueError'>, ValueError(), <traceback object at " '0x10efad040>)\n' " (<class 'TypeError'>, TypeError(), <traceback object at " '0x10efad080>)\n' ' >>> print(sys.exc_info())\n' ' (None, None, None)\n' '\n' 'The optional "else" clause is executed if the control flow ' 'leaves the\n' '"try" suite, no exception was raised, and no "return", ' '"continue", or\n' '"break" statement was executed. Exceptions in the "else" clause ' 'are\n' 'not handled by the preceding "except" clauses.\n' '\n' 'If "finally" is present, it specifies a ‘cleanup’ handler. The ' '"try"\n' 'clause is executed, including any "except" and "else" clauses. ' 'If an\n' 'exception occurs in any of the clauses and is not handled, the\n' 'exception is temporarily saved. The "finally" clause is ' 'executed. If\n' 'there is a saved exception it is re-raised at the end of the ' '"finally"\n' 'clause. If the "finally" clause raises another exception, the ' 'saved\n' 'exception is set as the context of the new exception. If the ' '"finally"\n' 'clause executes a "return", "break" or "continue" statement, the ' 'saved\n' 'exception is discarded:\n' '\n' ' >>> def f():\n' ' ... try:\n' ' ... 1/0\n' ' ... finally:\n' ' ... return 42\n' ' ...\n' ' >>> f()\n' ' 42\n' '\n' 'The exception information is not available to the program ' 'during\n' 'execution of the "finally" clause.\n' '\n' 'When a "return", "break" or "continue" statement is executed in ' 'the\n' '"try" suite of a "try"…"finally" statement, the "finally" clause ' 'is\n' 'also executed ‘on the way out.’\n' '\n' 'The return value of a function is determined by the last ' '"return"\n' 'statement executed. Since the "finally" clause always executes, ' 'a\n' '"return" statement executed in the "finally" clause will always ' 'be the\n' 'last one executed:\n' '\n' ' >>> def foo():\n' ' ... try:\n' " ... return 'try'\n" ' ... finally:\n' " ... return 'finally'\n" ' ...\n' ' >>> foo()\n' " 'finally'\n" '\n' 'Additional information on exceptions can be found in section\n' 'Exceptions, and information on using the "raise" statement to ' 'generate\n' 'exceptions may be found in section The raise statement.\n' '\n' 'Changed in version 3.8: Prior to Python 3.8, a "continue" ' 'statement\n' 'was illegal in the "finally" clause due to a problem with the\n' 'implementation.\n' '\n' '\n' 'The "with" statement\n' '====================\n' '\n' 'The "with" statement is used to wrap the execution of a block ' 'with\n' 'methods defined by a context manager (see section With ' 'Statement\n' 'Context Managers). This allows common "try"…"except"…"finally" ' 'usage\n' 'patterns to be encapsulated for convenient reuse.\n' '\n' ' with_stmt ::= "with" with_item ("," with_item)* ":" suite\n' ' with_item ::= expression ["as" target]\n' '\n' 'The execution of the "with" statement with one “item” proceeds ' 'as\n' 'follows:\n' '\n' '1. The context expression (the expression given in the ' '"with_item") is\n' ' evaluated to obtain a context manager.\n' '\n' '2. The context manager’s "__enter__()" is loaded for later use.\n' '\n' '3. The context manager’s "__exit__()" is loaded for later use.\n' '\n' '4. The context manager’s "__enter__()" method is invoked.\n' '\n' '5. If a target was included in the "with" statement, the return ' 'value\n' ' from "__enter__()" is assigned to it.\n' '\n' ' Note:\n' '\n' ' The "with" statement guarantees that if the "__enter__()" ' 'method\n' ' returns without an error, then "__exit__()" will always be\n' ' called. Thus, if an error occurs during the assignment to ' 'the\n' ' target list, it will be treated the same as an error ' 'occurring\n' ' within the suite would be. See step 6 below.\n' '\n' '6. The suite is executed.\n' '\n' '7. The context manager’s "__exit__()" method is invoked. If an\n' ' exception caused the suite to be exited, its type, value, ' 'and\n' ' traceback are passed as arguments to "__exit__()". Otherwise, ' 'three\n' ' "None" arguments are supplied.\n' '\n' ' If the suite was exited due to an exception, and the return ' 'value\n' ' from the "__exit__()" method was false, the exception is ' 'reraised.\n' ' If the return value was true, the exception is suppressed, ' 'and\n' ' execution continues with the statement following the "with"\n' ' statement.\n' '\n' ' If the suite was exited for any reason other than an ' 'exception, the\n' ' return value from "__exit__()" is ignored, and execution ' 'proceeds\n' ' at the normal location for the kind of exit that was taken.\n' '\n' 'The following code:\n' '\n' ' with EXPRESSION as TARGET:\n' ' SUITE\n' '\n' 'is semantically equivalent to:\n' '\n' ' manager = (EXPRESSION)\n' ' enter = type(manager).__enter__\n' ' exit = type(manager).__exit__\n' ' value = enter(manager)\n' ' hit_except = False\n' '\n' ' try:\n' ' TARGET = value\n' ' SUITE\n' ' except:\n' ' hit_except = True\n' ' if not exit(manager, *sys.exc_info()):\n' ' raise\n' ' finally:\n' ' if not hit_except:\n' ' exit(manager, None, None, None)\n' '\n' 'With more than one item, the context managers are processed as ' 'if\n' 'multiple "with" statements were nested:\n' '\n' ' with A() as a, B() as b:\n' ' SUITE\n' '\n' 'is semantically equivalent to:\n' '\n' ' with A() as a:\n' ' with B() as b:\n' ' SUITE\n' '\n' 'Changed in version 3.1: Support for multiple context ' 'expressions.\n' '\n' 'See also:\n' '\n' ' **PEP 343** - The “with” statement\n' ' The specification, background, and examples for the Python ' '"with"\n' ' statement.\n' '\n' '\n' 'Function definitions\n' '====================\n' '\n' 'A function definition defines a user-defined function object ' '(see\n' 'section The standard type hierarchy):\n' '\n' ' funcdef ::= [decorators] "def" funcname "(" ' '[parameter_list] ")"\n' ' ["->" expression] ":" suite\n' ' decorators ::= decorator+\n' ' decorator ::= "@" assignment_expression ' 'NEWLINE\n' ' dotted_name ::= identifier ("." identifier)*\n' ' parameter_list ::= defparameter ("," ' 'defparameter)* "," "/" ["," [parameter_list_no_posonly]]\n' ' | parameter_list_no_posonly\n' ' parameter_list_no_posonly ::= defparameter ("," ' 'defparameter)* ["," [parameter_list_starargs]]\n' ' | parameter_list_starargs\n' ' parameter_list_starargs ::= "*" [parameter] ("," ' 'defparameter)* ["," ["**" parameter [","]]]\n' ' | "**" parameter [","]\n' ' parameter ::= identifier [":" expression]\n' ' defparameter ::= parameter ["=" expression]\n' ' funcname ::= identifier\n' '\n' 'A function definition is an executable statement. Its execution ' 'binds\n' 'the function name in the current local namespace to a function ' 'object\n' '(a wrapper around the executable code for the function). This\n' 'function object contains a reference to the current global ' 'namespace\n' 'as the global namespace to be used when the function is called.\n' '\n' 'The function definition does not execute the function body; this ' 'gets\n' 'executed only when the function is called. [2]\n' '\n' 'A function definition may be wrapped by one or more *decorator*\n' 'expressions. Decorator expressions are evaluated when the ' 'function is\n' 'defined, in the scope that contains the function definition. ' 'The\n' 'result must be a callable, which is invoked with the function ' 'object\n' 'as the only argument. The returned value is bound to the ' 'function name\n' 'instead of the function object. Multiple decorators are applied ' 'in\n' 'nested fashion. For example, the following code\n' '\n' ' @f1(arg)\n' ' @f2\n' ' def func(): pass\n' '\n' 'is roughly equivalent to\n' '\n' ' def func(): pass\n' ' func = f1(arg)(f2(func))\n' '\n' 'except that the original function is not temporarily bound to ' 'the name\n' '"func".\n' '\n' 'Changed in version 3.9: Functions may be decorated with any ' 'valid\n' '"assignment_expression". Previously, the grammar was much more\n' 'restrictive; see **PEP 614** for details.\n' '\n' 'When one or more *parameters* have the form *parameter* "="\n' '*expression*, the function is said to have “default parameter ' 'values.”\n' 'For a parameter with a default value, the corresponding ' '*argument* may\n' 'be omitted from a call, in which case the parameter’s default ' 'value is\n' 'substituted. If a parameter has a default value, all following\n' 'parameters up until the “"*"” must also have a default value — ' 'this is\n' 'a syntactic restriction that is not expressed by the grammar.\n' '\n' '**Default parameter values are evaluated from left to right when ' 'the\n' 'function definition is executed.** This means that the ' 'expression is\n' 'evaluated once, when the function is defined, and that the same ' '“pre-\n' 'computed” value is used for each call. This is especially ' 'important\n' 'to understand when a default parameter value is a mutable ' 'object, such\n' 'as a list or a dictionary: if the function modifies the object ' '(e.g.\n' 'by appending an item to a list), the default parameter value is ' 'in\n' 'effect modified. This is generally not what was intended. A ' 'way\n' 'around this is to use "None" as the default, and explicitly test ' 'for\n' 'it in the body of the function, e.g.:\n' '\n' ' def whats_on_the_telly(penguin=None):\n' ' if penguin is None:\n' ' penguin = []\n' ' penguin.append("property of the zoo")\n' ' return penguin\n' '\n' 'Function call semantics are described in more detail in section ' 'Calls.\n' 'A function call always assigns values to all parameters ' 'mentioned in\n' 'the parameter list, either from position arguments, from ' 'keyword\n' 'arguments, or from default values. If the form “"*identifier"” ' 'is\n' 'present, it is initialized to a tuple receiving any excess ' 'positional\n' 'parameters, defaulting to the empty tuple. If the form\n' '“"**identifier"” is present, it is initialized to a new ordered\n' 'mapping receiving any excess keyword arguments, defaulting to a ' 'new\n' 'empty mapping of the same type. Parameters after “"*"” or\n' '“"*identifier"” are keyword-only parameters and may only be ' 'passed\n' 'used keyword arguments.\n' '\n' 'Parameters may have an *annotation* of the form “": ' 'expression"”\n' 'following the parameter name. Any parameter may have an ' 'annotation,\n' 'even those of the form "*identifier" or "**identifier". ' 'Functions may\n' 'have “return” annotation of the form “"-> expression"” after ' 'the\n' 'parameter list. These annotations can be any valid Python ' 'expression.\n' 'The presence of annotations does not change the semantics of a\n' 'function. The annotation values are available as string values ' 'in a\n' 'dictionary keyed by the parameters’ names in the ' '"__annotations__"\n' 'attribute of the function object.\n' '\n' 'It is also possible to create anonymous functions (functions not ' 'bound\n' 'to a name), for immediate use in expressions. This uses lambda\n' 'expressions, described in section Lambdas. Note that the ' 'lambda\n' 'expression is merely a shorthand for a simplified function ' 'definition;\n' 'a function defined in a “"def"” statement can be passed around ' 'or\n' 'assigned to another name just like a function defined by a ' 'lambda\n' 'expression. The “"def"” form is actually more powerful since ' 'it\n' 'allows the execution of multiple statements and annotations.\n' '\n' '**Programmer’s note:** Functions are first-class objects. A ' '“"def"”\n' 'statement executed inside a function definition defines a local\n' 'function that can be returned or passed around. Free variables ' 'used\n' 'in the nested function can access the local variables of the ' 'function\n' 'containing the def. See section Naming and binding for ' 'details.\n' '\n' 'See also:\n' '\n' ' **PEP 3107** - Function Annotations\n' ' The original specification for function annotations.\n' '\n' ' **PEP 484** - Type Hints\n' ' Definition of a standard meaning for annotations: type ' 'hints.\n' '\n' ' **PEP 526** - Syntax for Variable Annotations\n' ' Ability to type hint variable declarations, including ' 'class\n' ' variables and instance variables\n' '\n' ' **PEP 563** - Postponed Evaluation of Annotations\n' ' Support for forward references within annotations by ' 'preserving\n' ' annotations in a string form at runtime instead of eager\n' ' evaluation.\n' '\n' '\n' 'Class definitions\n' '=================\n' '\n' 'A class definition defines a class object (see section The ' 'standard\n' 'type hierarchy):\n' '\n' ' classdef ::= [decorators] "class" classname [inheritance] ' '":" suite\n' ' inheritance ::= "(" [argument_list] ")"\n' ' classname ::= identifier\n' '\n' 'A class definition is an executable statement. The inheritance ' 'list\n' 'usually gives a list of base classes (see Metaclasses for more\n' 'advanced uses), so each item in the list should evaluate to a ' 'class\n' 'object which allows subclassing. Classes without an inheritance ' 'list\n' 'inherit, by default, from the base class "object"; hence,\n' '\n' ' class Foo:\n' ' pass\n' '\n' 'is equivalent to\n' '\n' ' class Foo(object):\n' ' pass\n' '\n' 'The class’s suite is then executed in a new execution frame ' '(see\n' 'Naming and binding), using a newly created local namespace and ' 'the\n' 'original global namespace. (Usually, the suite contains mostly\n' 'function definitions.) When the class’s suite finishes ' 'execution, its\n' 'execution frame is discarded but its local namespace is saved. ' '[3] A\n' 'class object is then created using the inheritance list for the ' 'base\n' 'classes and the saved local namespace for the attribute ' 'dictionary.\n' 'The class name is bound to this class object in the original ' 'local\n' 'namespace.\n' '\n' 'The order in which attributes are defined in the class body is\n' 'preserved in the new class’s "__dict__". Note that this is ' 'reliable\n' 'only right after the class is created and only for classes that ' 'were\n' 'defined using the definition syntax.\n' '\n' 'Class creation can be customized heavily using metaclasses.\n' '\n' 'Classes can also be decorated: just like when decorating ' 'functions,\n' '\n' ' @f1(arg)\n' ' @f2\n' ' class Foo: pass\n' '\n' 'is roughly equivalent to\n' '\n' ' class Foo: pass\n' ' Foo = f1(arg)(f2(Foo))\n' '\n' 'The evaluation rules for the decorator expressions are the same ' 'as for\n' 'function decorators. The result is then bound to the class ' 'name.\n' '\n' 'Changed in version 3.9: Classes may be decorated with any valid\n' '"assignment_expression". Previously, the grammar was much more\n' 'restrictive; see **PEP 614** for details.\n' '\n' '**Programmer’s note:** Variables defined in the class definition ' 'are\n' 'class attributes; they are shared by instances. Instance ' 'attributes\n' 'can be set in a method with "self.name = value". Both class ' 'and\n' 'instance attributes are accessible through the notation ' '“"self.name"”,\n' 'and an instance attribute hides a class attribute with the same ' 'name\n' 'when accessed in this way. Class attributes can be used as ' 'defaults\n' 'for instance attributes, but using mutable values there can lead ' 'to\n' 'unexpected results. Descriptors can be used to create instance\n' 'variables with different implementation details.\n' '\n' 'See also:\n' '\n' ' **PEP 3115** - Metaclasses in Python 3000\n' ' The proposal that changed the declaration of metaclasses to ' 'the\n' ' current syntax, and the semantics for how classes with\n' ' metaclasses are constructed.\n' '\n' ' **PEP 3129** - Class Decorators\n' ' The proposal that added class decorators. Function and ' 'method\n' ' decorators were introduced in **PEP 318**.\n' '\n' '\n' 'Coroutines\n' '==========\n' '\n' 'New in version 3.5.\n' '\n' '\n' 'Coroutine function definition\n' '-----------------------------\n' '\n' ' async_funcdef ::= [decorators] "async" "def" funcname "(" ' '[parameter_list] ")"\n' ' ["->" expression] ":" suite\n' '\n' 'Execution of Python coroutines can be suspended and resumed at ' 'many\n' 'points (see *coroutine*). "await" expressions, "async for" and ' '"async\n' 'with" can only be used in the body of a coroutine function.\n' '\n' 'Functions defined with "async def" syntax are always coroutine\n' 'functions, even if they do not contain "await" or "async" ' 'keywords.\n' '\n' 'It is a "SyntaxError" to use a "yield from" expression inside ' 'the body\n' 'of a coroutine function.\n' '\n' 'An example of a coroutine function:\n' '\n' ' async def func(param1, param2):\n' ' do_stuff()\n' ' await some_coroutine()\n' '\n' 'Changed in version 3.7: "await" and "async" are now keywords;\n' 'previously they were only treated as such inside the body of a\n' 'coroutine function.\n' '\n' '\n' 'The "async for" statement\n' '-------------------------\n' '\n' ' async_for_stmt ::= "async" for_stmt\n' '\n' 'An *asynchronous iterable* provides an "__aiter__" method that\n' 'directly returns an *asynchronous iterator*, which can call\n' 'asynchronous code in its "__anext__" method.\n' '\n' 'The "async for" statement allows convenient iteration over\n' 'asynchronous iterables.\n' '\n' 'The following code:\n' '\n' ' async for TARGET in ITER:\n' ' SUITE\n' ' else:\n' ' SUITE2\n' '\n' 'Is semantically equivalent to:\n' '\n' ' iter = (ITER)\n' ' iter = type(iter).__aiter__(iter)\n' ' running = True\n' '\n' ' while running:\n' ' try:\n' ' TARGET = await type(iter).__anext__(iter)\n' ' except StopAsyncIteration:\n' ' running = False\n' ' else:\n' ' SUITE\n' ' else:\n' ' SUITE2\n' '\n' 'See also "__aiter__()" and "__anext__()" for details.\n' '\n' 'It is a "SyntaxError" to use an "async for" statement outside ' 'the body\n' 'of a coroutine function.\n' '\n' '\n' 'The "async with" statement\n' '--------------------------\n' '\n' ' async_with_stmt ::= "async" with_stmt\n' '\n' 'An *asynchronous context manager* is a *context manager* that is ' 'able\n' 'to suspend execution in its *enter* and *exit* methods.\n' '\n' 'The following code:\n' '\n' ' async with EXPRESSION as TARGET:\n' ' SUITE\n' '\n' 'is semantically equivalent to:\n' '\n' ' manager = (EXPRESSION)\n' ' aenter = type(manager).__aenter__\n' ' aexit = type(manager).__aexit__\n' ' value = await aenter(manager)\n' ' hit_except = False\n' '\n' ' try:\n' ' TARGET = value\n' ' SUITE\n' ' except:\n' ' hit_except = True\n' ' if not await aexit(manager, *sys.exc_info()):\n' ' raise\n' ' finally:\n' ' if not hit_except:\n' ' await aexit(manager, None, None, None)\n' '\n' 'See also "__aenter__()" and "__aexit__()" for details.\n' '\n' 'It is a "SyntaxError" to use an "async with" statement outside ' 'the\n' 'body of a coroutine function.\n' '\n' 'See also:\n' '\n' ' **PEP 492** - Coroutines with async and await syntax\n' ' The proposal that made coroutines a proper standalone ' 'concept in\n' ' Python, and added supporting syntax.\n' '\n' '-[ Footnotes ]-\n' '\n' '[1] The exception is propagated to the invocation stack unless ' 'there\n' ' is a "finally" clause which happens to raise another ' 'exception.\n' ' That new exception causes the old one to be lost.\n' '\n' '[2] A string literal appearing as the first statement in the ' 'function\n' ' body is transformed into the function’s "__doc__" attribute ' 'and\n' ' therefore the function’s *docstring*.\n' '\n' '[3] A string literal appearing as the first statement in the ' 'class\n' ' body is transformed into the namespace’s "__doc__" item and\n' ' therefore the class’s *docstring*.\n', 'context-managers': 'With Statement Context Managers\n' '*******************************\n' '\n' 'A *context manager* is an object that defines the ' 'runtime context to\n' 'be established when executing a "with" statement. The ' 'context manager\n' 'handles the entry into, and the exit from, the desired ' 'runtime context\n' 'for the execution of the block of code. Context ' 'managers are normally\n' 'invoked using the "with" statement (described in section ' 'The with\n' 'statement), but can also be used by directly invoking ' 'their methods.\n' '\n' 'Typical uses of context managers include saving and ' 'restoring various\n' 'kinds of global state, locking and unlocking resources, ' 'closing opened\n' 'files, etc.\n' '\n' 'For more information on context managers, see Context ' 'Manager Types.\n' '\n' 'object.__enter__(self)\n' '\n' ' Enter the runtime context related to this object. The ' '"with"\n' ' statement will bind this method’s return value to the ' 'target(s)\n' ' specified in the "as" clause of the statement, if ' 'any.\n' '\n' 'object.__exit__(self, exc_type, exc_value, traceback)\n' '\n' ' Exit the runtime context related to this object. The ' 'parameters\n' ' describe the exception that caused the context to be ' 'exited. If the\n' ' context was exited without an exception, all three ' 'arguments will\n' ' be "None".\n' '\n' ' If an exception is supplied, and the method wishes to ' 'suppress the\n' ' exception (i.e., prevent it from being propagated), ' 'it should\n' ' return a true value. Otherwise, the exception will be ' 'processed\n' ' normally upon exit from this method.\n' '\n' ' Note that "__exit__()" methods should not reraise the ' 'passed-in\n' ' exception; this is the caller’s responsibility.\n' '\n' 'See also:\n' '\n' ' **PEP 343** - The “with” statement\n' ' The specification, background, and examples for the ' 'Python "with"\n' ' statement.\n', 'continue': 'The "continue" statement\n' '************************\n' '\n' ' continue_stmt ::= "continue"\n' '\n' '"continue" may only occur syntactically nested in a "for" or ' '"while"\n' 'loop, but not nested in a function or class definition within ' 'that\n' 'loop. It continues with the next cycle of the nearest enclosing ' 'loop.\n' '\n' 'When "continue" passes control out of a "try" statement with a\n' '"finally" clause, that "finally" clause is executed before ' 'really\n' 'starting the next loop cycle.\n', 'conversions': 'Arithmetic conversions\n' '**********************\n' '\n' 'When a description of an arithmetic operator below uses the ' 'phrase\n' '“the numeric arguments are converted to a common type”, this ' 'means\n' 'that the operator implementation for built-in types works as ' 'follows:\n' '\n' '* If either argument is a complex number, the other is ' 'converted to\n' ' complex;\n' '\n' '* otherwise, if either argument is a floating point number, ' 'the other\n' ' is converted to floating point;\n' '\n' '* otherwise, both must be integers and no conversion is ' 'necessary.\n' '\n' 'Some additional rules apply for certain operators (e.g., a ' 'string as a\n' 'left argument to the ‘%’ operator). Extensions must define ' 'their own\n' 'conversion behavior.\n', 'customization': 'Basic customization\n' '*******************\n' '\n' 'object.__new__(cls[, ...])\n' '\n' ' Called to create a new instance of class *cls*. ' '"__new__()" is a\n' ' static method (special-cased so you need not declare it ' 'as such)\n' ' that takes the class of which an instance was requested ' 'as its\n' ' first argument. The remaining arguments are those ' 'passed to the\n' ' object constructor expression (the call to the class). ' 'The return\n' ' value of "__new__()" should be the new object instance ' '(usually an\n' ' instance of *cls*).\n' '\n' ' Typical implementations create a new instance of the ' 'class by\n' ' invoking the superclass’s "__new__()" method using\n' ' "super().__new__(cls[, ...])" with appropriate arguments ' 'and then\n' ' modifying the newly-created instance as necessary before ' 'returning\n' ' it.\n' '\n' ' If "__new__()" is invoked during object construction and ' 'it returns\n' ' an instance or subclass of *cls*, then the new ' 'instance’s\n' ' "__init__()" method will be invoked like ' '"__init__(self[, ...])",\n' ' where *self* is the new instance and the remaining ' 'arguments are\n' ' the same as were passed to the object constructor.\n' '\n' ' If "__new__()" does not return an instance of *cls*, ' 'then the new\n' ' instance’s "__init__()" method will not be invoked.\n' '\n' ' "__new__()" is intended mainly to allow subclasses of ' 'immutable\n' ' types (like int, str, or tuple) to customize instance ' 'creation. It\n' ' is also commonly overridden in custom metaclasses in ' 'order to\n' ' customize class creation.\n' '\n' 'object.__init__(self[, ...])\n' '\n' ' Called after the instance has been created (by ' '"__new__()"), but\n' ' before it is returned to the caller. The arguments are ' 'those\n' ' passed to the class constructor expression. If a base ' 'class has an\n' ' "__init__()" method, the derived class’s "__init__()" ' 'method, if\n' ' any, must explicitly call it to ensure proper ' 'initialization of the\n' ' base class part of the instance; for example:\n' ' "super().__init__([args...])".\n' '\n' ' Because "__new__()" and "__init__()" work together in ' 'constructing\n' ' objects ("__new__()" to create it, and "__init__()" to ' 'customize\n' ' it), no non-"None" value may be returned by ' '"__init__()"; doing so\n' ' will cause a "TypeError" to be raised at runtime.\n' '\n' 'object.__del__(self)\n' '\n' ' Called when the instance is about to be destroyed. This ' 'is also\n' ' called a finalizer or (improperly) a destructor. If a ' 'base class\n' ' has a "__del__()" method, the derived class’s ' '"__del__()" method,\n' ' if any, must explicitly call it to ensure proper ' 'deletion of the\n' ' base class part of the instance.\n' '\n' ' It is possible (though not recommended!) for the ' '"__del__()" method\n' ' to postpone destruction of the instance by creating a ' 'new reference\n' ' to it. This is called object *resurrection*. It is\n' ' implementation-dependent whether "__del__()" is called a ' 'second\n' ' time when a resurrected object is about to be destroyed; ' 'the\n' ' current *CPython* implementation only calls it once.\n' '\n' ' It is not guaranteed that "__del__()" methods are called ' 'for\n' ' objects that still exist when the interpreter exits.\n' '\n' ' Note:\n' '\n' ' "del x" doesn’t directly call "x.__del__()" — the ' 'former\n' ' decrements the reference count for "x" by one, and the ' 'latter is\n' ' only called when "x"’s reference count reaches zero.\n' '\n' ' **CPython implementation detail:** It is possible for a ' 'reference\n' ' cycle to prevent the reference count of an object from ' 'going to\n' ' zero. In this case, the cycle will be later detected ' 'and deleted\n' ' by the *cyclic garbage collector*. A common cause of ' 'reference\n' ' cycles is when an exception has been caught in a local ' 'variable.\n' ' The frame’s locals then reference the exception, which ' 'references\n' ' its own traceback, which references the locals of all ' 'frames caught\n' ' in the traceback.\n' '\n' ' See also: Documentation for the "gc" module.\n' '\n' ' Warning:\n' '\n' ' Due to the precarious circumstances under which ' '"__del__()"\n' ' methods are invoked, exceptions that occur during ' 'their execution\n' ' are ignored, and a warning is printed to "sys.stderr" ' 'instead.\n' ' In particular:\n' '\n' ' * "__del__()" can be invoked when arbitrary code is ' 'being\n' ' executed, including from any arbitrary thread. If ' '"__del__()"\n' ' needs to take a lock or invoke any other blocking ' 'resource, it\n' ' may deadlock as the resource may already be taken by ' 'the code\n' ' that gets interrupted to execute "__del__()".\n' '\n' ' * "__del__()" can be executed during interpreter ' 'shutdown. As a\n' ' consequence, the global variables it needs to access ' '(including\n' ' other modules) may already have been deleted or set ' 'to "None".\n' ' Python guarantees that globals whose name begins ' 'with a single\n' ' underscore are deleted from their module before ' 'other globals\n' ' are deleted; if no other references to such globals ' 'exist, this\n' ' may help in assuring that imported modules are still ' 'available\n' ' at the time when the "__del__()" method is called.\n' '\n' 'object.__repr__(self)\n' '\n' ' Called by the "repr()" built-in function to compute the ' '“official”\n' ' string representation of an object. If at all possible, ' 'this\n' ' should look like a valid Python expression that could be ' 'used to\n' ' recreate an object with the same value (given an ' 'appropriate\n' ' environment). If this is not possible, a string of the ' 'form\n' ' "<...some useful description...>" should be returned. ' 'The return\n' ' value must be a string object. If a class defines ' '"__repr__()" but\n' ' not "__str__()", then "__repr__()" is also used when an ' '“informal”\n' ' string representation of instances of that class is ' 'required.\n' '\n' ' This is typically used for debugging, so it is important ' 'that the\n' ' representation is information-rich and unambiguous.\n' '\n' 'object.__str__(self)\n' '\n' ' Called by "str(object)" and the built-in functions ' '"format()" and\n' ' "print()" to compute the “informal” or nicely printable ' 'string\n' ' representation of an object. The return value must be a ' 'string\n' ' object.\n' '\n' ' This method differs from "object.__repr__()" in that ' 'there is no\n' ' expectation that "__str__()" return a valid Python ' 'expression: a\n' ' more convenient or concise representation can be used.\n' '\n' ' The default implementation defined by the built-in type ' '"object"\n' ' calls "object.__repr__()".\n' '\n' 'object.__bytes__(self)\n' '\n' ' Called by bytes to compute a byte-string representation ' 'of an\n' ' object. This should return a "bytes" object.\n' '\n' 'object.__format__(self, format_spec)\n' '\n' ' Called by the "format()" built-in function, and by ' 'extension,\n' ' evaluation of formatted string literals and the ' '"str.format()"\n' ' method, to produce a “formatted” string representation ' 'of an\n' ' object. The *format_spec* argument is a string that ' 'contains a\n' ' description of the formatting options desired. The ' 'interpretation\n' ' of the *format_spec* argument is up to the type ' 'implementing\n' ' "__format__()", however most classes will either ' 'delegate\n' ' formatting to one of the built-in types, or use a ' 'similar\n' ' formatting option syntax.\n' '\n' ' See Format Specification Mini-Language for a description ' 'of the\n' ' standard formatting syntax.\n' '\n' ' The return value must be a string object.\n' '\n' ' Changed in version 3.4: The __format__ method of ' '"object" itself\n' ' raises a "TypeError" if passed any non-empty string.\n' '\n' ' Changed in version 3.7: "object.__format__(x, \'\')" is ' 'now\n' ' equivalent to "str(x)" rather than "format(str(x), ' '\'\')".\n' '\n' 'object.__lt__(self, other)\n' 'object.__le__(self, other)\n' 'object.__eq__(self, other)\n' 'object.__ne__(self, other)\n' 'object.__gt__(self, other)\n' 'object.__ge__(self, other)\n' '\n' ' These are the so-called “rich comparison” methods. The\n' ' correspondence between operator symbols and method names ' 'is as\n' ' follows: "x<y" calls "x.__lt__(y)", "x<=y" calls ' '"x.__le__(y)",\n' ' "x==y" calls "x.__eq__(y)", "x!=y" calls "x.__ne__(y)", ' '"x>y" calls\n' ' "x.__gt__(y)", and "x>=y" calls "x.__ge__(y)".\n' '\n' ' A rich comparison method may return the singleton ' '"NotImplemented"\n' ' if it does not implement the operation for a given pair ' 'of\n' ' arguments. By convention, "False" and "True" are ' 'returned for a\n' ' successful comparison. However, these methods can return ' 'any value,\n' ' so if the comparison operator is used in a Boolean ' 'context (e.g.,\n' ' in the condition of an "if" statement), Python will call ' '"bool()"\n' ' on the value to determine if the result is true or ' 'false.\n' '\n' ' By default, "object" implements "__eq__()" by using ' '"is", returning\n' ' "NotImplemented" in the case of a false comparison: ' '"True if x is y\n' ' else NotImplemented". For "__ne__()", by default it ' 'delegates to\n' ' "__eq__()" and inverts the result unless it is ' '"NotImplemented".\n' ' There are no other implied relationships among the ' 'comparison\n' ' operators or default implementations; for example, the ' 'truth of\n' ' "(x<y or x==y)" does not imply "x<=y". To automatically ' 'generate\n' ' ordering operations from a single root operation, see\n' ' "functools.total_ordering()".\n' '\n' ' See the paragraph on "__hash__()" for some important ' 'notes on\n' ' creating *hashable* objects which support custom ' 'comparison\n' ' operations and are usable as dictionary keys.\n' '\n' ' There are no swapped-argument versions of these methods ' '(to be used\n' ' when the left argument does not support the operation ' 'but the right\n' ' argument does); rather, "__lt__()" and "__gt__()" are ' 'each other’s\n' ' reflection, "__le__()" and "__ge__()" are each other’s ' 'reflection,\n' ' and "__eq__()" and "__ne__()" are their own reflection. ' 'If the\n' ' operands are of different types, and right operand’s ' 'type is a\n' ' direct or indirect subclass of the left operand’s type, ' 'the\n' ' reflected method of the right operand has priority, ' 'otherwise the\n' ' left operand’s method has priority. Virtual subclassing ' 'is not\n' ' considered.\n' '\n' 'object.__hash__(self)\n' '\n' ' Called by built-in function "hash()" and for operations ' 'on members\n' ' of hashed collections including "set", "frozenset", and ' '"dict".\n' ' "__hash__()" should return an integer. The only required ' 'property\n' ' is that objects which compare equal have the same hash ' 'value; it is\n' ' advised to mix together the hash values of the ' 'components of the\n' ' object that also play a part in comparison of objects by ' 'packing\n' ' them into a tuple and hashing the tuple. Example:\n' '\n' ' def __hash__(self):\n' ' return hash((self.name, self.nick, self.color))\n' '\n' ' Note:\n' '\n' ' "hash()" truncates the value returned from an object’s ' 'custom\n' ' "__hash__()" method to the size of a "Py_ssize_t". ' 'This is\n' ' typically 8 bytes on 64-bit builds and 4 bytes on ' '32-bit builds.\n' ' If an object’s "__hash__()" must interoperate on ' 'builds of\n' ' different bit sizes, be sure to check the width on all ' 'supported\n' ' builds. An easy way to do this is with "python -c ' '"import sys;\n' ' print(sys.hash_info.width)"".\n' '\n' ' If a class does not define an "__eq__()" method it ' 'should not\n' ' define a "__hash__()" operation either; if it defines ' '"__eq__()"\n' ' but not "__hash__()", its instances will not be usable ' 'as items in\n' ' hashable collections. If a class defines mutable ' 'objects and\n' ' implements an "__eq__()" method, it should not ' 'implement\n' ' "__hash__()", since the implementation of hashable ' 'collections\n' ' requires that a key’s hash value is immutable (if the ' 'object’s hash\n' ' value changes, it will be in the wrong hash bucket).\n' '\n' ' User-defined classes have "__eq__()" and "__hash__()" ' 'methods by\n' ' default; with them, all objects compare unequal (except ' 'with\n' ' themselves) and "x.__hash__()" returns an appropriate ' 'value such\n' ' that "x == y" implies both that "x is y" and "hash(x) == ' 'hash(y)".\n' '\n' ' A class that overrides "__eq__()" and does not define ' '"__hash__()"\n' ' will have its "__hash__()" implicitly set to "None". ' 'When the\n' ' "__hash__()" method of a class is "None", instances of ' 'the class\n' ' will raise an appropriate "TypeError" when a program ' 'attempts to\n' ' retrieve their hash value, and will also be correctly ' 'identified as\n' ' unhashable when checking "isinstance(obj,\n' ' collections.abc.Hashable)".\n' '\n' ' If a class that overrides "__eq__()" needs to retain ' 'the\n' ' implementation of "__hash__()" from a parent class, the ' 'interpreter\n' ' must be told this explicitly by setting "__hash__ =\n' ' <ParentClass>.__hash__".\n' '\n' ' If a class that does not override "__eq__()" wishes to ' 'suppress\n' ' hash support, it should include "__hash__ = None" in the ' 'class\n' ' definition. A class which defines its own "__hash__()" ' 'that\n' ' explicitly raises a "TypeError" would be incorrectly ' 'identified as\n' ' hashable by an "isinstance(obj, ' 'collections.abc.Hashable)" call.\n' '\n' ' Note:\n' '\n' ' By default, the "__hash__()" values of str and bytes ' 'objects are\n' ' “salted” with an unpredictable random value. Although ' 'they\n' ' remain constant within an individual Python process, ' 'they are not\n' ' predictable between repeated invocations of ' 'Python.This is\n' ' intended to provide protection against a ' 'denial-of-service caused\n' ' by carefully-chosen inputs that exploit the worst ' 'case\n' ' performance of a dict insertion, O(n^2) complexity. ' 'See\n' ' http://www.ocert.org/advisories/ocert-2011-003.html ' 'for\n' ' details.Changing hash values affects the iteration ' 'order of sets.\n' ' Python has never made guarantees about this ordering ' '(and it\n' ' typically varies between 32-bit and 64-bit builds).See ' 'also\n' ' "PYTHONHASHSEED".\n' '\n' ' Changed in version 3.3: Hash randomization is enabled by ' 'default.\n' '\n' 'object.__bool__(self)\n' '\n' ' Called to implement truth value testing and the built-in ' 'operation\n' ' "bool()"; should return "False" or "True". When this ' 'method is not\n' ' defined, "__len__()" is called, if it is defined, and ' 'the object is\n' ' considered true if its result is nonzero. If a class ' 'defines\n' ' neither "__len__()" nor "__bool__()", all its instances ' 'are\n' ' considered true.\n', 'debugger': '"pdb" — The Python Debugger\n' '***************************\n' '\n' '**Source code:** Lib/pdb.py\n' '\n' '======================================================================\n' '\n' 'The module "pdb" defines an interactive source code debugger ' 'for\n' 'Python programs. It supports setting (conditional) breakpoints ' 'and\n' 'single stepping at the source line level, inspection of stack ' 'frames,\n' 'source code listing, and evaluation of arbitrary Python code in ' 'the\n' 'context of any stack frame. It also supports post-mortem ' 'debugging\n' 'and can be called under program control.\n' '\n' 'The debugger is extensible – it is actually defined as the ' 'class\n' '"Pdb". This is currently undocumented but easily understood by ' 'reading\n' 'the source. The extension interface uses the modules "bdb" and ' '"cmd".\n' '\n' 'The debugger’s prompt is "(Pdb)". Typical usage to run a program ' 'under\n' 'control of the debugger is:\n' '\n' ' >>> import pdb\n' ' >>> import mymodule\n' " >>> pdb.run('mymodule.test()')\n" ' > <string>(0)?()\n' ' (Pdb) continue\n' ' > <string>(1)?()\n' ' (Pdb) continue\n' " NameError: 'spam'\n" ' > <string>(1)?()\n' ' (Pdb)\n' '\n' 'Changed in version 3.3: Tab-completion via the "readline" module ' 'is\n' 'available for commands and command arguments, e.g. the current ' 'global\n' 'and local names are offered as arguments of the "p" command.\n' '\n' '"pdb.py" can also be invoked as a script to debug other ' 'scripts. For\n' 'example:\n' '\n' ' python3 -m pdb myscript.py\n' '\n' 'When invoked as a script, pdb will automatically enter ' 'post-mortem\n' 'debugging if the program being debugged exits abnormally. After ' 'post-\n' 'mortem debugging (or after normal exit of the program), pdb ' 'will\n' 'restart the program. Automatic restarting preserves pdb’s state ' '(such\n' 'as breakpoints) and in most cases is more useful than quitting ' 'the\n' 'debugger upon program’s exit.\n' '\n' 'New in version 3.2: "pdb.py" now accepts a "-c" option that ' 'executes\n' 'commands as if given in a ".pdbrc" file, see Debugger Commands.\n' '\n' 'New in version 3.7: "pdb.py" now accepts a "-m" option that ' 'execute\n' 'modules similar to the way "python3 -m" does. As with a script, ' 'the\n' 'debugger will pause execution just before the first line of the\n' 'module.\n' '\n' 'The typical usage to break into the debugger from a running ' 'program is\n' 'to insert\n' '\n' ' import pdb; pdb.set_trace()\n' '\n' 'at the location you want to break into the debugger. You can ' 'then\n' 'step through the code following this statement, and continue ' 'running\n' 'without the debugger using the "continue" command.\n' '\n' 'New in version 3.7: The built-in "breakpoint()", when called ' 'with\n' 'defaults, can be used instead of "import pdb; pdb.set_trace()".\n' '\n' 'The typical usage to inspect a crashed program is:\n' '\n' ' >>> import pdb\n' ' >>> import mymodule\n' ' >>> mymodule.test()\n' ' Traceback (most recent call last):\n' ' File "<stdin>", line 1, in <module>\n' ' File "./mymodule.py", line 4, in test\n' ' test2()\n' ' File "./mymodule.py", line 3, in test2\n' ' print(spam)\n' ' NameError: spam\n' ' >>> pdb.pm()\n' ' > ./mymodule.py(3)test2()\n' ' -> print(spam)\n' ' (Pdb)\n' '\n' 'The module defines the following functions; each enters the ' 'debugger\n' 'in a slightly different way:\n' '\n' 'pdb.run(statement, globals=None, locals=None)\n' '\n' ' Execute the *statement* (given as a string or a code object) ' 'under\n' ' debugger control. The debugger prompt appears before any ' 'code is\n' ' executed; you can set breakpoints and type "continue", or you ' 'can\n' ' step through the statement using "step" or "next" (all these\n' ' commands are explained below). The optional *globals* and ' '*locals*\n' ' arguments specify the environment in which the code is ' 'executed; by\n' ' default the dictionary of the module "__main__" is used. ' '(See the\n' ' explanation of the built-in "exec()" or "eval()" functions.)\n' '\n' 'pdb.runeval(expression, globals=None, locals=None)\n' '\n' ' Evaluate the *expression* (given as a string or a code ' 'object)\n' ' under debugger control. When "runeval()" returns, it returns ' 'the\n' ' value of the expression. Otherwise this function is similar ' 'to\n' ' "run()".\n' '\n' 'pdb.runcall(function, *args, **kwds)\n' '\n' ' Call the *function* (a function or method object, not a ' 'string)\n' ' with the given arguments. When "runcall()" returns, it ' 'returns\n' ' whatever the function call returned. The debugger prompt ' 'appears\n' ' as soon as the function is entered.\n' '\n' 'pdb.set_trace(*, header=None)\n' '\n' ' Enter the debugger at the calling stack frame. This is ' 'useful to\n' ' hard-code a breakpoint at a given point in a program, even if ' 'the\n' ' code is not otherwise being debugged (e.g. when an assertion\n' ' fails). If given, *header* is printed to the console just ' 'before\n' ' debugging begins.\n' '\n' ' Changed in version 3.7: The keyword-only argument *header*.\n' '\n' 'pdb.post_mortem(traceback=None)\n' '\n' ' Enter post-mortem debugging of the given *traceback* object. ' 'If no\n' ' *traceback* is given, it uses the one of the exception that ' 'is\n' ' currently being handled (an exception must be being handled ' 'if the\n' ' default is to be used).\n' '\n' 'pdb.pm()\n' '\n' ' Enter post-mortem debugging of the traceback found in\n' ' "sys.last_traceback".\n' '\n' 'The "run*" functions and "set_trace()" are aliases for ' 'instantiating\n' 'the "Pdb" class and calling the method of the same name. If you ' 'want\n' 'to access further features, you have to do this yourself:\n' '\n' "class pdb.Pdb(completekey='tab', stdin=None, stdout=None, " 'skip=None, nosigint=False, readrc=True)\n' '\n' ' "Pdb" is the debugger class.\n' '\n' ' The *completekey*, *stdin* and *stdout* arguments are passed ' 'to the\n' ' underlying "cmd.Cmd" class; see the description there.\n' '\n' ' The *skip* argument, if given, must be an iterable of ' 'glob-style\n' ' module name patterns. The debugger will not step into frames ' 'that\n' ' originate in a module that matches one of these patterns. ' '[1]\n' '\n' ' By default, Pdb sets a handler for the SIGINT signal (which ' 'is sent\n' ' when the user presses "Ctrl-C" on the console) when you give ' 'a\n' ' "continue" command. This allows you to break into the ' 'debugger\n' ' again by pressing "Ctrl-C". If you want Pdb not to touch ' 'the\n' ' SIGINT handler, set *nosigint* to true.\n' '\n' ' The *readrc* argument defaults to true and controls whether ' 'Pdb\n' ' will load .pdbrc files from the filesystem.\n' '\n' ' Example call to enable tracing with *skip*:\n' '\n' " import pdb; pdb.Pdb(skip=['django.*']).set_trace()\n" '\n' ' Raises an auditing event "pdb.Pdb" with no arguments.\n' '\n' ' New in version 3.1: The *skip* argument.\n' '\n' ' New in version 3.2: The *nosigint* argument. Previously, a ' 'SIGINT\n' ' handler was never set by Pdb.\n' '\n' ' Changed in version 3.6: The *readrc* argument.\n' '\n' ' run(statement, globals=None, locals=None)\n' ' runeval(expression, globals=None, locals=None)\n' ' runcall(function, *args, **kwds)\n' ' set_trace()\n' '\n' ' See the documentation for the functions explained above.\n' '\n' '\n' 'Debugger Commands\n' '=================\n' '\n' 'The commands recognized by the debugger are listed below. Most\n' 'commands can be abbreviated to one or two letters as indicated; ' 'e.g.\n' '"h(elp)" means that either "h" or "help" can be used to enter ' 'the help\n' 'command (but not "he" or "hel", nor "H" or "Help" or "HELP").\n' 'Arguments to commands must be separated by whitespace (spaces ' 'or\n' 'tabs). Optional arguments are enclosed in square brackets ' '("[]") in\n' 'the command syntax; the square brackets must not be typed.\n' 'Alternatives in the command syntax are separated by a vertical ' 'bar\n' '("|").\n' '\n' 'Entering a blank line repeats the last command entered. ' 'Exception: if\n' 'the last command was a "list" command, the next 11 lines are ' 'listed.\n' '\n' 'Commands that the debugger doesn’t recognize are assumed to be ' 'Python\n' 'statements and are executed in the context of the program being\n' 'debugged. Python statements can also be prefixed with an ' 'exclamation\n' 'point ("!"). This is a powerful way to inspect the program ' 'being\n' 'debugged; it is even possible to change a variable or call a ' 'function.\n' 'When an exception occurs in such a statement, the exception name ' 'is\n' 'printed but the debugger’s state is not changed.\n' '\n' 'The debugger supports aliases. Aliases can have parameters ' 'which\n' 'allows one a certain level of adaptability to the context under\n' 'examination.\n' '\n' 'Multiple commands may be entered on a single line, separated by ' '";;".\n' '(A single ";" is not used as it is the separator for multiple ' 'commands\n' 'in a line that is passed to the Python parser.) No intelligence ' 'is\n' 'applied to separating the commands; the input is split at the ' 'first\n' '";;" pair, even if it is in the middle of a quoted string.\n' '\n' 'If a file ".pdbrc" exists in the user’s home directory or in ' 'the\n' 'current directory, it is read in and executed as if it had been ' 'typed\n' 'at the debugger prompt. This is particularly useful for ' 'aliases. If\n' 'both files exist, the one in the home directory is read first ' 'and\n' 'aliases defined there can be overridden by the local file.\n' '\n' 'Changed in version 3.2: ".pdbrc" can now contain commands that\n' 'continue debugging, such as "continue" or "next". Previously, ' 'these\n' 'commands had no effect.\n' '\n' 'h(elp) [command]\n' '\n' ' Without argument, print the list of available commands. With ' 'a\n' ' *command* as argument, print help about that command. "help ' 'pdb"\n' ' displays the full documentation (the docstring of the "pdb"\n' ' module). Since the *command* argument must be an identifier, ' '"help\n' ' exec" must be entered to get help on the "!" command.\n' '\n' 'w(here)\n' '\n' ' Print a stack trace, with the most recent frame at the ' 'bottom. An\n' ' arrow indicates the current frame, which determines the ' 'context of\n' ' most commands.\n' '\n' 'd(own) [count]\n' '\n' ' Move the current frame *count* (default one) levels down in ' 'the\n' ' stack trace (to a newer frame).\n' '\n' 'u(p) [count]\n' '\n' ' Move the current frame *count* (default one) levels up in the ' 'stack\n' ' trace (to an older frame).\n' '\n' 'b(reak) [([filename:]lineno | function) [, condition]]\n' '\n' ' With a *lineno* argument, set a break there in the current ' 'file.\n' ' With a *function* argument, set a break at the first ' 'executable\n' ' statement within that function. The line number may be ' 'prefixed\n' ' with a filename and a colon, to specify a breakpoint in ' 'another\n' ' file (probably one that hasn’t been loaded yet). The file ' 'is\n' ' searched on "sys.path". Note that each breakpoint is ' 'assigned a\n' ' number to which all the other breakpoint commands refer.\n' '\n' ' If a second argument is present, it is an expression which ' 'must\n' ' evaluate to true before the breakpoint is honored.\n' '\n' ' Without argument, list all breaks, including for each ' 'breakpoint,\n' ' the number of times that breakpoint has been hit, the ' 'current\n' ' ignore count, and the associated condition if any.\n' '\n' 'tbreak [([filename:]lineno | function) [, condition]]\n' '\n' ' Temporary breakpoint, which is removed automatically when it ' 'is\n' ' first hit. The arguments are the same as for "break".\n' '\n' 'cl(ear) [filename:lineno | bpnumber ...]\n' '\n' ' With a *filename:lineno* argument, clear all the breakpoints ' 'at\n' ' this line. With a space separated list of breakpoint numbers, ' 'clear\n' ' those breakpoints. Without argument, clear all breaks (but ' 'first\n' ' ask confirmation).\n' '\n' 'disable [bpnumber ...]\n' '\n' ' Disable the breakpoints given as a space separated list of\n' ' breakpoint numbers. Disabling a breakpoint means it cannot ' 'cause\n' ' the program to stop execution, but unlike clearing a ' 'breakpoint, it\n' ' remains in the list of breakpoints and can be (re-)enabled.\n' '\n' 'enable [bpnumber ...]\n' '\n' ' Enable the breakpoints specified.\n' '\n' 'ignore bpnumber [count]\n' '\n' ' Set the ignore count for the given breakpoint number. If ' 'count is\n' ' omitted, the ignore count is set to 0. A breakpoint becomes ' 'active\n' ' when the ignore count is zero. When non-zero, the count is\n' ' decremented each time the breakpoint is reached and the ' 'breakpoint\n' ' is not disabled and any associated condition evaluates to ' 'true.\n' '\n' 'condition bpnumber [condition]\n' '\n' ' Set a new *condition* for the breakpoint, an expression which ' 'must\n' ' evaluate to true before the breakpoint is honored. If ' '*condition*\n' ' is absent, any existing condition is removed; i.e., the ' 'breakpoint\n' ' is made unconditional.\n' '\n' 'commands [bpnumber]\n' '\n' ' Specify a list of commands for breakpoint number *bpnumber*. ' 'The\n' ' commands themselves appear on the following lines. Type a ' 'line\n' ' containing just "end" to terminate the commands. An example:\n' '\n' ' (Pdb) commands 1\n' ' (com) p some_variable\n' ' (com) end\n' ' (Pdb)\n' '\n' ' To remove all commands from a breakpoint, type "commands" ' 'and\n' ' follow it immediately with "end"; that is, give no commands.\n' '\n' ' With no *bpnumber* argument, "commands" refers to the last\n' ' breakpoint set.\n' '\n' ' You can use breakpoint commands to start your program up ' 'again.\n' ' Simply use the "continue" command, or "step", or any other ' 'command\n' ' that resumes execution.\n' '\n' ' Specifying any command resuming execution (currently ' '"continue",\n' ' "step", "next", "return", "jump", "quit" and their ' 'abbreviations)\n' ' terminates the command list (as if that command was ' 'immediately\n' ' followed by end). This is because any time you resume ' 'execution\n' ' (even with a simple next or step), you may encounter another\n' ' breakpoint—which could have its own command list, leading to\n' ' ambiguities about which list to execute.\n' '\n' ' If you use the ‘silent’ command in the command list, the ' 'usual\n' ' message about stopping at a breakpoint is not printed. This ' 'may be\n' ' desirable for breakpoints that are to print a specific ' 'message and\n' ' then continue. If none of the other commands print anything, ' 'you\n' ' see no sign that the breakpoint was reached.\n' '\n' 's(tep)\n' '\n' ' Execute the current line, stop at the first possible ' 'occasion\n' ' (either in a function that is called or on the next line in ' 'the\n' ' current function).\n' '\n' 'n(ext)\n' '\n' ' Continue execution until the next line in the current ' 'function is\n' ' reached or it returns. (The difference between "next" and ' '"step"\n' ' is that "step" stops inside a called function, while "next"\n' ' executes called functions at (nearly) full speed, only ' 'stopping at\n' ' the next line in the current function.)\n' '\n' 'unt(il) [lineno]\n' '\n' ' Without argument, continue execution until the line with a ' 'number\n' ' greater than the current one is reached.\n' '\n' ' With a line number, continue execution until a line with a ' 'number\n' ' greater or equal to that is reached. In both cases, also ' 'stop when\n' ' the current frame returns.\n' '\n' ' Changed in version 3.2: Allow giving an explicit line ' 'number.\n' '\n' 'r(eturn)\n' '\n' ' Continue execution until the current function returns.\n' '\n' 'c(ont(inue))\n' '\n' ' Continue execution, only stop when a breakpoint is ' 'encountered.\n' '\n' 'j(ump) lineno\n' '\n' ' Set the next line that will be executed. Only available in ' 'the\n' ' bottom-most frame. This lets you jump back and execute code ' 'again,\n' ' or jump forward to skip code that you don’t want to run.\n' '\n' ' It should be noted that not all jumps are allowed – for ' 'instance it\n' ' is not possible to jump into the middle of a "for" loop or ' 'out of a\n' ' "finally" clause.\n' '\n' 'l(ist) [first[, last]]\n' '\n' ' List source code for the current file. Without arguments, ' 'list 11\n' ' lines around the current line or continue the previous ' 'listing.\n' ' With "." as argument, list 11 lines around the current line. ' 'With\n' ' one argument, list 11 lines around at that line. With two\n' ' arguments, list the given range; if the second argument is ' 'less\n' ' than the first, it is interpreted as a count.\n' '\n' ' The current line in the current frame is indicated by "->". ' 'If an\n' ' exception is being debugged, the line where the exception ' 'was\n' ' originally raised or propagated is indicated by ">>", if it ' 'differs\n' ' from the current line.\n' '\n' ' New in version 3.2: The ">>" marker.\n' '\n' 'll | longlist\n' '\n' ' List all source code for the current function or frame.\n' ' Interesting lines are marked as for "list".\n' '\n' ' New in version 3.2.\n' '\n' 'a(rgs)\n' '\n' ' Print the argument list of the current function.\n' '\n' 'p expression\n' '\n' ' Evaluate the *expression* in the current context and print ' 'its\n' ' value.\n' '\n' ' Note:\n' '\n' ' "print()" can also be used, but is not a debugger command — ' 'this\n' ' executes the Python "print()" function.\n' '\n' 'pp expression\n' '\n' ' Like the "p" command, except the value of the expression is ' 'pretty-\n' ' printed using the "pprint" module.\n' '\n' 'whatis expression\n' '\n' ' Print the type of the *expression*.\n' '\n' 'source expression\n' '\n' ' Try to get source code for the given object and display it.\n' '\n' ' New in version 3.2.\n' '\n' 'display [expression]\n' '\n' ' Display the value of the expression if it changed, each time\n' ' execution stops in the current frame.\n' '\n' ' Without expression, list all display expressions for the ' 'current\n' ' frame.\n' '\n' ' New in version 3.2.\n' '\n' 'undisplay [expression]\n' '\n' ' Do not display the expression any more in the current frame.\n' ' Without expression, clear all display expressions for the ' 'current\n' ' frame.\n' '\n' ' New in version 3.2.\n' '\n' 'interact\n' '\n' ' Start an interactive interpreter (using the "code" module) ' 'whose\n' ' global namespace contains all the (global and local) names ' 'found in\n' ' the current scope.\n' '\n' ' New in version 3.2.\n' '\n' 'alias [name [command]]\n' '\n' ' Create an alias called *name* that executes *command*. The ' 'command\n' ' must *not* be enclosed in quotes. Replaceable parameters can ' 'be\n' ' indicated by "%1", "%2", and so on, while "%*" is replaced by ' 'all\n' ' the parameters. If no command is given, the current alias ' 'for\n' ' *name* is shown. If no arguments are given, all aliases are ' 'listed.\n' '\n' ' Aliases may be nested and can contain anything that can be ' 'legally\n' ' typed at the pdb prompt. Note that internal pdb commands ' '*can* be\n' ' overridden by aliases. Such a command is then hidden until ' 'the\n' ' alias is removed. Aliasing is recursively applied to the ' 'first\n' ' word of the command line; all other words in the line are ' 'left\n' ' alone.\n' '\n' ' As an example, here are two useful aliases (especially when ' 'placed\n' ' in the ".pdbrc" file):\n' '\n' ' # Print instance variables (usage "pi classInst")\n' ' alias pi for k in %1.__dict__.keys(): ' 'print("%1.",k,"=",%1.__dict__[k])\n' ' # Print instance variables in self\n' ' alias ps pi self\n' '\n' 'unalias name\n' '\n' ' Delete the specified alias.\n' '\n' '! statement\n' '\n' ' Execute the (one-line) *statement* in the context of the ' 'current\n' ' stack frame. The exclamation point can be omitted unless the ' 'first\n' ' word of the statement resembles a debugger command. To set ' 'a\n' ' global variable, you can prefix the assignment command with ' 'a\n' ' "global" statement on the same line, e.g.:\n' '\n' " (Pdb) global list_options; list_options = ['-l']\n" ' (Pdb)\n' '\n' 'run [args ...]\n' 'restart [args ...]\n' '\n' ' Restart the debugged Python program. If an argument is ' 'supplied,\n' ' it is split with "shlex" and the result is used as the new\n' ' "sys.argv". History, breakpoints, actions and debugger ' 'options are\n' ' preserved. "restart" is an alias for "run".\n' '\n' 'q(uit)\n' '\n' ' Quit from the debugger. The program being executed is ' 'aborted.\n' '\n' 'debug code\n' '\n' ' Enter a recursive debugger that steps through the code ' 'argument\n' ' (which is an arbitrary expression or statement to be executed ' 'in\n' ' the current environment).\n' '\n' 'retval\n' '\n' ' Print the return value for the last return of a function.\n' '\n' '-[ Footnotes ]-\n' '\n' '[1] Whether a frame is considered to originate in a certain ' 'module is\n' ' determined by the "__name__" in the frame globals.\n', 'del': 'The "del" statement\n' '*******************\n' '\n' ' del_stmt ::= "del" target_list\n' '\n' 'Deletion is recursively defined very similar to the way assignment ' 'is\n' 'defined. Rather than spelling it out in full details, here are some\n' 'hints.\n' '\n' 'Deletion of a target list recursively deletes each target, from left\n' 'to right.\n' '\n' 'Deletion of a name removes the binding of that name from the local ' 'or\n' 'global namespace, depending on whether the name occurs in a "global"\n' 'statement in the same code block. If the name is unbound, a\n' '"NameError" exception will be raised.\n' '\n' 'Deletion of attribute references, subscriptions and slicings is ' 'passed\n' 'to the primary object involved; deletion of a slicing is in general\n' 'equivalent to assignment of an empty slice of the right type (but ' 'even\n' 'this is determined by the sliced object).\n' '\n' 'Changed in version 3.2: Previously it was illegal to delete a name\n' 'from the local namespace if it occurs as a free variable in a nested\n' 'block.\n', 'dict': 'Dictionary displays\n' '*******************\n' '\n' 'A dictionary display is a possibly empty series of key/datum pairs\n' 'enclosed in curly braces:\n' '\n' ' dict_display ::= "{" [key_datum_list | dict_comprehension] ' '"}"\n' ' key_datum_list ::= key_datum ("," key_datum)* [","]\n' ' key_datum ::= expression ":" expression | "**" or_expr\n' ' dict_comprehension ::= expression ":" expression comp_for\n' '\n' 'A dictionary display yields a new dictionary object.\n' '\n' 'If a comma-separated sequence of key/datum pairs is given, they are\n' 'evaluated from left to right to define the entries of the ' 'dictionary:\n' 'each key object is used as a key into the dictionary to store the\n' 'corresponding datum. This means that you can specify the same key\n' 'multiple times in the key/datum list, and the final dictionary’s ' 'value\n' 'for that key will be the last one given.\n' '\n' 'A double asterisk "**" denotes *dictionary unpacking*. Its operand\n' 'must be a *mapping*. Each mapping item is added to the new\n' 'dictionary. Later values replace values already set by earlier\n' 'key/datum pairs and earlier dictionary unpackings.\n' '\n' 'New in version 3.5: Unpacking into dictionary displays, originally\n' 'proposed by **PEP 448**.\n' '\n' 'A dict comprehension, in contrast to list and set comprehensions,\n' 'needs two expressions separated with a colon followed by the usual\n' '“for” and “if” clauses. When the comprehension is run, the ' 'resulting\n' 'key and value elements are inserted in the new dictionary in the ' 'order\n' 'they are produced.\n' '\n' 'Restrictions on the types of the key values are listed earlier in\n' 'section The standard type hierarchy. (To summarize, the key type\n' 'should be *hashable*, which excludes all mutable objects.) Clashes\n' 'between duplicate keys are not detected; the last datum (textually\n' 'rightmost in the display) stored for a given key value prevails.\n' '\n' 'Changed in version 3.8: Prior to Python 3.8, in dict ' 'comprehensions,\n' 'the evaluation order of key and value was not well-defined. In\n' 'CPython, the value was evaluated before the key. Starting with ' '3.8,\n' 'the key is evaluated before the value, as proposed by **PEP 572**.\n', 'dynamic-features': 'Interaction with dynamic features\n' '*********************************\n' '\n' 'Name resolution of free variables occurs at runtime, not ' 'at compile\n' 'time. This means that the following code will print 42:\n' '\n' ' i = 10\n' ' def f():\n' ' print(i)\n' ' i = 42\n' ' f()\n' '\n' 'The "eval()" and "exec()" functions do not have access ' 'to the full\n' 'environment for resolving names. Names may be resolved ' 'in the local\n' 'and global namespaces of the caller. Free variables are ' 'not resolved\n' 'in the nearest enclosing namespace, but in the global ' 'namespace. [1]\n' 'The "exec()" and "eval()" functions have optional ' 'arguments to\n' 'override the global and local namespace. If only one ' 'namespace is\n' 'specified, it is used for both.\n', 'else': 'The "if" statement\n' '******************\n' '\n' 'The "if" statement is used for conditional execution:\n' '\n' ' if_stmt ::= "if" assignment_expression ":" suite\n' ' ("elif" assignment_expression ":" suite)*\n' ' ["else" ":" suite]\n' '\n' 'It selects exactly one of the suites by evaluating the expressions ' 'one\n' 'by one until one is found to be true (see section Boolean ' 'operations\n' 'for the definition of true and false); then that suite is executed\n' '(and no other part of the "if" statement is executed or evaluated).\n' 'If all expressions are false, the suite of the "else" clause, if\n' 'present, is executed.\n', 'exceptions': 'Exceptions\n' '**********\n' '\n' 'Exceptions are a means of breaking out of the normal flow of ' 'control\n' 'of a code block in order to handle errors or other ' 'exceptional\n' 'conditions. An exception is *raised* at the point where the ' 'error is\n' 'detected; it may be *handled* by the surrounding code block or ' 'by any\n' 'code block that directly or indirectly invoked the code block ' 'where\n' 'the error occurred.\n' '\n' 'The Python interpreter raises an exception when it detects a ' 'run-time\n' 'error (such as division by zero). A Python program can also\n' 'explicitly raise an exception with the "raise" statement. ' 'Exception\n' 'handlers are specified with the "try" … "except" statement. ' 'The\n' '"finally" clause of such a statement can be used to specify ' 'cleanup\n' 'code which does not handle the exception, but is executed ' 'whether an\n' 'exception occurred or not in the preceding code.\n' '\n' 'Python uses the “termination” model of error handling: an ' 'exception\n' 'handler can find out what happened and continue execution at ' 'an outer\n' 'level, but it cannot repair the cause of the error and retry ' 'the\n' 'failing operation (except by re-entering the offending piece ' 'of code\n' 'from the top).\n' '\n' 'When an exception is not handled at all, the interpreter ' 'terminates\n' 'execution of the program, or returns to its interactive main ' 'loop. In\n' 'either case, it prints a stack traceback, except when the ' 'exception is\n' '"SystemExit".\n' '\n' 'Exceptions are identified by class instances. The "except" ' 'clause is\n' 'selected depending on the class of the instance: it must ' 'reference the\n' 'class of the instance or a base class thereof. The instance ' 'can be\n' 'received by the handler and can carry additional information ' 'about the\n' 'exceptional condition.\n' '\n' 'Note:\n' '\n' ' Exception messages are not part of the Python API. Their ' 'contents\n' ' may change from one version of Python to the next without ' 'warning\n' ' and should not be relied on by code which will run under ' 'multiple\n' ' versions of the interpreter.\n' '\n' 'See also the description of the "try" statement in section The ' 'try\n' 'statement and "raise" statement in section The raise ' 'statement.\n' '\n' '-[ Footnotes ]-\n' '\n' '[1] This limitation occurs because the code that is executed ' 'by these\n' ' operations is not available at the time the module is ' 'compiled.\n', 'execmodel': 'Execution model\n' '***************\n' '\n' '\n' 'Structure of a program\n' '======================\n' '\n' 'A Python program is constructed from code blocks. A *block* is ' 'a piece\n' 'of Python program text that is executed as a unit. The ' 'following are\n' 'blocks: a module, a function body, and a class definition. ' 'Each\n' 'command typed interactively is a block. A script file (a file ' 'given\n' 'as standard input to the interpreter or specified as a command ' 'line\n' 'argument to the interpreter) is a code block. A script command ' '(a\n' 'command specified on the interpreter command line with the ' '"-c"\n' 'option) is a code block. A module run as a top level script (as ' 'module\n' '"__main__") from the command line using a "-m" argument is also ' 'a code\n' 'block. The string argument passed to the built-in functions ' '"eval()"\n' 'and "exec()" is a code block.\n' '\n' 'A code block is executed in an *execution frame*. A frame ' 'contains\n' 'some administrative information (used for debugging) and ' 'determines\n' 'where and how execution continues after the code block’s ' 'execution has\n' 'completed.\n' '\n' '\n' 'Naming and binding\n' '==================\n' '\n' '\n' 'Binding of names\n' '----------------\n' '\n' '*Names* refer to objects. Names are introduced by name ' 'binding\n' 'operations.\n' '\n' 'The following constructs bind names: formal parameters to ' 'functions,\n' '"import" statements, class and function definitions (these bind ' 'the\n' 'class or function name in the defining block), and targets that ' 'are\n' 'identifiers if occurring in an assignment, "for" loop header, ' 'or after\n' '"as" in a "with" statement or "except" clause. The "import" ' 'statement\n' 'of the form "from ... import *" binds all names defined in the\n' 'imported module, except those beginning with an underscore. ' 'This form\n' 'may only be used at the module level.\n' '\n' 'A target occurring in a "del" statement is also considered ' 'bound for\n' 'this purpose (though the actual semantics are to unbind the ' 'name).\n' '\n' 'Each assignment or import statement occurs within a block ' 'defined by a\n' 'class or function definition or at the module level (the ' 'top-level\n' 'code block).\n' '\n' 'If a name is bound in a block, it is a local variable of that ' 'block,\n' 'unless declared as "nonlocal" or "global". If a name is bound ' 'at the\n' 'module level, it is a global variable. (The variables of the ' 'module\n' 'code block are local and global.) If a variable is used in a ' 'code\n' 'block but not defined there, it is a *free variable*.\n' '\n' 'Each occurrence of a name in the program text refers to the ' '*binding*\n' 'of that name established by the following name resolution ' 'rules.\n' '\n' '\n' 'Resolution of names\n' '-------------------\n' '\n' 'A *scope* defines the visibility of a name within a block. If ' 'a local\n' 'variable is defined in a block, its scope includes that block. ' 'If the\n' 'definition occurs in a function block, the scope extends to any ' 'blocks\n' 'contained within the defining one, unless a contained block ' 'introduces\n' 'a different binding for the name.\n' '\n' 'When a name is used in a code block, it is resolved using the ' 'nearest\n' 'enclosing scope. The set of all such scopes visible to a code ' 'block\n' 'is called the block’s *environment*.\n' '\n' 'When a name is not found at all, a "NameError" exception is ' 'raised. If\n' 'the current scope is a function scope, and the name refers to a ' 'local\n' 'variable that has not yet been bound to a value at the point ' 'where the\n' 'name is used, an "UnboundLocalError" exception is raised.\n' '"UnboundLocalError" is a subclass of "NameError".\n' '\n' 'If a name binding operation occurs anywhere within a code ' 'block, all\n' 'uses of the name within the block are treated as references to ' 'the\n' 'current block. This can lead to errors when a name is used ' 'within a\n' 'block before it is bound. This rule is subtle. Python lacks\n' 'declarations and allows name binding operations to occur ' 'anywhere\n' 'within a code block. The local variables of a code block can ' 'be\n' 'determined by scanning the entire text of the block for name ' 'binding\n' 'operations.\n' '\n' 'If the "global" statement occurs within a block, all uses of ' 'the name\n' 'specified in the statement refer to the binding of that name in ' 'the\n' 'top-level namespace. Names are resolved in the top-level ' 'namespace by\n' 'searching the global namespace, i.e. the namespace of the ' 'module\n' 'containing the code block, and the builtins namespace, the ' 'namespace\n' 'of the module "builtins". The global namespace is searched ' 'first. If\n' 'the name is not found there, the builtins namespace is ' 'searched. The\n' '"global" statement must precede all uses of the name.\n' '\n' 'The "global" statement has the same scope as a name binding ' 'operation\n' 'in the same block. If the nearest enclosing scope for a free ' 'variable\n' 'contains a global statement, the free variable is treated as a ' 'global.\n' '\n' 'The "nonlocal" statement causes corresponding names to refer ' 'to\n' 'previously bound variables in the nearest enclosing function ' 'scope.\n' '"SyntaxError" is raised at compile time if the given name does ' 'not\n' 'exist in any enclosing function scope.\n' '\n' 'The namespace for a module is automatically created the first ' 'time a\n' 'module is imported. The main module for a script is always ' 'called\n' '"__main__".\n' '\n' 'Class definition blocks and arguments to "exec()" and "eval()" ' 'are\n' 'special in the context of name resolution. A class definition ' 'is an\n' 'executable statement that may use and define names. These ' 'references\n' 'follow the normal rules for name resolution with an exception ' 'that\n' 'unbound local variables are looked up in the global namespace. ' 'The\n' 'namespace of the class definition becomes the attribute ' 'dictionary of\n' 'the class. The scope of names defined in a class block is ' 'limited to\n' 'the class block; it does not extend to the code blocks of ' 'methods –\n' 'this includes comprehensions and generator expressions since ' 'they are\n' 'implemented using a function scope. This means that the ' 'following\n' 'will fail:\n' '\n' ' class A:\n' ' a = 42\n' ' b = list(a + i for i in range(10))\n' '\n' '\n' 'Builtins and restricted execution\n' '---------------------------------\n' '\n' '**CPython implementation detail:** Users should not touch\n' '"__builtins__"; it is strictly an implementation detail. ' 'Users\n' 'wanting to override values in the builtins namespace should ' '"import"\n' 'the "builtins" module and modify its attributes appropriately.\n' '\n' 'The builtins namespace associated with the execution of a code ' 'block\n' 'is actually found by looking up the name "__builtins__" in its ' 'global\n' 'namespace; this should be a dictionary or a module (in the ' 'latter case\n' 'the module’s dictionary is used). By default, when in the ' '"__main__"\n' 'module, "__builtins__" is the built-in module "builtins"; when ' 'in any\n' 'other module, "__builtins__" is an alias for the dictionary of ' 'the\n' '"builtins" module itself.\n' '\n' '\n' 'Interaction with dynamic features\n' '---------------------------------\n' '\n' 'Name resolution of free variables occurs at runtime, not at ' 'compile\n' 'time. This means that the following code will print 42:\n' '\n' ' i = 10\n' ' def f():\n' ' print(i)\n' ' i = 42\n' ' f()\n' '\n' 'The "eval()" and "exec()" functions do not have access to the ' 'full\n' 'environment for resolving names. Names may be resolved in the ' 'local\n' 'and global namespaces of the caller. Free variables are not ' 'resolved\n' 'in the nearest enclosing namespace, but in the global ' 'namespace. [1]\n' 'The "exec()" and "eval()" functions have optional arguments to\n' 'override the global and local namespace. If only one namespace ' 'is\n' 'specified, it is used for both.\n' '\n' '\n' 'Exceptions\n' '==========\n' '\n' 'Exceptions are a means of breaking out of the normal flow of ' 'control\n' 'of a code block in order to handle errors or other exceptional\n' 'conditions. An exception is *raised* at the point where the ' 'error is\n' 'detected; it may be *handled* by the surrounding code block or ' 'by any\n' 'code block that directly or indirectly invoked the code block ' 'where\n' 'the error occurred.\n' '\n' 'The Python interpreter raises an exception when it detects a ' 'run-time\n' 'error (such as division by zero). A Python program can also\n' 'explicitly raise an exception with the "raise" statement. ' 'Exception\n' 'handlers are specified with the "try" … "except" statement. ' 'The\n' '"finally" clause of such a statement can be used to specify ' 'cleanup\n' 'code which does not handle the exception, but is executed ' 'whether an\n' 'exception occurred or not in the preceding code.\n' '\n' 'Python uses the “termination” model of error handling: an ' 'exception\n' 'handler can find out what happened and continue execution at an ' 'outer\n' 'level, but it cannot repair the cause of the error and retry ' 'the\n' 'failing operation (except by re-entering the offending piece of ' 'code\n' 'from the top).\n' '\n' 'When an exception is not handled at all, the interpreter ' 'terminates\n' 'execution of the program, or returns to its interactive main ' 'loop. In\n' 'either case, it prints a stack traceback, except when the ' 'exception is\n' '"SystemExit".\n' '\n' 'Exceptions are identified by class instances. The "except" ' 'clause is\n' 'selected depending on the class of the instance: it must ' 'reference the\n' 'class of the instance or a base class thereof. The instance ' 'can be\n' 'received by the handler and can carry additional information ' 'about the\n' 'exceptional condition.\n' '\n' 'Note:\n' '\n' ' Exception messages are not part of the Python API. Their ' 'contents\n' ' may change from one version of Python to the next without ' 'warning\n' ' and should not be relied on by code which will run under ' 'multiple\n' ' versions of the interpreter.\n' '\n' 'See also the description of the "try" statement in section The ' 'try\n' 'statement and "raise" statement in section The raise ' 'statement.\n' '\n' '-[ Footnotes ]-\n' '\n' '[1] This limitation occurs because the code that is executed by ' 'these\n' ' operations is not available at the time the module is ' 'compiled.\n', 'exprlists': 'Expression lists\n' '****************\n' '\n' ' expression_list ::= expression ("," expression)* [","]\n' ' starred_list ::= starred_item ("," starred_item)* ' '[","]\n' ' starred_expression ::= expression | (starred_item ",")* ' '[starred_item]\n' ' starred_item ::= assignment_expression | "*" or_expr\n' '\n' 'Except when part of a list or set display, an expression list\n' 'containing at least one comma yields a tuple. The length of ' 'the tuple\n' 'is the number of expressions in the list. The expressions are\n' 'evaluated from left to right.\n' '\n' 'An asterisk "*" denotes *iterable unpacking*. Its operand must ' 'be an\n' '*iterable*. The iterable is expanded into a sequence of items, ' 'which\n' 'are included in the new tuple, list, or set, at the site of ' 'the\n' 'unpacking.\n' '\n' 'New in version 3.5: Iterable unpacking in expression lists, ' 'originally\n' 'proposed by **PEP 448**.\n' '\n' 'The trailing comma is required only to create a single tuple ' '(a.k.a. a\n' '*singleton*); it is optional in all other cases. A single ' 'expression\n' 'without a trailing comma doesn’t create a tuple, but rather ' 'yields the\n' 'value of that expression. (To create an empty tuple, use an ' 'empty pair\n' 'of parentheses: "()".)\n', 'floating': 'Floating point literals\n' '***********************\n' '\n' 'Floating point literals are described by the following lexical\n' 'definitions:\n' '\n' ' floatnumber ::= pointfloat | exponentfloat\n' ' pointfloat ::= [digitpart] fraction | digitpart "."\n' ' exponentfloat ::= (digitpart | pointfloat) exponent\n' ' digitpart ::= digit (["_"] digit)*\n' ' fraction ::= "." digitpart\n' ' exponent ::= ("e" | "E") ["+" | "-"] digitpart\n' '\n' 'Note that the integer and exponent parts are always interpreted ' 'using\n' 'radix 10. For example, "077e010" is legal, and denotes the same ' 'number\n' 'as "77e10". The allowed range of floating point literals is\n' 'implementation-dependent. As in integer literals, underscores ' 'are\n' 'supported for digit grouping.\n' '\n' 'Some examples of floating point literals:\n' '\n' ' 3.14 10. .001 1e100 3.14e-10 0e0 ' '3.14_15_93\n' '\n' 'Changed in version 3.6: Underscores are now allowed for ' 'grouping\n' 'purposes in literals.\n', 'for': 'The "for" statement\n' '*******************\n' '\n' 'The "for" statement is used to iterate over the elements of a ' 'sequence\n' '(such as a string, tuple or list) or other iterable object:\n' '\n' ' for_stmt ::= "for" target_list "in" expression_list ":" suite\n' ' ["else" ":" suite]\n' '\n' 'The expression list is evaluated once; it should yield an iterable\n' 'object. An iterator is created for the result of the\n' '"expression_list". The suite is then executed once for each item\n' 'provided by the iterator, in the order returned by the iterator. ' 'Each\n' 'item in turn is assigned to the target list using the standard rules\n' 'for assignments (see Assignment statements), and then the suite is\n' 'executed. When the items are exhausted (which is immediately when ' 'the\n' 'sequence is empty or an iterator raises a "StopIteration" ' 'exception),\n' 'the suite in the "else" clause, if present, is executed, and the ' 'loop\n' 'terminates.\n' '\n' 'A "break" statement executed in the first suite terminates the loop\n' 'without executing the "else" clause’s suite. A "continue" statement\n' 'executed in the first suite skips the rest of the suite and ' 'continues\n' 'with the next item, or with the "else" clause if there is no next\n' 'item.\n' '\n' 'The for-loop makes assignments to the variables in the target list.\n' 'This overwrites all previous assignments to those variables ' 'including\n' 'those made in the suite of the for-loop:\n' '\n' ' for i in range(10):\n' ' print(i)\n' ' i = 5 # this will not affect the for-loop\n' ' # because i will be overwritten with the ' 'next\n' ' # index in the range\n' '\n' 'Names in the target list are not deleted when the loop is finished,\n' 'but if the sequence is empty, they will not have been assigned to at\n' 'all by the loop. Hint: the built-in function "range()" returns an\n' 'iterator of integers suitable to emulate the effect of Pascal’s "for ' 'i\n' ':= a to b do"; e.g., "list(range(3))" returns the list "[0, 1, 2]".\n' '\n' 'Note:\n' '\n' ' There is a subtlety when the sequence is being modified by the ' 'loop\n' ' (this can only occur for mutable sequences, e.g. lists). An\n' ' internal counter is used to keep track of which item is used next,\n' ' and this is incremented on each iteration. When this counter has\n' ' reached the length of the sequence the loop terminates. This ' 'means\n' ' that if the suite deletes the current (or a previous) item from ' 'the\n' ' sequence, the next item will be skipped (since it gets the index ' 'of\n' ' the current item which has already been treated). Likewise, if ' 'the\n' ' suite inserts an item in the sequence before the current item, the\n' ' current item will be treated again the next time through the loop.\n' ' This can lead to nasty bugs that can be avoided by making a\n' ' temporary copy using a slice of the whole sequence, e.g.,\n' '\n' ' for x in a[:]:\n' ' if x < 0: a.remove(x)\n', 'formatstrings': 'Format String Syntax\n' '********************\n' '\n' 'The "str.format()" method and the "Formatter" class share ' 'the same\n' 'syntax for format strings (although in the case of ' '"Formatter",\n' 'subclasses can define their own format string syntax). The ' 'syntax is\n' 'related to that of formatted string literals, but there ' 'are\n' 'differences.\n' '\n' 'Format strings contain “replacement fields” surrounded by ' 'curly braces\n' '"{}". Anything that is not contained in braces is ' 'considered literal\n' 'text, which is copied unchanged to the output. If you need ' 'to include\n' 'a brace character in the literal text, it can be escaped by ' 'doubling:\n' '"{{" and "}}".\n' '\n' 'The grammar for a replacement field is as follows:\n' '\n' ' replacement_field ::= "{" [field_name] ["!" ' 'conversion] [":" format_spec] "}"\n' ' field_name ::= arg_name ("." attribute_name | ' '"[" element_index "]")*\n' ' arg_name ::= [identifier | digit+]\n' ' attribute_name ::= identifier\n' ' element_index ::= digit+ | index_string\n' ' index_string ::= <any source character except ' '"]"> +\n' ' conversion ::= "r" | "s" | "a"\n' ' format_spec ::= <described in the next ' 'section>\n' '\n' 'In less formal terms, the replacement field can start with ' 'a\n' '*field_name* that specifies the object whose value is to be ' 'formatted\n' 'and inserted into the output instead of the replacement ' 'field. The\n' '*field_name* is optionally followed by a *conversion* ' 'field, which is\n' 'preceded by an exclamation point "\'!\'", and a ' '*format_spec*, which is\n' 'preceded by a colon "\':\'". These specify a non-default ' 'format for the\n' 'replacement value.\n' '\n' 'See also the Format Specification Mini-Language section.\n' '\n' 'The *field_name* itself begins with an *arg_name* that is ' 'either a\n' 'number or a keyword. If it’s a number, it refers to a ' 'positional\n' 'argument, and if it’s a keyword, it refers to a named ' 'keyword\n' 'argument. If the numerical arg_names in a format string ' 'are 0, 1, 2,\n' '… in sequence, they can all be omitted (not just some) and ' 'the numbers\n' '0, 1, 2, … will be automatically inserted in that order. ' 'Because\n' '*arg_name* is not quote-delimited, it is not possible to ' 'specify\n' 'arbitrary dictionary keys (e.g., the strings "\'10\'" or ' '"\':-]\'") within\n' 'a format string. The *arg_name* can be followed by any ' 'number of index\n' 'or attribute expressions. An expression of the form ' '"\'.name\'" selects\n' 'the named attribute using "getattr()", while an expression ' 'of the form\n' '"\'[index]\'" does an index lookup using "__getitem__()".\n' '\n' 'Changed in version 3.1: The positional argument specifiers ' 'can be\n' 'omitted for "str.format()", so "\'{} {}\'.format(a, b)" is ' 'equivalent to\n' '"\'{0} {1}\'.format(a, b)".\n' '\n' 'Changed in version 3.4: The positional argument specifiers ' 'can be\n' 'omitted for "Formatter".\n' '\n' 'Some simple format string examples:\n' '\n' ' "First, thou shalt count to {0}" # References first ' 'positional argument\n' ' "Bring me a {}" # Implicitly ' 'references the first positional argument\n' ' "From {} to {}" # Same as "From {0} to ' '{1}"\n' ' "My quest is {name}" # References keyword ' "argument 'name'\n" ' "Weight in tons {0.weight}" # \'weight\' attribute ' 'of first positional arg\n' ' "Units destroyed: {players[0]}" # First element of ' "keyword argument 'players'.\n" '\n' 'The *conversion* field causes a type coercion before ' 'formatting.\n' 'Normally, the job of formatting a value is done by the ' '"__format__()"\n' 'method of the value itself. However, in some cases it is ' 'desirable to\n' 'force a type to be formatted as a string, overriding its ' 'own\n' 'definition of formatting. By converting the value to a ' 'string before\n' 'calling "__format__()", the normal formatting logic is ' 'bypassed.\n' '\n' 'Three conversion flags are currently supported: "\'!s\'" ' 'which calls\n' '"str()" on the value, "\'!r\'" which calls "repr()" and ' '"\'!a\'" which\n' 'calls "ascii()".\n' '\n' 'Some examples:\n' '\n' ' "Harold\'s a clever {0!s}" # Calls str() on the ' 'argument first\n' ' "Bring out the holy {name!r}" # Calls repr() on the ' 'argument first\n' ' "More {!a}" # Calls ascii() on the ' 'argument first\n' '\n' 'The *format_spec* field contains a specification of how the ' 'value\n' 'should be presented, including such details as field width, ' 'alignment,\n' 'padding, decimal precision and so on. Each value type can ' 'define its\n' 'own “formatting mini-language” or interpretation of the ' '*format_spec*.\n' '\n' 'Most built-in types support a common formatting ' 'mini-language, which\n' 'is described in the next section.\n' '\n' 'A *format_spec* field can also include nested replacement ' 'fields\n' 'within it. These nested replacement fields may contain a ' 'field name,\n' 'conversion flag and format specification, but deeper ' 'nesting is not\n' 'allowed. The replacement fields within the format_spec ' 'are\n' 'substituted before the *format_spec* string is interpreted. ' 'This\n' 'allows the formatting of a value to be dynamically ' 'specified.\n' '\n' 'See the Format examples section for some examples.\n' '\n' '\n' 'Format Specification Mini-Language\n' '==================================\n' '\n' '“Format specifications” are used within replacement fields ' 'contained\n' 'within a format string to define how individual values are ' 'presented\n' '(see Format String Syntax and Formatted string literals). ' 'They can\n' 'also be passed directly to the built-in "format()" ' 'function. Each\n' 'formattable type may define how the format specification is ' 'to be\n' 'interpreted.\n' '\n' 'Most built-in types implement the following options for ' 'format\n' 'specifications, although some of the formatting options are ' 'only\n' 'supported by the numeric types.\n' '\n' 'A general convention is that an empty format specification ' 'produces\n' 'the same result as if you had called "str()" on the value. ' 'A non-empty\n' 'format specification typically modifies the result.\n' '\n' 'The general form of a *standard format specifier* is:\n' '\n' ' format_spec ::= ' '[[fill]align][sign][#][0][width][grouping_option][.precision][type]\n' ' fill ::= <any character>\n' ' align ::= "<" | ">" | "=" | "^"\n' ' sign ::= "+" | "-" | " "\n' ' width ::= digit+\n' ' grouping_option ::= "_" | ","\n' ' precision ::= digit+\n' ' type ::= "b" | "c" | "d" | "e" | "E" | "f" | ' '"F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"\n' '\n' 'If a valid *align* value is specified, it can be preceded ' 'by a *fill*\n' 'character that can be any character and defaults to a space ' 'if\n' 'omitted. It is not possible to use a literal curly brace ' '(“"{"” or\n' '“"}"”) as the *fill* character in a formatted string ' 'literal or when\n' 'using the "str.format()" method. However, it is possible ' 'to insert a\n' 'curly brace with a nested replacement field. This ' 'limitation doesn’t\n' 'affect the "format()" function.\n' '\n' 'The meaning of the various alignment options is as ' 'follows:\n' '\n' ' ' '+-----------+------------------------------------------------------------+\n' ' | Option | ' 'Meaning ' '|\n' ' ' '|===========|============================================================|\n' ' | "\'<\'" | Forces the field to be left-aligned ' 'within the available |\n' ' | | space (this is the default for most ' 'objects). |\n' ' ' '+-----------+------------------------------------------------------------+\n' ' | "\'>\'" | Forces the field to be right-aligned ' 'within the available |\n' ' | | space (this is the default for ' 'numbers). |\n' ' ' '+-----------+------------------------------------------------------------+\n' ' | "\'=\'" | Forces the padding to be placed after ' 'the sign (if any) |\n' ' | | but before the digits. This is used for ' 'printing fields |\n' ' | | in the form ‘+000000120’. This alignment ' 'option is only |\n' ' | | valid for numeric types. It becomes the ' 'default when ‘0’ |\n' ' | | immediately precedes the field ' 'width. |\n' ' ' '+-----------+------------------------------------------------------------+\n' ' | "\'^\'" | Forces the field to be centered within ' 'the available |\n' ' | | ' 'space. ' '|\n' ' ' '+-----------+------------------------------------------------------------+\n' '\n' 'Note that unless a minimum field width is defined, the ' 'field width\n' 'will always be the same size as the data to fill it, so ' 'that the\n' 'alignment option has no meaning in this case.\n' '\n' 'The *sign* option is only valid for number types, and can ' 'be one of\n' 'the following:\n' '\n' ' ' '+-----------+------------------------------------------------------------+\n' ' | Option | ' 'Meaning ' '|\n' ' ' '|===========|============================================================|\n' ' | "\'+\'" | indicates that a sign should be used for ' 'both positive as |\n' ' | | well as negative ' 'numbers. |\n' ' ' '+-----------+------------------------------------------------------------+\n' ' | "\'-\'" | indicates that a sign should be used ' 'only for negative |\n' ' | | numbers (this is the default ' 'behavior). |\n' ' ' '+-----------+------------------------------------------------------------+\n' ' | space | indicates that a leading space should be ' 'used on positive |\n' ' | | numbers, and a minus sign on negative ' 'numbers. |\n' ' ' '+-----------+------------------------------------------------------------+\n' '\n' 'The "\'#\'" option causes the “alternate form” to be used ' 'for the\n' 'conversion. The alternate form is defined differently for ' 'different\n' 'types. This option is only valid for integer, float and ' 'complex\n' 'types. For integers, when binary, octal, or hexadecimal ' 'output is\n' 'used, this option adds the prefix respective "\'0b\'", ' '"\'0o\'", or "\'0x\'"\n' 'to the output value. For float and complex the alternate ' 'form causes\n' 'the result of the conversion to always contain a ' 'decimal-point\n' 'character, even if no digits follow it. Normally, a ' 'decimal-point\n' 'character appears in the result of these conversions only ' 'if a digit\n' 'follows it. In addition, for "\'g\'" and "\'G\'" ' 'conversions, trailing\n' 'zeros are not removed from the result.\n' '\n' 'The "\',\'" option signals the use of a comma for a ' 'thousands separator.\n' 'For a locale aware separator, use the "\'n\'" integer ' 'presentation type\n' 'instead.\n' '\n' 'Changed in version 3.1: Added the "\',\'" option (see also ' '**PEP 378**).\n' '\n' 'The "\'_\'" option signals the use of an underscore for a ' 'thousands\n' 'separator for floating point presentation types and for ' 'integer\n' 'presentation type "\'d\'". For integer presentation types ' '"\'b\'", "\'o\'",\n' '"\'x\'", and "\'X\'", underscores will be inserted every 4 ' 'digits. For\n' 'other presentation types, specifying this option is an ' 'error.\n' '\n' 'Changed in version 3.6: Added the "\'_\'" option (see also ' '**PEP 515**).\n' '\n' '*width* is a decimal integer defining the minimum total ' 'field width,\n' 'including any prefixes, separators, and other formatting ' 'characters.\n' 'If not specified, then the field width will be determined ' 'by the\n' 'content.\n' '\n' 'When no explicit alignment is given, preceding the *width* ' 'field by a\n' 'zero ("\'0\'") character enables sign-aware zero-padding ' 'for numeric\n' 'types. This is equivalent to a *fill* character of "\'0\'" ' 'with an\n' '*alignment* type of "\'=\'".\n' '\n' 'The *precision* is a decimal number indicating how many ' 'digits should\n' 'be displayed after the decimal point for a floating point ' 'value\n' 'formatted with "\'f\'" and "\'F\'", or before and after the ' 'decimal point\n' 'for a floating point value formatted with "\'g\'" or ' '"\'G\'". For non-\n' 'number types the field indicates the maximum field size - ' 'in other\n' 'words, how many characters will be used from the field ' 'content. The\n' '*precision* is not allowed for integer values.\n' '\n' 'Finally, the *type* determines how the data should be ' 'presented.\n' '\n' 'The available string presentation types are:\n' '\n' ' ' '+-----------+------------------------------------------------------------+\n' ' | Type | ' 'Meaning ' '|\n' ' ' '|===========|============================================================|\n' ' | "\'s\'" | String format. This is the default type ' 'for strings and |\n' ' | | may be ' 'omitted. |\n' ' ' '+-----------+------------------------------------------------------------+\n' ' | None | The same as ' '"\'s\'". |\n' ' ' '+-----------+------------------------------------------------------------+\n' '\n' 'The available integer presentation types are:\n' '\n' ' ' '+-----------+------------------------------------------------------------+\n' ' | Type | ' 'Meaning ' '|\n' ' ' '|===========|============================================================|\n' ' | "\'b\'" | Binary format. Outputs the number in ' 'base 2. |\n' ' ' '+-----------+------------------------------------------------------------+\n' ' | "\'c\'" | Character. Converts the integer to the ' 'corresponding |\n' ' | | unicode character before ' 'printing. |\n' ' ' '+-----------+------------------------------------------------------------+\n' ' | "\'d\'" | Decimal Integer. Outputs the number in ' 'base 10. |\n' ' ' '+-----------+------------------------------------------------------------+\n' ' | "\'o\'" | Octal format. Outputs the number in base ' '8. |\n' ' ' '+-----------+------------------------------------------------------------+\n' ' | "\'x\'" | Hex format. Outputs the number in base ' '16, using lower- |\n' ' | | case letters for the digits above ' '9. |\n' ' ' '+-----------+------------------------------------------------------------+\n' ' | "\'X\'" | Hex format. Outputs the number in base ' '16, using upper- |\n' ' | | case letters for the digits above ' '9. |\n' ' ' '+-----------+------------------------------------------------------------+\n' ' | "\'n\'" | Number. This is the same as "\'d\'", ' 'except that it uses the |\n' ' | | current locale setting to insert the ' 'appropriate number |\n' ' | | separator ' 'characters. |\n' ' ' '+-----------+------------------------------------------------------------+\n' ' | None | The same as ' '"\'d\'". |\n' ' ' '+-----------+------------------------------------------------------------+\n' '\n' 'In addition to the above presentation types, integers can ' 'be formatted\n' 'with the floating point presentation types listed below ' '(except "\'n\'"\n' 'and "None"). When doing so, "float()" is used to convert ' 'the integer\n' 'to a floating point number before formatting.\n' '\n' 'The available presentation types for "float" and "Decimal" ' 'values are:\n' '\n' ' ' '+-----------+------------------------------------------------------------+\n' ' | Type | ' 'Meaning ' '|\n' ' ' '|===========|============================================================|\n' ' | "\'e\'" | Scientific notation. For a given ' 'precision "p", formats |\n' ' | | the number in scientific notation with the ' 'letter ‘e’ |\n' ' | | separating the coefficient from the ' 'exponent. The |\n' ' | | coefficient has one digit before and "p" ' 'digits after the |\n' ' | | decimal point, for a total of "p + 1" ' 'significant digits. |\n' ' | | With no precision given, uses a precision ' 'of "6" digits |\n' ' | | after the decimal point for "float", and ' 'shows all |\n' ' | | coefficient digits for "Decimal". If no ' 'digits follow the |\n' ' | | decimal point, the decimal point is also ' 'removed unless |\n' ' | | the "#" option is ' 'used. |\n' ' ' '+-----------+------------------------------------------------------------+\n' ' | "\'E\'" | Scientific notation. Same as "\'e\'" ' 'except it uses an upper |\n' ' | | case ‘E’ as the separator ' 'character. |\n' ' ' '+-----------+------------------------------------------------------------+\n' ' | "\'f\'" | Fixed-point notation. For a given ' 'precision "p", formats |\n' ' | | the number as a decimal number with ' 'exactly "p" digits |\n' ' | | following the decimal point. With no ' 'precision given, uses |\n' ' | | a precision of "6" digits after the ' 'decimal point for |\n' ' | | "float", and uses a precision large enough ' 'to show all |\n' ' | | coefficient digits for "Decimal". If no ' 'digits follow the |\n' ' | | decimal point, the decimal point is also ' 'removed unless |\n' ' | | the "#" option is ' 'used. |\n' ' ' '+-----------+------------------------------------------------------------+\n' ' | "\'F\'" | Fixed-point notation. Same as "\'f\'", ' 'but converts "nan" to |\n' ' | | "NAN" and "inf" to ' '"INF". |\n' ' ' '+-----------+------------------------------------------------------------+\n' ' | "\'g\'" | General format. For a given precision ' '"p >= 1", this |\n' ' | | rounds the number to "p" significant ' 'digits and then |\n' ' | | formats the result in either fixed-point ' 'format or in |\n' ' | | scientific notation, depending on its ' 'magnitude. A |\n' ' | | precision of "0" is treated as equivalent ' 'to a precision |\n' ' | | of "1". The precise rules are as follows: ' 'suppose that |\n' ' | | the result formatted with presentation ' 'type "\'e\'" and |\n' ' | | precision "p-1" would have exponent ' '"exp". Then, if "m <= |\n' ' | | exp < p", where "m" is -4 for floats and ' '-6 for |\n' ' | | "Decimals", the number is formatted with ' 'presentation type |\n' ' | | "\'f\'" and precision "p-1-exp". ' 'Otherwise, the number is |\n' ' | | formatted with presentation type "\'e\'" ' 'and precision |\n' ' | | "p-1". In both cases insignificant ' 'trailing zeros are |\n' ' | | removed from the significand, and the ' 'decimal point is |\n' ' | | also removed if there are no remaining ' 'digits following |\n' ' | | it, unless the "\'#\'" option is used. ' 'With no precision |\n' ' | | given, uses a precision of "6" significant ' 'digits for |\n' ' | | "float". For "Decimal", the coefficient of ' 'the result is |\n' ' | | formed from the coefficient digits of the ' 'value; |\n' ' | | scientific notation is used for values ' 'smaller than "1e-6" |\n' ' | | in absolute value and values where the ' 'place value of the |\n' ' | | least significant digit is larger than 1, ' 'and fixed-point |\n' ' | | notation is used otherwise. Positive and ' 'negative |\n' ' | | infinity, positive and negative zero, and ' 'nans, are |\n' ' | | formatted as "inf", "-inf", "0", "-0" and ' '"nan" |\n' ' | | respectively, regardless of the ' 'precision. |\n' ' ' '+-----------+------------------------------------------------------------+\n' ' | "\'G\'" | General format. Same as "\'g\'" except ' 'switches to "\'E\'" if |\n' ' | | the number gets too large. The ' 'representations of infinity |\n' ' | | and NaN are uppercased, ' 'too. |\n' ' ' '+-----------+------------------------------------------------------------+\n' ' | "\'n\'" | Number. This is the same as "\'g\'", ' 'except that it uses the |\n' ' | | current locale setting to insert the ' 'appropriate number |\n' ' | | separator ' 'characters. |\n' ' ' '+-----------+------------------------------------------------------------+\n' ' | "\'%\'" | Percentage. Multiplies the number by 100 ' 'and displays in |\n' ' | | fixed ("\'f\'") format, followed by a ' 'percent sign. |\n' ' ' '+-----------+------------------------------------------------------------+\n' ' | None | For "float" this is the same as "\'g\'", ' 'except that when |\n' ' | | fixed-point notation is used to format the ' 'result, it |\n' ' | | always includes at least one digit past ' 'the decimal point. |\n' ' | | The precision used is as large as needed ' 'to represent the |\n' ' | | given value faithfully. For "Decimal", ' 'this is the same |\n' ' | | as either "\'g\'" or "\'G\'" depending on ' 'the value of |\n' ' | | "context.capitals" for the current decimal ' 'context. The |\n' ' | | overall effect is to match the output of ' '"str()" as |\n' ' | | altered by the other format ' 'modifiers. |\n' ' ' '+-----------+------------------------------------------------------------+\n' '\n' '\n' 'Format examples\n' '===============\n' '\n' 'This section contains examples of the "str.format()" syntax ' 'and\n' 'comparison with the old "%"-formatting.\n' '\n' 'In most of the cases the syntax is similar to the old ' '"%"-formatting,\n' 'with the addition of the "{}" and with ":" used instead of ' '"%". For\n' 'example, "\'%03.2f\'" can be translated to "\'{:03.2f}\'".\n' '\n' 'The new format syntax also supports new and different ' 'options, shown\n' 'in the following examples.\n' '\n' 'Accessing arguments by position:\n' '\n' " >>> '{0}, {1}, {2}'.format('a', 'b', 'c')\n" " 'a, b, c'\n" " >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only\n" " 'a, b, c'\n" " >>> '{2}, {1}, {0}'.format('a', 'b', 'c')\n" " 'c, b, a'\n" " >>> '{2}, {1}, {0}'.format(*'abc') # unpacking " 'argument sequence\n' " 'c, b, a'\n" " >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' " 'indices can be repeated\n' " 'abracadabra'\n" '\n' 'Accessing arguments by name:\n' '\n' " >>> 'Coordinates: {latitude}, " "{longitude}'.format(latitude='37.24N', " "longitude='-115.81W')\n" " 'Coordinates: 37.24N, -115.81W'\n" " >>> coord = {'latitude': '37.24N', 'longitude': " "'-115.81W'}\n" " >>> 'Coordinates: {latitude}, " "{longitude}'.format(**coord)\n" " 'Coordinates: 37.24N, -115.81W'\n" '\n' 'Accessing arguments’ attributes:\n' '\n' ' >>> c = 3-5j\n' " >>> ('The complex number {0} is formed from the real " "part {0.real} '\n" " ... 'and the imaginary part {0.imag}.').format(c)\n" " 'The complex number (3-5j) is formed from the real part " "3.0 and the imaginary part -5.0.'\n" ' >>> class Point:\n' ' ... def __init__(self, x, y):\n' ' ... self.x, self.y = x, y\n' ' ... def __str__(self):\n' " ... return 'Point({self.x}, " "{self.y})'.format(self=self)\n" ' ...\n' ' >>> str(Point(4, 2))\n' " 'Point(4, 2)'\n" '\n' 'Accessing arguments’ items:\n' '\n' ' >>> coord = (3, 5)\n' " >>> 'X: {0[0]}; Y: {0[1]}'.format(coord)\n" " 'X: 3; Y: 5'\n" '\n' 'Replacing "%s" and "%r":\n' '\n' ' >>> "repr() shows quotes: {!r}; str() doesn\'t: ' '{!s}".format(\'test1\', \'test2\')\n' ' "repr() shows quotes: \'test1\'; str() doesn\'t: test2"\n' '\n' 'Aligning the text and specifying a width:\n' '\n' " >>> '{:<30}'.format('left aligned')\n" " 'left aligned '\n" " >>> '{:>30}'.format('right aligned')\n" " ' right aligned'\n" " >>> '{:^30}'.format('centered')\n" " ' centered '\n" " >>> '{:*^30}'.format('centered') # use '*' as a fill " 'char\n' " '***********centered***********'\n" '\n' 'Replacing "%+f", "%-f", and "% f" and specifying a sign:\n' '\n' " >>> '{:+f}; {:+f}'.format(3.14, -3.14) # show it " 'always\n' " '+3.140000; -3.140000'\n" " >>> '{: f}; {: f}'.format(3.14, -3.14) # show a space " 'for positive numbers\n' " ' 3.140000; -3.140000'\n" " >>> '{:-f}; {:-f}'.format(3.14, -3.14) # show only the " "minus -- same as '{:f}; {:f}'\n" " '3.140000; -3.140000'\n" '\n' 'Replacing "%x" and "%o" and converting the value to ' 'different bases:\n' '\n' ' >>> # format also supports binary numbers\n' ' >>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: ' '{0:b}".format(42)\n' " 'int: 42; hex: 2a; oct: 52; bin: 101010'\n" ' >>> # with 0x, 0o, or 0b as prefix:\n' ' >>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: ' '{0:#b}".format(42)\n' " 'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'\n" '\n' 'Using the comma as a thousands separator:\n' '\n' " >>> '{:,}'.format(1234567890)\n" " '1,234,567,890'\n" '\n' 'Expressing a percentage:\n' '\n' ' >>> points = 19\n' ' >>> total = 22\n' " >>> 'Correct answers: {:.2%}'.format(points/total)\n" " 'Correct answers: 86.36%'\n" '\n' 'Using type-specific formatting:\n' '\n' ' >>> import datetime\n' ' >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)\n' " >>> '{:%Y-%m-%d %H:%M:%S}'.format(d)\n" " '2010-07-04 12:15:58'\n" '\n' 'Nesting arguments and more complex examples:\n' '\n' " >>> for align, text in zip('<^>', ['left', 'center', " "'right']):\n" " ... '{0:{fill}{align}16}'.format(text, fill=align, " 'align=align)\n' ' ...\n' " 'left<<<<<<<<<<<<'\n" " '^^^^^center^^^^^'\n" " '>>>>>>>>>>>right'\n" ' >>>\n' ' >>> octets = [192, 168, 0, 1]\n' " >>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)\n" " 'C0A80001'\n" ' >>> int(_, 16)\n' ' 3232235521\n' ' >>>\n' ' >>> width = 5\n' ' >>> for num in range(5,12): \n' " ... for base in 'dXob':\n" " ... print('{0:{width}{base}}'.format(num, " "base=base, width=width), end=' ')\n" ' ... print()\n' ' ...\n' ' 5 5 5 101\n' ' 6 6 6 110\n' ' 7 7 7 111\n' ' 8 8 10 1000\n' ' 9 9 11 1001\n' ' 10 A 12 1010\n' ' 11 B 13 1011\n', 'function': 'Function definitions\n' '********************\n' '\n' 'A function definition defines a user-defined function object ' '(see\n' 'section The standard type hierarchy):\n' '\n' ' funcdef ::= [decorators] "def" funcname "(" ' '[parameter_list] ")"\n' ' ["->" expression] ":" suite\n' ' decorators ::= decorator+\n' ' decorator ::= "@" assignment_expression ' 'NEWLINE\n' ' dotted_name ::= identifier ("." identifier)*\n' ' parameter_list ::= defparameter ("," ' 'defparameter)* "," "/" ["," [parameter_list_no_posonly]]\n' ' | parameter_list_no_posonly\n' ' parameter_list_no_posonly ::= defparameter ("," ' 'defparameter)* ["," [parameter_list_starargs]]\n' ' | parameter_list_starargs\n' ' parameter_list_starargs ::= "*" [parameter] ("," ' 'defparameter)* ["," ["**" parameter [","]]]\n' ' | "**" parameter [","]\n' ' parameter ::= identifier [":" expression]\n' ' defparameter ::= parameter ["=" expression]\n' ' funcname ::= identifier\n' '\n' 'A function definition is an executable statement. Its execution ' 'binds\n' 'the function name in the current local namespace to a function ' 'object\n' '(a wrapper around the executable code for the function). This\n' 'function object contains a reference to the current global ' 'namespace\n' 'as the global namespace to be used when the function is called.\n' '\n' 'The function definition does not execute the function body; this ' 'gets\n' 'executed only when the function is called. [2]\n' '\n' 'A function definition may be wrapped by one or more *decorator*\n' 'expressions. Decorator expressions are evaluated when the ' 'function is\n' 'defined, in the scope that contains the function definition. ' 'The\n' 'result must be a callable, which is invoked with the function ' 'object\n' 'as the only argument. The returned value is bound to the ' 'function name\n' 'instead of the function object. Multiple decorators are applied ' 'in\n' 'nested fashion. For example, the following code\n' '\n' ' @f1(arg)\n' ' @f2\n' ' def func(): pass\n' '\n' 'is roughly equivalent to\n' '\n' ' def func(): pass\n' ' func = f1(arg)(f2(func))\n' '\n' 'except that the original function is not temporarily bound to ' 'the name\n' '"func".\n' '\n' 'Changed in version 3.9: Functions may be decorated with any ' 'valid\n' '"assignment_expression". Previously, the grammar was much more\n' 'restrictive; see **PEP 614** for details.\n' '\n' 'When one or more *parameters* have the form *parameter* "="\n' '*expression*, the function is said to have “default parameter ' 'values.”\n' 'For a parameter with a default value, the corresponding ' '*argument* may\n' 'be omitted from a call, in which case the parameter’s default ' 'value is\n' 'substituted. If a parameter has a default value, all following\n' 'parameters up until the “"*"” must also have a default value — ' 'this is\n' 'a syntactic restriction that is not expressed by the grammar.\n' '\n' '**Default parameter values are evaluated from left to right when ' 'the\n' 'function definition is executed.** This means that the ' 'expression is\n' 'evaluated once, when the function is defined, and that the same ' '“pre-\n' 'computed” value is used for each call. This is especially ' 'important\n' 'to understand when a default parameter value is a mutable ' 'object, such\n' 'as a list or a dictionary: if the function modifies the object ' '(e.g.\n' 'by appending an item to a list), the default parameter value is ' 'in\n' 'effect modified. This is generally not what was intended. A ' 'way\n' 'around this is to use "None" as the default, and explicitly test ' 'for\n' 'it in the body of the function, e.g.:\n' '\n' ' def whats_on_the_telly(penguin=None):\n' ' if penguin is None:\n' ' penguin = []\n' ' penguin.append("property of the zoo")\n' ' return penguin\n' '\n' 'Function call semantics are described in more detail in section ' 'Calls.\n' 'A function call always assigns values to all parameters ' 'mentioned in\n' 'the parameter list, either from position arguments, from ' 'keyword\n' 'arguments, or from default values. If the form “"*identifier"” ' 'is\n' 'present, it is initialized to a tuple receiving any excess ' 'positional\n' 'parameters, defaulting to the empty tuple. If the form\n' '“"**identifier"” is present, it is initialized to a new ordered\n' 'mapping receiving any excess keyword arguments, defaulting to a ' 'new\n' 'empty mapping of the same type. Parameters after “"*"” or\n' '“"*identifier"” are keyword-only parameters and may only be ' 'passed\n' 'used keyword arguments.\n' '\n' 'Parameters may have an *annotation* of the form “": ' 'expression"”\n' 'following the parameter name. Any parameter may have an ' 'annotation,\n' 'even those of the form "*identifier" or "**identifier". ' 'Functions may\n' 'have “return” annotation of the form “"-> expression"” after ' 'the\n' 'parameter list. These annotations can be any valid Python ' 'expression.\n' 'The presence of annotations does not change the semantics of a\n' 'function. The annotation values are available as string values ' 'in a\n' 'dictionary keyed by the parameters’ names in the ' '"__annotations__"\n' 'attribute of the function object.\n' '\n' 'It is also possible to create anonymous functions (functions not ' 'bound\n' 'to a name), for immediate use in expressions. This uses lambda\n' 'expressions, described in section Lambdas. Note that the ' 'lambda\n' 'expression is merely a shorthand for a simplified function ' 'definition;\n' 'a function defined in a “"def"” statement can be passed around ' 'or\n' 'assigned to another name just like a function defined by a ' 'lambda\n' 'expression. The “"def"” form is actually more powerful since ' 'it\n' 'allows the execution of multiple statements and annotations.\n' '\n' '**Programmer’s note:** Functions are first-class objects. A ' '“"def"”\n' 'statement executed inside a function definition defines a local\n' 'function that can be returned or passed around. Free variables ' 'used\n' 'in the nested function can access the local variables of the ' 'function\n' 'containing the def. See section Naming and binding for ' 'details.\n' '\n' 'See also:\n' '\n' ' **PEP 3107** - Function Annotations\n' ' The original specification for function annotations.\n' '\n' ' **PEP 484** - Type Hints\n' ' Definition of a standard meaning for annotations: type ' 'hints.\n' '\n' ' **PEP 526** - Syntax for Variable Annotations\n' ' Ability to type hint variable declarations, including ' 'class\n' ' variables and instance variables\n' '\n' ' **PEP 563** - Postponed Evaluation of Annotations\n' ' Support for forward references within annotations by ' 'preserving\n' ' annotations in a string form at runtime instead of eager\n' ' evaluation.\n', 'global': 'The "global" statement\n' '**********************\n' '\n' ' global_stmt ::= "global" identifier ("," identifier)*\n' '\n' 'The "global" statement is a declaration which holds for the ' 'entire\n' 'current code block. It means that the listed identifiers are to ' 'be\n' 'interpreted as globals. It would be impossible to assign to a ' 'global\n' 'variable without "global", although free variables may refer to\n' 'globals without being declared global.\n' '\n' 'Names listed in a "global" statement must not be used in the same ' 'code\n' 'block textually preceding that "global" statement.\n' '\n' 'Names listed in a "global" statement must not be defined as ' 'formal\n' 'parameters, or as targets in "with" statements or "except" ' 'clauses, or\n' 'in a "for" target list, "class" definition, function definition,\n' '"import" statement, or variable annotation.\n' '\n' '**CPython implementation detail:** The current implementation does ' 'not\n' 'enforce some of these restrictions, but programs should not abuse ' 'this\n' 'freedom, as future implementations may enforce them or silently ' 'change\n' 'the meaning of the program.\n' '\n' '**Programmer’s note:** "global" is a directive to the parser. It\n' 'applies only to code parsed at the same time as the "global"\n' 'statement. In particular, a "global" statement contained in a ' 'string\n' 'or code object supplied to the built-in "exec()" function does ' 'not\n' 'affect the code block *containing* the function call, and code\n' 'contained in such a string is unaffected by "global" statements in ' 'the\n' 'code containing the function call. The same applies to the ' '"eval()"\n' 'and "compile()" functions.\n', 'id-classes': 'Reserved classes of identifiers\n' '*******************************\n' '\n' 'Certain classes of identifiers (besides keywords) have ' 'special\n' 'meanings. These classes are identified by the patterns of ' 'leading and\n' 'trailing underscore characters:\n' '\n' '"_*"\n' ' Not imported by "from module import *". The special ' 'identifier "_"\n' ' is used in the interactive interpreter to store the result ' 'of the\n' ' last evaluation; it is stored in the "builtins" module. ' 'When not\n' ' in interactive mode, "_" has no special meaning and is not ' 'defined.\n' ' See section The import statement.\n' '\n' ' Note:\n' '\n' ' The name "_" is often used in conjunction with\n' ' internationalization; refer to the documentation for the\n' ' "gettext" module for more information on this ' 'convention.\n' '\n' '"__*__"\n' ' System-defined names, informally known as “dunder” names. ' 'These\n' ' names are defined by the interpreter and its ' 'implementation\n' ' (including the standard library). Current system names are\n' ' discussed in the Special method names section and ' 'elsewhere. More\n' ' will likely be defined in future versions of Python. *Any* ' 'use of\n' ' "__*__" names, in any context, that does not follow ' 'explicitly\n' ' documented use, is subject to breakage without warning.\n' '\n' '"__*"\n' ' Class-private names. Names in this category, when used ' 'within the\n' ' context of a class definition, are re-written to use a ' 'mangled form\n' ' to help avoid name clashes between “private” attributes of ' 'base and\n' ' derived classes. See section Identifiers (Names).\n', 'identifiers': 'Identifiers and keywords\n' '************************\n' '\n' 'Identifiers (also referred to as *names*) are described by ' 'the\n' 'following lexical definitions.\n' '\n' 'The syntax of identifiers in Python is based on the Unicode ' 'standard\n' 'annex UAX-31, with elaboration and changes as defined below; ' 'see also\n' '**PEP 3131** for further details.\n' '\n' 'Within the ASCII range (U+0001..U+007F), the valid characters ' 'for\n' 'identifiers are the same as in Python 2.x: the uppercase and ' 'lowercase\n' 'letters "A" through "Z", the underscore "_" and, except for ' 'the first\n' 'character, the digits "0" through "9".\n' '\n' 'Python 3.0 introduces additional characters from outside the ' 'ASCII\n' 'range (see **PEP 3131**). For these characters, the ' 'classification\n' 'uses the version of the Unicode Character Database as ' 'included in the\n' '"unicodedata" module.\n' '\n' 'Identifiers are unlimited in length. Case is significant.\n' '\n' ' identifier ::= xid_start xid_continue*\n' ' id_start ::= <all characters in general categories Lu, ' 'Ll, Lt, Lm, Lo, Nl, the underscore, and characters with the ' 'Other_ID_Start property>\n' ' id_continue ::= <all characters in id_start, plus ' 'characters in the categories Mn, Mc, Nd, Pc and others with ' 'the Other_ID_Continue property>\n' ' xid_start ::= <all characters in id_start whose NFKC ' 'normalization is in "id_start xid_continue*">\n' ' xid_continue ::= <all characters in id_continue whose NFKC ' 'normalization is in "id_continue*">\n' '\n' 'The Unicode category codes mentioned above stand for:\n' '\n' '* *Lu* - uppercase letters\n' '\n' '* *Ll* - lowercase letters\n' '\n' '* *Lt* - titlecase letters\n' '\n' '* *Lm* - modifier letters\n' '\n' '* *Lo* - other letters\n' '\n' '* *Nl* - letter numbers\n' '\n' '* *Mn* - nonspacing marks\n' '\n' '* *Mc* - spacing combining marks\n' '\n' '* *Nd* - decimal numbers\n' '\n' '* *Pc* - connector punctuations\n' '\n' '* *Other_ID_Start* - explicit list of characters in ' 'PropList.txt to\n' ' support backwards compatibility\n' '\n' '* *Other_ID_Continue* - likewise\n' '\n' 'All identifiers are converted into the normal form NFKC while ' 'parsing;\n' 'comparison of identifiers is based on NFKC.\n' '\n' 'A non-normative HTML file listing all valid identifier ' 'characters for\n' 'Unicode 4.1 can be found at\n' 'https://www.unicode.org/Public/13.0.0/ucd/DerivedCoreProperties.txt\n' '\n' '\n' 'Keywords\n' '========\n' '\n' 'The following identifiers are used as reserved words, or ' '*keywords* of\n' 'the language, and cannot be used as ordinary identifiers. ' 'They must\n' 'be spelled exactly as written here:\n' '\n' ' False await else import pass\n' ' None break except in raise\n' ' True class finally is return\n' ' and continue for lambda try\n' ' as def from nonlocal while\n' ' assert del global not with\n' ' async elif if or yield\n' '\n' '\n' 'Reserved classes of identifiers\n' '===============================\n' '\n' 'Certain classes of identifiers (besides keywords) have ' 'special\n' 'meanings. These classes are identified by the patterns of ' 'leading and\n' 'trailing underscore characters:\n' '\n' '"_*"\n' ' Not imported by "from module import *". The special ' 'identifier "_"\n' ' is used in the interactive interpreter to store the result ' 'of the\n' ' last evaluation; it is stored in the "builtins" module. ' 'When not\n' ' in interactive mode, "_" has no special meaning and is not ' 'defined.\n' ' See section The import statement.\n' '\n' ' Note:\n' '\n' ' The name "_" is often used in conjunction with\n' ' internationalization; refer to the documentation for ' 'the\n' ' "gettext" module for more information on this ' 'convention.\n' '\n' '"__*__"\n' ' System-defined names, informally known as “dunder” names. ' 'These\n' ' names are defined by the interpreter and its ' 'implementation\n' ' (including the standard library). Current system names ' 'are\n' ' discussed in the Special method names section and ' 'elsewhere. More\n' ' will likely be defined in future versions of Python. ' '*Any* use of\n' ' "__*__" names, in any context, that does not follow ' 'explicitly\n' ' documented use, is subject to breakage without warning.\n' '\n' '"__*"\n' ' Class-private names. Names in this category, when used ' 'within the\n' ' context of a class definition, are re-written to use a ' 'mangled form\n' ' to help avoid name clashes between “private” attributes of ' 'base and\n' ' derived classes. See section Identifiers (Names).\n', 'if': 'The "if" statement\n' '******************\n' '\n' 'The "if" statement is used for conditional execution:\n' '\n' ' if_stmt ::= "if" assignment_expression ":" suite\n' ' ("elif" assignment_expression ":" suite)*\n' ' ["else" ":" suite]\n' '\n' 'It selects exactly one of the suites by evaluating the expressions ' 'one\n' 'by one until one is found to be true (see section Boolean operations\n' 'for the definition of true and false); then that suite is executed\n' '(and no other part of the "if" statement is executed or evaluated).\n' 'If all expressions are false, the suite of the "else" clause, if\n' 'present, is executed.\n', 'imaginary': 'Imaginary literals\n' '******************\n' '\n' 'Imaginary literals are described by the following lexical ' 'definitions:\n' '\n' ' imagnumber ::= (floatnumber | digitpart) ("j" | "J")\n' '\n' 'An imaginary literal yields a complex number with a real part ' 'of 0.0.\n' 'Complex numbers are represented as a pair of floating point ' 'numbers\n' 'and have the same restrictions on their range. To create a ' 'complex\n' 'number with a nonzero real part, add a floating point number to ' 'it,\n' 'e.g., "(3+4j)". Some examples of imaginary literals:\n' '\n' ' 3.14j 10.j 10j .001j 1e100j 3.14e-10j ' '3.14_15_93j\n', 'import': 'The "import" statement\n' '**********************\n' '\n' ' import_stmt ::= "import" module ["as" identifier] ("," ' 'module ["as" identifier])*\n' ' | "from" relative_module "import" identifier ' '["as" identifier]\n' ' ("," identifier ["as" identifier])*\n' ' | "from" relative_module "import" "(" ' 'identifier ["as" identifier]\n' ' ("," identifier ["as" identifier])* [","] ")"\n' ' | "from" module "import" "*"\n' ' module ::= (identifier ".")* identifier\n' ' relative_module ::= "."* module | "."+\n' '\n' 'The basic import statement (no "from" clause) is executed in two\n' 'steps:\n' '\n' '1. find a module, loading and initializing it if necessary\n' '\n' '2. define a name or names in the local namespace for the scope ' 'where\n' ' the "import" statement occurs.\n' '\n' 'When the statement contains multiple clauses (separated by commas) ' 'the\n' 'two steps are carried out separately for each clause, just as ' 'though\n' 'the clauses had been separated out into individual import ' 'statements.\n' '\n' 'The details of the first step, finding and loading modules are\n' 'described in greater detail in the section on the import system, ' 'which\n' 'also describes the various types of packages and modules that can ' 'be\n' 'imported, as well as all the hooks that can be used to customize ' 'the\n' 'import system. Note that failures in this step may indicate ' 'either\n' 'that the module could not be located, *or* that an error occurred\n' 'while initializing the module, which includes execution of the\n' 'module’s code.\n' '\n' 'If the requested module is retrieved successfully, it will be ' 'made\n' 'available in the local namespace in one of three ways:\n' '\n' '* If the module name is followed by "as", then the name following ' '"as"\n' ' is bound directly to the imported module.\n' '\n' '* If no other name is specified, and the module being imported is ' 'a\n' ' top level module, the module’s name is bound in the local ' 'namespace\n' ' as a reference to the imported module\n' '\n' '* If the module being imported is *not* a top level module, then ' 'the\n' ' name of the top level package that contains the module is bound ' 'in\n' ' the local namespace as a reference to the top level package. ' 'The\n' ' imported module must be accessed using its full qualified name\n' ' rather than directly\n' '\n' 'The "from" form uses a slightly more complex process:\n' '\n' '1. find the module specified in the "from" clause, loading and\n' ' initializing it if necessary;\n' '\n' '2. for each of the identifiers specified in the "import" clauses:\n' '\n' ' 1. check if the imported module has an attribute by that name\n' '\n' ' 2. if not, attempt to import a submodule with that name and ' 'then\n' ' check the imported module again for that attribute\n' '\n' ' 3. if the attribute is not found, "ImportError" is raised.\n' '\n' ' 4. otherwise, a reference to that value is stored in the local\n' ' namespace, using the name in the "as" clause if it is ' 'present,\n' ' otherwise using the attribute name\n' '\n' 'Examples:\n' '\n' ' import foo # foo imported and bound locally\n' ' import foo.bar.baz # foo.bar.baz imported, foo bound ' 'locally\n' ' import foo.bar.baz as fbb # foo.bar.baz imported and bound as ' 'fbb\n' ' from foo.bar import baz # foo.bar.baz imported and bound as ' 'baz\n' ' from foo import attr # foo imported and foo.attr bound as ' 'attr\n' '\n' 'If the list of identifiers is replaced by a star ("\'*\'"), all ' 'public\n' 'names defined in the module are bound in the local namespace for ' 'the\n' 'scope where the "import" statement occurs.\n' '\n' 'The *public names* defined by a module are determined by checking ' 'the\n' 'module’s namespace for a variable named "__all__"; if defined, it ' 'must\n' 'be a sequence of strings which are names defined or imported by ' 'that\n' 'module. The names given in "__all__" are all considered public ' 'and\n' 'are required to exist. If "__all__" is not defined, the set of ' 'public\n' 'names includes all names found in the module’s namespace which do ' 'not\n' 'begin with an underscore character ("\'_\'"). "__all__" should ' 'contain\n' 'the entire public API. It is intended to avoid accidentally ' 'exporting\n' 'items that are not part of the API (such as library modules which ' 'were\n' 'imported and used within the module).\n' '\n' 'The wild card form of import — "from module import *" — is only\n' 'allowed at the module level. Attempting to use it in class or\n' 'function definitions will raise a "SyntaxError".\n' '\n' 'When specifying what module to import you do not have to specify ' 'the\n' 'absolute name of the module. When a module or package is ' 'contained\n' 'within another package it is possible to make a relative import ' 'within\n' 'the same top package without having to mention the package name. ' 'By\n' 'using leading dots in the specified module or package after "from" ' 'you\n' 'can specify how high to traverse up the current package hierarchy\n' 'without specifying exact names. One leading dot means the current\n' 'package where the module making the import exists. Two dots means ' 'up\n' 'one package level. Three dots is up two levels, etc. So if you ' 'execute\n' '"from . import mod" from a module in the "pkg" package then you ' 'will\n' 'end up importing "pkg.mod". If you execute "from ..subpkg2 import ' 'mod"\n' 'from within "pkg.subpkg1" you will import "pkg.subpkg2.mod". The\n' 'specification for relative imports is contained in the Package\n' 'Relative Imports section.\n' '\n' '"importlib.import_module()" is provided to support applications ' 'that\n' 'determine dynamically the modules to be loaded.\n' '\n' 'Raises an auditing event "import" with arguments "module", ' '"filename",\n' '"sys.path", "sys.meta_path", "sys.path_hooks".\n' '\n' '\n' 'Future statements\n' '=================\n' '\n' 'A *future statement* is a directive to the compiler that a ' 'particular\n' 'module should be compiled using syntax or semantics that will be\n' 'available in a specified future release of Python where the ' 'feature\n' 'becomes standard.\n' '\n' 'The future statement is intended to ease migration to future ' 'versions\n' 'of Python that introduce incompatible changes to the language. ' 'It\n' 'allows use of the new features on a per-module basis before the\n' 'release in which the feature becomes standard.\n' '\n' ' future_stmt ::= "from" "__future__" "import" feature ["as" ' 'identifier]\n' ' ("," feature ["as" identifier])*\n' ' | "from" "__future__" "import" "(" feature ' '["as" identifier]\n' ' ("," feature ["as" identifier])* [","] ")"\n' ' feature ::= identifier\n' '\n' 'A future statement must appear near the top of the module. The ' 'only\n' 'lines that can appear before a future statement are:\n' '\n' '* the module docstring (if any),\n' '\n' '* comments,\n' '\n' '* blank lines, and\n' '\n' '* other future statements.\n' '\n' 'The only feature that requires using the future statement is\n' '"annotations" (see **PEP 563**).\n' '\n' 'All historical features enabled by the future statement are still\n' 'recognized by Python 3. The list includes "absolute_import",\n' '"division", "generators", "generator_stop", "unicode_literals",\n' '"print_function", "nested_scopes" and "with_statement". They are ' 'all\n' 'redundant because they are always enabled, and only kept for ' 'backwards\n' 'compatibility.\n' '\n' 'A future statement is recognized and treated specially at compile\n' 'time: Changes to the semantics of core constructs are often\n' 'implemented by generating different code. It may even be the ' 'case\n' 'that a new feature introduces new incompatible syntax (such as a ' 'new\n' 'reserved word), in which case the compiler may need to parse the\n' 'module differently. Such decisions cannot be pushed off until\n' 'runtime.\n' '\n' 'For any given release, the compiler knows which feature names ' 'have\n' 'been defined, and raises a compile-time error if a future ' 'statement\n' 'contains a feature not known to it.\n' '\n' 'The direct runtime semantics are the same as for any import ' 'statement:\n' 'there is a standard module "__future__", described later, and it ' 'will\n' 'be imported in the usual way at the time the future statement is\n' 'executed.\n' '\n' 'The interesting runtime semantics depend on the specific feature\n' 'enabled by the future statement.\n' '\n' 'Note that there is nothing special about the statement:\n' '\n' ' import __future__ [as name]\n' '\n' 'That is not a future statement; it’s an ordinary import statement ' 'with\n' 'no special semantics or syntax restrictions.\n' '\n' 'Code compiled by calls to the built-in functions "exec()" and\n' '"compile()" that occur in a module "M" containing a future ' 'statement\n' 'will, by default, use the new syntax or semantics associated with ' 'the\n' 'future statement. This can be controlled by optional arguments ' 'to\n' '"compile()" — see the documentation of that function for details.\n' '\n' 'A future statement typed at an interactive interpreter prompt ' 'will\n' 'take effect for the rest of the interpreter session. If an\n' 'interpreter is started with the "-i" option, is passed a script ' 'name\n' 'to execute, and the script includes a future statement, it will be ' 'in\n' 'effect in the interactive session started after the script is\n' 'executed.\n' '\n' 'See also:\n' '\n' ' **PEP 236** - Back to the __future__\n' ' The original proposal for the __future__ mechanism.\n', 'in': 'Membership test operations\n' '**************************\n' '\n' 'The operators "in" and "not in" test for membership. "x in s"\n' 'evaluates to "True" if *x* is a member of *s*, and "False" otherwise.\n' '"x not in s" returns the negation of "x in s". All built-in ' 'sequences\n' 'and set types support this as well as dictionary, for which "in" ' 'tests\n' 'whether the dictionary has a given key. For container types such as\n' 'list, tuple, set, frozenset, dict, or collections.deque, the\n' 'expression "x in y" is equivalent to "any(x is e or x == e for e in\n' 'y)".\n' '\n' 'For the string and bytes types, "x in y" is "True" if and only if *x*\n' 'is a substring of *y*. An equivalent test is "y.find(x) != -1".\n' 'Empty strings are always considered to be a substring of any other\n' 'string, so """ in "abc"" will return "True".\n' '\n' 'For user-defined classes which define the "__contains__()" method, "x\n' 'in y" returns "True" if "y.__contains__(x)" returns a true value, and\n' '"False" otherwise.\n' '\n' 'For user-defined classes which do not define "__contains__()" but do\n' 'define "__iter__()", "x in y" is "True" if some value "z", for which\n' 'the expression "x is z or x == z" is true, is produced while ' 'iterating\n' 'over "y". If an exception is raised during the iteration, it is as if\n' '"in" raised that exception.\n' '\n' 'Lastly, the old-style iteration protocol is tried: if a class defines\n' '"__getitem__()", "x in y" is "True" if and only if there is a non-\n' 'negative integer index *i* such that "x is y[i] or x == y[i]", and no\n' 'lower integer index raises the "IndexError" exception. (If any other\n' 'exception is raised, it is as if "in" raised that exception).\n' '\n' 'The operator "not in" is defined to have the inverse truth value of\n' '"in".\n', 'integers': 'Integer literals\n' '****************\n' '\n' 'Integer literals are described by the following lexical ' 'definitions:\n' '\n' ' integer ::= decinteger | bininteger | octinteger | ' 'hexinteger\n' ' decinteger ::= nonzerodigit (["_"] digit)* | "0"+ (["_"] ' '"0")*\n' ' bininteger ::= "0" ("b" | "B") (["_"] bindigit)+\n' ' octinteger ::= "0" ("o" | "O") (["_"] octdigit)+\n' ' hexinteger ::= "0" ("x" | "X") (["_"] hexdigit)+\n' ' nonzerodigit ::= "1"..."9"\n' ' digit ::= "0"..."9"\n' ' bindigit ::= "0" | "1"\n' ' octdigit ::= "0"..."7"\n' ' hexdigit ::= digit | "a"..."f" | "A"..."F"\n' '\n' 'There is no limit for the length of integer literals apart from ' 'what\n' 'can be stored in available memory.\n' '\n' 'Underscores are ignored for determining the numeric value of ' 'the\n' 'literal. They can be used to group digits for enhanced ' 'readability.\n' 'One underscore can occur between digits, and after base ' 'specifiers\n' 'like "0x".\n' '\n' 'Note that leading zeros in a non-zero decimal number are not ' 'allowed.\n' 'This is for disambiguation with C-style octal literals, which ' 'Python\n' 'used before version 3.0.\n' '\n' 'Some examples of integer literals:\n' '\n' ' 7 2147483647 0o177 0b100110111\n' ' 3 79228162514264337593543950336 0o377 0xdeadbeef\n' ' 100_000_000_000 0b_1110_0101\n' '\n' 'Changed in version 3.6: Underscores are now allowed for ' 'grouping\n' 'purposes in literals.\n', 'lambda': 'Lambdas\n' '*******\n' '\n' ' lambda_expr ::= "lambda" [parameter_list] ":" ' 'expression\n' ' lambda_expr_nocond ::= "lambda" [parameter_list] ":" ' 'expression_nocond\n' '\n' 'Lambda expressions (sometimes called lambda forms) are used to ' 'create\n' 'anonymous functions. The expression "lambda parameters: ' 'expression"\n' 'yields a function object. The unnamed object behaves like a ' 'function\n' 'object defined with:\n' '\n' ' def <lambda>(parameters):\n' ' return expression\n' '\n' 'See section Function definitions for the syntax of parameter ' 'lists.\n' 'Note that functions created with lambda expressions cannot ' 'contain\n' 'statements or annotations.\n', 'lists': 'List displays\n' '*************\n' '\n' 'A list display is a possibly empty series of expressions enclosed ' 'in\n' 'square brackets:\n' '\n' ' list_display ::= "[" [starred_list | comprehension] "]"\n' '\n' 'A list display yields a new list object, the contents being ' 'specified\n' 'by either a list of expressions or a comprehension. When a comma-\n' 'separated list of expressions is supplied, its elements are ' 'evaluated\n' 'from left to right and placed into the list object in that order.\n' 'When a comprehension is supplied, the list is constructed from the\n' 'elements resulting from the comprehension.\n', 'naming': 'Naming and binding\n' '******************\n' '\n' '\n' 'Binding of names\n' '================\n' '\n' '*Names* refer to objects. Names are introduced by name binding\n' 'operations.\n' '\n' 'The following constructs bind names: formal parameters to ' 'functions,\n' '"import" statements, class and function definitions (these bind ' 'the\n' 'class or function name in the defining block), and targets that ' 'are\n' 'identifiers if occurring in an assignment, "for" loop header, or ' 'after\n' '"as" in a "with" statement or "except" clause. The "import" ' 'statement\n' 'of the form "from ... import *" binds all names defined in the\n' 'imported module, except those beginning with an underscore. This ' 'form\n' 'may only be used at the module level.\n' '\n' 'A target occurring in a "del" statement is also considered bound ' 'for\n' 'this purpose (though the actual semantics are to unbind the ' 'name).\n' '\n' 'Each assignment or import statement occurs within a block defined ' 'by a\n' 'class or function definition or at the module level (the ' 'top-level\n' 'code block).\n' '\n' 'If a name is bound in a block, it is a local variable of that ' 'block,\n' 'unless declared as "nonlocal" or "global". If a name is bound at ' 'the\n' 'module level, it is a global variable. (The variables of the ' 'module\n' 'code block are local and global.) If a variable is used in a ' 'code\n' 'block but not defined there, it is a *free variable*.\n' '\n' 'Each occurrence of a name in the program text refers to the ' '*binding*\n' 'of that name established by the following name resolution rules.\n' '\n' '\n' 'Resolution of names\n' '===================\n' '\n' 'A *scope* defines the visibility of a name within a block. If a ' 'local\n' 'variable is defined in a block, its scope includes that block. If ' 'the\n' 'definition occurs in a function block, the scope extends to any ' 'blocks\n' 'contained within the defining one, unless a contained block ' 'introduces\n' 'a different binding for the name.\n' '\n' 'When a name is used in a code block, it is resolved using the ' 'nearest\n' 'enclosing scope. The set of all such scopes visible to a code ' 'block\n' 'is called the block’s *environment*.\n' '\n' 'When a name is not found at all, a "NameError" exception is ' 'raised. If\n' 'the current scope is a function scope, and the name refers to a ' 'local\n' 'variable that has not yet been bound to a value at the point where ' 'the\n' 'name is used, an "UnboundLocalError" exception is raised.\n' '"UnboundLocalError" is a subclass of "NameError".\n' '\n' 'If a name binding operation occurs anywhere within a code block, ' 'all\n' 'uses of the name within the block are treated as references to ' 'the\n' 'current block. This can lead to errors when a name is used within ' 'a\n' 'block before it is bound. This rule is subtle. Python lacks\n' 'declarations and allows name binding operations to occur anywhere\n' 'within a code block. The local variables of a code block can be\n' 'determined by scanning the entire text of the block for name ' 'binding\n' 'operations.\n' '\n' 'If the "global" statement occurs within a block, all uses of the ' 'name\n' 'specified in the statement refer to the binding of that name in ' 'the\n' 'top-level namespace. Names are resolved in the top-level ' 'namespace by\n' 'searching the global namespace, i.e. the namespace of the module\n' 'containing the code block, and the builtins namespace, the ' 'namespace\n' 'of the module "builtins". The global namespace is searched ' 'first. If\n' 'the name is not found there, the builtins namespace is searched. ' 'The\n' '"global" statement must precede all uses of the name.\n' '\n' 'The "global" statement has the same scope as a name binding ' 'operation\n' 'in the same block. If the nearest enclosing scope for a free ' 'variable\n' 'contains a global statement, the free variable is treated as a ' 'global.\n' '\n' 'The "nonlocal" statement causes corresponding names to refer to\n' 'previously bound variables in the nearest enclosing function ' 'scope.\n' '"SyntaxError" is raised at compile time if the given name does ' 'not\n' 'exist in any enclosing function scope.\n' '\n' 'The namespace for a module is automatically created the first time ' 'a\n' 'module is imported. The main module for a script is always ' 'called\n' '"__main__".\n' '\n' 'Class definition blocks and arguments to "exec()" and "eval()" ' 'are\n' 'special in the context of name resolution. A class definition is ' 'an\n' 'executable statement that may use and define names. These ' 'references\n' 'follow the normal rules for name resolution with an exception ' 'that\n' 'unbound local variables are looked up in the global namespace. ' 'The\n' 'namespace of the class definition becomes the attribute dictionary ' 'of\n' 'the class. The scope of names defined in a class block is limited ' 'to\n' 'the class block; it does not extend to the code blocks of methods ' '–\n' 'this includes comprehensions and generator expressions since they ' 'are\n' 'implemented using a function scope. This means that the ' 'following\n' 'will fail:\n' '\n' ' class A:\n' ' a = 42\n' ' b = list(a + i for i in range(10))\n' '\n' '\n' 'Builtins and restricted execution\n' '=================================\n' '\n' '**CPython implementation detail:** Users should not touch\n' '"__builtins__"; it is strictly an implementation detail. Users\n' 'wanting to override values in the builtins namespace should ' '"import"\n' 'the "builtins" module and modify its attributes appropriately.\n' '\n' 'The builtins namespace associated with the execution of a code ' 'block\n' 'is actually found by looking up the name "__builtins__" in its ' 'global\n' 'namespace; this should be a dictionary or a module (in the latter ' 'case\n' 'the module’s dictionary is used). By default, when in the ' '"__main__"\n' 'module, "__builtins__" is the built-in module "builtins"; when in ' 'any\n' 'other module, "__builtins__" is an alias for the dictionary of ' 'the\n' '"builtins" module itself.\n' '\n' '\n' 'Interaction with dynamic features\n' '=================================\n' '\n' 'Name resolution of free variables occurs at runtime, not at ' 'compile\n' 'time. This means that the following code will print 42:\n' '\n' ' i = 10\n' ' def f():\n' ' print(i)\n' ' i = 42\n' ' f()\n' '\n' 'The "eval()" and "exec()" functions do not have access to the ' 'full\n' 'environment for resolving names. Names may be resolved in the ' 'local\n' 'and global namespaces of the caller. Free variables are not ' 'resolved\n' 'in the nearest enclosing namespace, but in the global namespace. ' '[1]\n' 'The "exec()" and "eval()" functions have optional arguments to\n' 'override the global and local namespace. If only one namespace ' 'is\n' 'specified, it is used for both.\n', 'nonlocal': 'The "nonlocal" statement\n' '************************\n' '\n' ' nonlocal_stmt ::= "nonlocal" identifier ("," identifier)*\n' '\n' 'The "nonlocal" statement causes the listed identifiers to refer ' 'to\n' 'previously bound variables in the nearest enclosing scope ' 'excluding\n' 'globals. This is important because the default behavior for ' 'binding is\n' 'to search the local namespace first. The statement allows\n' 'encapsulated code to rebind variables outside of the local ' 'scope\n' 'besides the global (module) scope.\n' '\n' 'Names listed in a "nonlocal" statement, unlike those listed in ' 'a\n' '"global" statement, must refer to pre-existing bindings in an\n' 'enclosing scope (the scope in which a new binding should be ' 'created\n' 'cannot be determined unambiguously).\n' '\n' 'Names listed in a "nonlocal" statement must not collide with ' 'pre-\n' 'existing bindings in the local scope.\n' '\n' 'See also:\n' '\n' ' **PEP 3104** - Access to Names in Outer Scopes\n' ' The specification for the "nonlocal" statement.\n', 'numbers': 'Numeric literals\n' '****************\n' '\n' 'There are three types of numeric literals: integers, floating ' 'point\n' 'numbers, and imaginary numbers. There are no complex literals\n' '(complex numbers can be formed by adding a real number and an\n' 'imaginary number).\n' '\n' 'Note that numeric literals do not include a sign; a phrase like ' '"-1"\n' 'is actually an expression composed of the unary operator ‘"-"‘ ' 'and the\n' 'literal "1".\n', 'numeric-types': 'Emulating numeric types\n' '***********************\n' '\n' 'The following methods can be defined to emulate numeric ' 'objects.\n' 'Methods corresponding to operations that are not supported ' 'by the\n' 'particular kind of number implemented (e.g., bitwise ' 'operations for\n' 'non-integral numbers) should be left undefined.\n' '\n' 'object.__add__(self, other)\n' 'object.__sub__(self, other)\n' 'object.__mul__(self, other)\n' 'object.__matmul__(self, other)\n' 'object.__truediv__(self, other)\n' 'object.__floordiv__(self, other)\n' 'object.__mod__(self, other)\n' 'object.__divmod__(self, other)\n' 'object.__pow__(self, other[, modulo])\n' 'object.__lshift__(self, other)\n' 'object.__rshift__(self, other)\n' 'object.__and__(self, other)\n' 'object.__xor__(self, other)\n' 'object.__or__(self, other)\n' '\n' ' These methods are called to implement the binary ' 'arithmetic\n' ' operations ("+", "-", "*", "@", "/", "//", "%", ' '"divmod()",\n' ' "pow()", "**", "<<", ">>", "&", "^", "|"). For ' 'instance, to\n' ' evaluate the expression "x + y", where *x* is an ' 'instance of a\n' ' class that has an "__add__()" method, "x.__add__(y)" is ' 'called.\n' ' The "__divmod__()" method should be the equivalent to ' 'using\n' ' "__floordiv__()" and "__mod__()"; it should not be ' 'related to\n' ' "__truediv__()". Note that "__pow__()" should be ' 'defined to accept\n' ' an optional third argument if the ternary version of the ' 'built-in\n' ' "pow()" function is to be supported.\n' '\n' ' If one of those methods does not support the operation ' 'with the\n' ' supplied arguments, it should return "NotImplemented".\n' '\n' 'object.__radd__(self, other)\n' 'object.__rsub__(self, other)\n' 'object.__rmul__(self, other)\n' 'object.__rmatmul__(self, other)\n' 'object.__rtruediv__(self, other)\n' 'object.__rfloordiv__(self, other)\n' 'object.__rmod__(self, other)\n' 'object.__rdivmod__(self, other)\n' 'object.__rpow__(self, other[, modulo])\n' 'object.__rlshift__(self, other)\n' 'object.__rrshift__(self, other)\n' 'object.__rand__(self, other)\n' 'object.__rxor__(self, other)\n' 'object.__ror__(self, other)\n' '\n' ' These methods are called to implement the binary ' 'arithmetic\n' ' operations ("+", "-", "*", "@", "/", "//", "%", ' '"divmod()",\n' ' "pow()", "**", "<<", ">>", "&", "^", "|") with reflected ' '(swapped)\n' ' operands. These functions are only called if the left ' 'operand does\n' ' not support the corresponding operation [3] and the ' 'operands are of\n' ' different types. [4] For instance, to evaluate the ' 'expression "x -\n' ' y", where *y* is an instance of a class that has an ' '"__rsub__()"\n' ' method, "y.__rsub__(x)" is called if "x.__sub__(y)" ' 'returns\n' ' *NotImplemented*.\n' '\n' ' Note that ternary "pow()" will not try calling ' '"__rpow__()" (the\n' ' coercion rules would become too complicated).\n' '\n' ' Note:\n' '\n' ' If the right operand’s type is a subclass of the left ' 'operand’s\n' ' type and that subclass provides a different ' 'implementation of the\n' ' reflected method for the operation, this method will ' 'be called\n' ' before the left operand’s non-reflected method. This ' 'behavior\n' ' allows subclasses to override their ancestors’ ' 'operations.\n' '\n' 'object.__iadd__(self, other)\n' 'object.__isub__(self, other)\n' 'object.__imul__(self, other)\n' 'object.__imatmul__(self, other)\n' 'object.__itruediv__(self, other)\n' 'object.__ifloordiv__(self, other)\n' 'object.__imod__(self, other)\n' 'object.__ipow__(self, other[, modulo])\n' 'object.__ilshift__(self, other)\n' 'object.__irshift__(self, other)\n' 'object.__iand__(self, other)\n' 'object.__ixor__(self, other)\n' 'object.__ior__(self, other)\n' '\n' ' These methods are called to implement the augmented ' 'arithmetic\n' ' assignments ("+=", "-=", "*=", "@=", "/=", "//=", "%=", ' '"**=",\n' ' "<<=", ">>=", "&=", "^=", "|="). These methods should ' 'attempt to\n' ' do the operation in-place (modifying *self*) and return ' 'the result\n' ' (which could be, but does not have to be, *self*). If a ' 'specific\n' ' method is not defined, the augmented assignment falls ' 'back to the\n' ' normal methods. For instance, if *x* is an instance of ' 'a class\n' ' with an "__iadd__()" method, "x += y" is equivalent to ' '"x =\n' ' x.__iadd__(y)" . Otherwise, "x.__add__(y)" and ' '"y.__radd__(x)" are\n' ' considered, as with the evaluation of "x + y". In ' 'certain\n' ' situations, augmented assignment can result in ' 'unexpected errors\n' ' (see Why does a_tuple[i] += [‘item’] raise an exception ' 'when the\n' ' addition works?), but this behavior is in fact part of ' 'the data\n' ' model.\n' '\n' 'object.__neg__(self)\n' 'object.__pos__(self)\n' 'object.__abs__(self)\n' 'object.__invert__(self)\n' '\n' ' Called to implement the unary arithmetic operations ' '("-", "+",\n' ' "abs()" and "~").\n' '\n' 'object.__complex__(self)\n' 'object.__int__(self)\n' 'object.__float__(self)\n' '\n' ' Called to implement the built-in functions "complex()", ' '"int()" and\n' ' "float()". Should return a value of the appropriate ' 'type.\n' '\n' 'object.__index__(self)\n' '\n' ' Called to implement "operator.index()", and whenever ' 'Python needs\n' ' to losslessly convert the numeric object to an integer ' 'object (such\n' ' as in slicing, or in the built-in "bin()", "hex()" and ' '"oct()"\n' ' functions). Presence of this method indicates that the ' 'numeric\n' ' object is an integer type. Must return an integer.\n' '\n' ' If "__int__()", "__float__()" and "__complex__()" are ' 'not defined\n' ' then corresponding built-in functions "int()", "float()" ' 'and\n' ' "complex()" fall back to "__index__()".\n' '\n' 'object.__round__(self[, ndigits])\n' 'object.__trunc__(self)\n' 'object.__floor__(self)\n' 'object.__ceil__(self)\n' '\n' ' Called to implement the built-in function "round()" and ' '"math"\n' ' functions "trunc()", "floor()" and "ceil()". Unless ' '*ndigits* is\n' ' passed to "__round__()" all these methods should return ' 'the value\n' ' of the object truncated to an "Integral" (typically an ' '"int").\n' '\n' ' If "__int__()" is not defined then the built-in function ' '"int()"\n' ' falls back to "__trunc__()".\n', 'objects': 'Objects, values and types\n' '*************************\n' '\n' '*Objects* are Python’s abstraction for data. All data in a ' 'Python\n' 'program is represented by objects or by relations between ' 'objects. (In\n' 'a sense, and in conformance to Von Neumann’s model of a “stored\n' 'program computer”, code is also represented by objects.)\n' '\n' 'Every object has an identity, a type and a value. An object’s\n' '*identity* never changes once it has been created; you may think ' 'of it\n' 'as the object’s address in memory. The ‘"is"’ operator compares ' 'the\n' 'identity of two objects; the "id()" function returns an integer\n' 'representing its identity.\n' '\n' '**CPython implementation detail:** For CPython, "id(x)" is the ' 'memory\n' 'address where "x" is stored.\n' '\n' 'An object’s type determines the operations that the object ' 'supports\n' '(e.g., “does it have a length?”) and also defines the possible ' 'values\n' 'for objects of that type. The "type()" function returns an ' 'object’s\n' 'type (which is an object itself). Like its identity, an ' 'object’s\n' '*type* is also unchangeable. [1]\n' '\n' 'The *value* of some objects can change. Objects whose value can\n' 'change are said to be *mutable*; objects whose value is ' 'unchangeable\n' 'once they are created are called *immutable*. (The value of an\n' 'immutable container object that contains a reference to a ' 'mutable\n' 'object can change when the latter’s value is changed; however ' 'the\n' 'container is still considered immutable, because the collection ' 'of\n' 'objects it contains cannot be changed. So, immutability is not\n' 'strictly the same as having an unchangeable value, it is more ' 'subtle.)\n' 'An object’s mutability is determined by its type; for instance,\n' 'numbers, strings and tuples are immutable, while dictionaries ' 'and\n' 'lists are mutable.\n' '\n' 'Objects are never explicitly destroyed; however, when they ' 'become\n' 'unreachable they may be garbage-collected. An implementation is\n' 'allowed to postpone garbage collection or omit it altogether — it ' 'is a\n' 'matter of implementation quality how garbage collection is\n' 'implemented, as long as no objects are collected that are still\n' 'reachable.\n' '\n' '**CPython implementation detail:** CPython currently uses a ' 'reference-\n' 'counting scheme with (optional) delayed detection of cyclically ' 'linked\n' 'garbage, which collects most objects as soon as they become\n' 'unreachable, but is not guaranteed to collect garbage containing\n' 'circular references. See the documentation of the "gc" module ' 'for\n' 'information on controlling the collection of cyclic garbage. ' 'Other\n' 'implementations act differently and CPython may change. Do not ' 'depend\n' 'on immediate finalization of objects when they become unreachable ' '(so\n' 'you should always close files explicitly).\n' '\n' 'Note that the use of the implementation’s tracing or debugging\n' 'facilities may keep objects alive that would normally be ' 'collectable.\n' 'Also note that catching an exception with a ‘"try"…"except"’ ' 'statement\n' 'may keep objects alive.\n' '\n' 'Some objects contain references to “external” resources such as ' 'open\n' 'files or windows. It is understood that these resources are ' 'freed\n' 'when the object is garbage-collected, but since garbage ' 'collection is\n' 'not guaranteed to happen, such objects also provide an explicit ' 'way to\n' 'release the external resource, usually a "close()" method. ' 'Programs\n' 'are strongly recommended to explicitly close such objects. The\n' '‘"try"…"finally"’ statement and the ‘"with"’ statement provide\n' 'convenient ways to do this.\n' '\n' 'Some objects contain references to other objects; these are ' 'called\n' '*containers*. Examples of containers are tuples, lists and\n' 'dictionaries. The references are part of a container’s value. ' 'In\n' 'most cases, when we talk about the value of a container, we imply ' 'the\n' 'values, not the identities of the contained objects; however, ' 'when we\n' 'talk about the mutability of a container, only the identities of ' 'the\n' 'immediately contained objects are implied. So, if an immutable\n' 'container (like a tuple) contains a reference to a mutable ' 'object, its\n' 'value changes if that mutable object is changed.\n' '\n' 'Types affect almost all aspects of object behavior. Even the\n' 'importance of object identity is affected in some sense: for ' 'immutable\n' 'types, operations that compute new values may actually return a\n' 'reference to any existing object with the same type and value, ' 'while\n' 'for mutable objects this is not allowed. E.g., after "a = 1; b = ' '1",\n' '"a" and "b" may or may not refer to the same object with the ' 'value\n' 'one, depending on the implementation, but after "c = []; d = []", ' '"c"\n' 'and "d" are guaranteed to refer to two different, unique, newly\n' 'created empty lists. (Note that "c = d = []" assigns the same ' 'object\n' 'to both "c" and "d".)\n', 'operator-summary': 'Operator precedence\n' '*******************\n' '\n' 'The following table summarizes the operator precedence ' 'in Python, from\n' 'lowest precedence (least binding) to highest precedence ' '(most\n' 'binding). Operators in the same box have the same ' 'precedence. Unless\n' 'the syntax is explicitly given, operators are binary. ' 'Operators in\n' 'the same box group left to right (except for ' 'exponentiation, which\n' 'groups from right to left).\n' '\n' 'Note that comparisons, membership tests, and identity ' 'tests, all have\n' 'the same precedence and have a left-to-right chaining ' 'feature as\n' 'described in the Comparisons section.\n' '\n' '+-------------------------------------------------+---------------------------------------+\n' '| Operator | ' 'Description |\n' '|=================================================|=======================================|\n' '| ":=" | ' 'Assignment expression |\n' '+-------------------------------------------------+---------------------------------------+\n' '| "lambda" | ' 'Lambda expression |\n' '+-------------------------------------------------+---------------------------------------+\n' '| "if" – "else" | ' 'Conditional expression |\n' '+-------------------------------------------------+---------------------------------------+\n' '| "or" | ' 'Boolean OR |\n' '+-------------------------------------------------+---------------------------------------+\n' '| "and" | ' 'Boolean AND |\n' '+-------------------------------------------------+---------------------------------------+\n' '| "not" "x" | ' 'Boolean NOT |\n' '+-------------------------------------------------+---------------------------------------+\n' '| "in", "not in", "is", "is not", "<", "<=", ">", | ' 'Comparisons, including membership |\n' '| ">=", "!=", "==" | ' 'tests and identity tests |\n' '+-------------------------------------------------+---------------------------------------+\n' '| "|" | ' 'Bitwise OR |\n' '+-------------------------------------------------+---------------------------------------+\n' '| "^" | ' 'Bitwise XOR |\n' '+-------------------------------------------------+---------------------------------------+\n' '| "&" | ' 'Bitwise AND |\n' '+-------------------------------------------------+---------------------------------------+\n' '| "<<", ">>" | ' 'Shifts |\n' '+-------------------------------------------------+---------------------------------------+\n' '| "+", "-" | ' 'Addition and subtraction |\n' '+-------------------------------------------------+---------------------------------------+\n' '| "*", "@", "/", "//", "%" | ' 'Multiplication, matrix |\n' '| | ' 'multiplication, division, floor |\n' '| | ' 'division, remainder [5] |\n' '+-------------------------------------------------+---------------------------------------+\n' '| "+x", "-x", "~x" | ' 'Positive, negative, bitwise NOT |\n' '+-------------------------------------------------+---------------------------------------+\n' '| "**" | ' 'Exponentiation [6] |\n' '+-------------------------------------------------+---------------------------------------+\n' '| "await" "x" | ' 'Await expression |\n' '+-------------------------------------------------+---------------------------------------+\n' '| "x[index]", "x[index:index]", | ' 'Subscription, slicing, call, |\n' '| "x(arguments...)", "x.attribute" | ' 'attribute reference |\n' '+-------------------------------------------------+---------------------------------------+\n' '| "(expressions...)", "[expressions...]", "{key: | ' 'Binding or parenthesized expression, |\n' '| value...}", "{expressions...}" | list ' 'display, dictionary display, set |\n' '| | ' 'display |\n' '+-------------------------------------------------+---------------------------------------+\n' '\n' '-[ Footnotes ]-\n' '\n' '[1] While "abs(x%y) < abs(y)" is true mathematically, ' 'for floats it\n' ' may not be true numerically due to roundoff. For ' 'example, and\n' ' assuming a platform on which a Python float is an ' 'IEEE 754 double-\n' ' precision number, in order that "-1e-100 % 1e100" ' 'have the same\n' ' sign as "1e100", the computed result is "-1e-100 + ' '1e100", which\n' ' is numerically exactly equal to "1e100". The ' 'function\n' ' "math.fmod()" returns a result whose sign matches ' 'the sign of the\n' ' first argument instead, and so returns "-1e-100" in ' 'this case.\n' ' Which approach is more appropriate depends on the ' 'application.\n' '\n' '[2] If x is very close to an exact integer multiple of ' 'y, it’s\n' ' possible for "x//y" to be one larger than ' '"(x-x%y)//y" due to\n' ' rounding. In such cases, Python returns the latter ' 'result, in\n' ' order to preserve that "divmod(x,y)[0] * y + x % y" ' 'be very close\n' ' to "x".\n' '\n' '[3] The Unicode standard distinguishes between *code ' 'points* (e.g.\n' ' U+0041) and *abstract characters* (e.g. “LATIN ' 'CAPITAL LETTER A”).\n' ' While most abstract characters in Unicode are only ' 'represented\n' ' using one code point, there is a number of abstract ' 'characters\n' ' that can in addition be represented using a sequence ' 'of more than\n' ' one code point. For example, the abstract character ' '“LATIN\n' ' CAPITAL LETTER C WITH CEDILLA” can be represented as ' 'a single\n' ' *precomposed character* at code position U+00C7, or ' 'as a sequence\n' ' of a *base character* at code position U+0043 (LATIN ' 'CAPITAL\n' ' LETTER C), followed by a *combining character* at ' 'code position\n' ' U+0327 (COMBINING CEDILLA).\n' '\n' ' The comparison operators on strings compare at the ' 'level of\n' ' Unicode code points. This may be counter-intuitive ' 'to humans. For\n' ' example, ""\\u00C7" == "\\u0043\\u0327"" is "False", ' 'even though both\n' ' strings represent the same abstract character “LATIN ' 'CAPITAL\n' ' LETTER C WITH CEDILLA”.\n' '\n' ' To compare strings at the level of abstract ' 'characters (that is,\n' ' in a way intuitive to humans), use ' '"unicodedata.normalize()".\n' '\n' '[4] Due to automatic garbage-collection, free lists, and ' 'the dynamic\n' ' nature of descriptors, you may notice seemingly ' 'unusual behaviour\n' ' in certain uses of the "is" operator, like those ' 'involving\n' ' comparisons between instance methods, or constants. ' 'Check their\n' ' documentation for more info.\n' '\n' '[5] The "%" operator is also used for string formatting; ' 'the same\n' ' precedence applies.\n' '\n' '[6] The power operator "**" binds less tightly than an ' 'arithmetic or\n' ' bitwise unary operator on its right, that is, ' '"2**-1" is "0.5".\n', 'pass': 'The "pass" statement\n' '********************\n' '\n' ' pass_stmt ::= "pass"\n' '\n' '"pass" is a null operation — when it is executed, nothing happens. ' 'It\n' 'is useful as a placeholder when a statement is required ' 'syntactically,\n' 'but no code needs to be executed, for example:\n' '\n' ' def f(arg): pass # a function that does nothing (yet)\n' '\n' ' class C: pass # a class with no methods (yet)\n', 'power': 'The power operator\n' '******************\n' '\n' 'The power operator binds more tightly than unary operators on its\n' 'left; it binds less tightly than unary operators on its right. ' 'The\n' 'syntax is:\n' '\n' ' power ::= (await_expr | primary) ["**" u_expr]\n' '\n' 'Thus, in an unparenthesized sequence of power and unary operators, ' 'the\n' 'operators are evaluated from right to left (this does not ' 'constrain\n' 'the evaluation order for the operands): "-1**2" results in "-1".\n' '\n' 'The power operator has the same semantics as the built-in "pow()"\n' 'function, when called with two arguments: it yields its left ' 'argument\n' 'raised to the power of its right argument. The numeric arguments ' 'are\n' 'first converted to a common type, and the result is of that type.\n' '\n' 'For int operands, the result has the same type as the operands ' 'unless\n' 'the second argument is negative; in that case, all arguments are\n' 'converted to float and a float result is delivered. For example,\n' '"10**2" returns "100", but "10**-2" returns "0.01".\n' '\n' 'Raising "0.0" to a negative power results in a ' '"ZeroDivisionError".\n' 'Raising a negative number to a fractional power results in a ' '"complex"\n' 'number. (In earlier versions it raised a "ValueError".)\n', 'raise': 'The "raise" statement\n' '*********************\n' '\n' ' raise_stmt ::= "raise" [expression ["from" expression]]\n' '\n' 'If no expressions are present, "raise" re-raises the last ' 'exception\n' 'that was active in the current scope. If no exception is active ' 'in\n' 'the current scope, a "RuntimeError" exception is raised indicating\n' 'that this is an error.\n' '\n' 'Otherwise, "raise" evaluates the first expression as the exception\n' 'object. It must be either a subclass or an instance of\n' '"BaseException". If it is a class, the exception instance will be\n' 'obtained when needed by instantiating the class with no arguments.\n' '\n' 'The *type* of the exception is the exception instance’s class, the\n' '*value* is the instance itself.\n' '\n' 'A traceback object is normally created automatically when an ' 'exception\n' 'is raised and attached to it as the "__traceback__" attribute, ' 'which\n' 'is writable. You can create an exception and set your own traceback ' 'in\n' 'one step using the "with_traceback()" exception method (which ' 'returns\n' 'the same exception instance, with its traceback set to its ' 'argument),\n' 'like so:\n' '\n' ' raise Exception("foo occurred").with_traceback(tracebackobj)\n' '\n' 'The "from" clause is used for exception chaining: if given, the ' 'second\n' '*expression* must be another exception class or instance, which ' 'will\n' 'then be attached to the raised exception as the "__cause__" ' 'attribute\n' '(which is writable). If the raised exception is not handled, both\n' 'exceptions will be printed:\n' '\n' ' >>> try:\n' ' ... print(1 / 0)\n' ' ... except Exception as exc:\n' ' ... raise RuntimeError("Something bad happened") from exc\n' ' ...\n' ' Traceback (most recent call last):\n' ' File "<stdin>", line 2, in <module>\n' ' ZeroDivisionError: division by zero\n' '\n' ' The above exception was the direct cause of the following ' 'exception:\n' '\n' ' Traceback (most recent call last):\n' ' File "<stdin>", line 4, in <module>\n' ' RuntimeError: Something bad happened\n' '\n' 'A similar mechanism works implicitly if an exception is raised ' 'inside\n' 'an exception handler or a "finally" clause: the previous exception ' 'is\n' 'then attached as the new exception’s "__context__" attribute:\n' '\n' ' >>> try:\n' ' ... print(1 / 0)\n' ' ... except:\n' ' ... raise RuntimeError("Something bad happened")\n' ' ...\n' ' Traceback (most recent call last):\n' ' File "<stdin>", line 2, in <module>\n' ' ZeroDivisionError: division by zero\n' '\n' ' During handling of the above exception, another exception ' 'occurred:\n' '\n' ' Traceback (most recent call last):\n' ' File "<stdin>", line 4, in <module>\n' ' RuntimeError: Something bad happened\n' '\n' 'Exception chaining can be explicitly suppressed by specifying ' '"None"\n' 'in the "from" clause:\n' '\n' ' >>> try:\n' ' ... print(1 / 0)\n' ' ... except:\n' ' ... raise RuntimeError("Something bad happened") from None\n' ' ...\n' ' Traceback (most recent call last):\n' ' File "<stdin>", line 4, in <module>\n' ' RuntimeError: Something bad happened\n' '\n' 'Additional information on exceptions can be found in section\n' 'Exceptions, and information about handling exceptions is in ' 'section\n' 'The try statement.\n' '\n' 'Changed in version 3.3: "None" is now permitted as "Y" in "raise X\n' 'from Y".\n' '\n' 'New in version 3.3: The "__suppress_context__" attribute to ' 'suppress\n' 'automatic display of the exception context.\n', 'return': 'The "return" statement\n' '**********************\n' '\n' ' return_stmt ::= "return" [expression_list]\n' '\n' '"return" may only occur syntactically nested in a function ' 'definition,\n' 'not within a nested class definition.\n' '\n' 'If an expression list is present, it is evaluated, else "None" is\n' 'substituted.\n' '\n' '"return" leaves the current function call with the expression list ' '(or\n' '"None") as return value.\n' '\n' 'When "return" passes control out of a "try" statement with a ' '"finally"\n' 'clause, that "finally" clause is executed before really leaving ' 'the\n' 'function.\n' '\n' 'In a generator function, the "return" statement indicates that ' 'the\n' 'generator is done and will cause "StopIteration" to be raised. ' 'The\n' 'returned value (if any) is used as an argument to construct\n' '"StopIteration" and becomes the "StopIteration.value" attribute.\n' '\n' 'In an asynchronous generator function, an empty "return" ' 'statement\n' 'indicates that the asynchronous generator is done and will cause\n' '"StopAsyncIteration" to be raised. A non-empty "return" statement ' 'is\n' 'a syntax error in an asynchronous generator function.\n', 'sequence-types': 'Emulating container types\n' '*************************\n' '\n' 'The following methods can be defined to implement ' 'container objects.\n' 'Containers usually are sequences (such as lists or tuples) ' 'or mappings\n' '(like dictionaries), but can represent other containers as ' 'well. The\n' 'first set of methods is used either to emulate a sequence ' 'or to\n' 'emulate a mapping; the difference is that for a sequence, ' 'the\n' 'allowable keys should be the integers *k* for which "0 <= ' 'k < N" where\n' '*N* is the length of the sequence, or slice objects, which ' 'define a\n' 'range of items. It is also recommended that mappings ' 'provide the\n' 'methods "keys()", "values()", "items()", "get()", ' '"clear()",\n' '"setdefault()", "pop()", "popitem()", "copy()", and ' '"update()"\n' 'behaving similar to those for Python’s standard dictionary ' 'objects.\n' 'The "collections.abc" module provides a "MutableMapping" ' 'abstract base\n' 'class to help create those methods from a base set of ' '"__getitem__()",\n' '"__setitem__()", "__delitem__()", and "keys()". Mutable ' 'sequences\n' 'should provide methods "append()", "count()", "index()", ' '"extend()",\n' '"insert()", "pop()", "remove()", "reverse()" and "sort()", ' 'like Python\n' 'standard list objects. Finally, sequence types should ' 'implement\n' 'addition (meaning concatenation) and multiplication ' '(meaning\n' 'repetition) by defining the methods "__add__()", ' '"__radd__()",\n' '"__iadd__()", "__mul__()", "__rmul__()" and "__imul__()" ' 'described\n' 'below; they should not define other numerical operators. ' 'It is\n' 'recommended that both mappings and sequences implement ' 'the\n' '"__contains__()" method to allow efficient use of the "in" ' 'operator;\n' 'for mappings, "in" should search the mapping’s keys; for ' 'sequences, it\n' 'should search through the values. It is further ' 'recommended that both\n' 'mappings and sequences implement the "__iter__()" method ' 'to allow\n' 'efficient iteration through the container; for mappings, ' '"__iter__()"\n' 'should iterate through the object’s keys; for sequences, ' 'it should\n' 'iterate through the values.\n' '\n' 'object.__len__(self)\n' '\n' ' Called to implement the built-in function "len()". ' 'Should return\n' ' the length of the object, an integer ">=" 0. Also, an ' 'object that\n' ' doesn’t define a "__bool__()" method and whose ' '"__len__()" method\n' ' returns zero is considered to be false in a Boolean ' 'context.\n' '\n' ' **CPython implementation detail:** In CPython, the ' 'length is\n' ' required to be at most "sys.maxsize". If the length is ' 'larger than\n' ' "sys.maxsize" some features (such as "len()") may ' 'raise\n' ' "OverflowError". To prevent raising "OverflowError" by ' 'truth value\n' ' testing, an object must define a "__bool__()" method.\n' '\n' 'object.__length_hint__(self)\n' '\n' ' Called to implement "operator.length_hint()". Should ' 'return an\n' ' estimated length for the object (which may be greater ' 'or less than\n' ' the actual length). The length must be an integer ">=" ' '0. The\n' ' return value may also be "NotImplemented", which is ' 'treated the\n' ' same as if the "__length_hint__" method didn’t exist at ' 'all. This\n' ' method is purely an optimization and is never required ' 'for\n' ' correctness.\n' '\n' ' New in version 3.4.\n' '\n' 'Note:\n' '\n' ' Slicing is done exclusively with the following three ' 'methods. A\n' ' call like\n' '\n' ' a[1:2] = b\n' '\n' ' is translated to\n' '\n' ' a[slice(1, 2, None)] = b\n' '\n' ' and so forth. Missing slice items are always filled in ' 'with "None".\n' '\n' 'object.__getitem__(self, key)\n' '\n' ' Called to implement evaluation of "self[key]". For ' 'sequence types,\n' ' the accepted keys should be integers and slice ' 'objects. Note that\n' ' the special interpretation of negative indexes (if the ' 'class wishes\n' ' to emulate a sequence type) is up to the ' '"__getitem__()" method. If\n' ' *key* is of an inappropriate type, "TypeError" may be ' 'raised; if of\n' ' a value outside the set of indexes for the sequence ' '(after any\n' ' special interpretation of negative values), ' '"IndexError" should be\n' ' raised. For mapping types, if *key* is missing (not in ' 'the\n' ' container), "KeyError" should be raised.\n' '\n' ' Note:\n' '\n' ' "for" loops expect that an "IndexError" will be ' 'raised for\n' ' illegal indexes to allow proper detection of the end ' 'of the\n' ' sequence.\n' '\n' 'object.__setitem__(self, key, value)\n' '\n' ' Called to implement assignment to "self[key]". Same ' 'note as for\n' ' "__getitem__()". This should only be implemented for ' 'mappings if\n' ' the objects support changes to the values for keys, or ' 'if new keys\n' ' can be added, or for sequences if elements can be ' 'replaced. The\n' ' same exceptions should be raised for improper *key* ' 'values as for\n' ' the "__getitem__()" method.\n' '\n' 'object.__delitem__(self, key)\n' '\n' ' Called to implement deletion of "self[key]". Same note ' 'as for\n' ' "__getitem__()". This should only be implemented for ' 'mappings if\n' ' the objects support removal of keys, or for sequences ' 'if elements\n' ' can be removed from the sequence. The same exceptions ' 'should be\n' ' raised for improper *key* values as for the ' '"__getitem__()" method.\n' '\n' 'object.__missing__(self, key)\n' '\n' ' Called by "dict"."__getitem__()" to implement ' '"self[key]" for dict\n' ' subclasses when key is not in the dictionary.\n' '\n' 'object.__iter__(self)\n' '\n' ' This method is called when an iterator is required for ' 'a container.\n' ' This method should return a new iterator object that ' 'can iterate\n' ' over all the objects in the container. For mappings, ' 'it should\n' ' iterate over the keys of the container.\n' '\n' ' Iterator objects also need to implement this method; ' 'they are\n' ' required to return themselves. For more information on ' 'iterator\n' ' objects, see Iterator Types.\n' '\n' 'object.__reversed__(self)\n' '\n' ' Called (if present) by the "reversed()" built-in to ' 'implement\n' ' reverse iteration. It should return a new iterator ' 'object that\n' ' iterates over all the objects in the container in ' 'reverse order.\n' '\n' ' If the "__reversed__()" method is not provided, the ' '"reversed()"\n' ' built-in will fall back to using the sequence protocol ' '("__len__()"\n' ' and "__getitem__()"). Objects that support the ' 'sequence protocol\n' ' should only provide "__reversed__()" if they can ' 'provide an\n' ' implementation that is more efficient than the one ' 'provided by\n' ' "reversed()".\n' '\n' 'The membership test operators ("in" and "not in") are ' 'normally\n' 'implemented as an iteration through a container. However, ' 'container\n' 'objects can supply the following special method with a ' 'more efficient\n' 'implementation, which also does not require the object be ' 'iterable.\n' '\n' 'object.__contains__(self, item)\n' '\n' ' Called to implement membership test operators. Should ' 'return true\n' ' if *item* is in *self*, false otherwise. For mapping ' 'objects, this\n' ' should consider the keys of the mapping rather than the ' 'values or\n' ' the key-item pairs.\n' '\n' ' For objects that don’t define "__contains__()", the ' 'membership test\n' ' first tries iteration via "__iter__()", then the old ' 'sequence\n' ' iteration protocol via "__getitem__()", see this ' 'section in the\n' ' language reference.\n', 'shifting': 'Shifting operations\n' '*******************\n' '\n' 'The shifting operations have lower priority than the arithmetic\n' 'operations:\n' '\n' ' shift_expr ::= a_expr | shift_expr ("<<" | ">>") a_expr\n' '\n' 'These operators accept integers as arguments. They shift the ' 'first\n' 'argument to the left or right by the number of bits given by ' 'the\n' 'second argument.\n' '\n' 'A right shift by *n* bits is defined as floor division by ' '"pow(2,n)".\n' 'A left shift by *n* bits is defined as multiplication with ' '"pow(2,n)".\n', 'slicings': 'Slicings\n' '********\n' '\n' 'A slicing selects a range of items in a sequence object (e.g., ' 'a\n' 'string, tuple or list). Slicings may be used as expressions or ' 'as\n' 'targets in assignment or "del" statements. The syntax for a ' 'slicing:\n' '\n' ' slicing ::= primary "[" slice_list "]"\n' ' slice_list ::= slice_item ("," slice_item)* [","]\n' ' slice_item ::= expression | proper_slice\n' ' proper_slice ::= [lower_bound] ":" [upper_bound] [ ":" ' '[stride] ]\n' ' lower_bound ::= expression\n' ' upper_bound ::= expression\n' ' stride ::= expression\n' '\n' 'There is ambiguity in the formal syntax here: anything that ' 'looks like\n' 'an expression list also looks like a slice list, so any ' 'subscription\n' 'can be interpreted as a slicing. Rather than further ' 'complicating the\n' 'syntax, this is disambiguated by defining that in this case the\n' 'interpretation as a subscription takes priority over the\n' 'interpretation as a slicing (this is the case if the slice list\n' 'contains no proper slice).\n' '\n' 'The semantics for a slicing are as follows. The primary is ' 'indexed\n' '(using the same "__getitem__()" method as normal subscription) ' 'with a\n' 'key that is constructed from the slice list, as follows. If the ' 'slice\n' 'list contains at least one comma, the key is a tuple containing ' 'the\n' 'conversion of the slice items; otherwise, the conversion of the ' 'lone\n' 'slice item is the key. The conversion of a slice item that is ' 'an\n' 'expression is that expression. The conversion of a proper slice ' 'is a\n' 'slice object (see section The standard type hierarchy) whose ' '"start",\n' '"stop" and "step" attributes are the values of the expressions ' 'given\n' 'as lower bound, upper bound and stride, respectively, ' 'substituting\n' '"None" for missing expressions.\n', 'specialattrs': 'Special Attributes\n' '******************\n' '\n' 'The implementation adds a few special read-only attributes ' 'to several\n' 'object types, where they are relevant. Some of these are ' 'not reported\n' 'by the "dir()" built-in function.\n' '\n' 'object.__dict__\n' '\n' ' A dictionary or other mapping object used to store an ' 'object’s\n' ' (writable) attributes.\n' '\n' 'instance.__class__\n' '\n' ' The class to which a class instance belongs.\n' '\n' 'class.__bases__\n' '\n' ' The tuple of base classes of a class object.\n' '\n' 'definition.__name__\n' '\n' ' The name of the class, function, method, descriptor, or ' 'generator\n' ' instance.\n' '\n' 'definition.__qualname__\n' '\n' ' The *qualified name* of the class, function, method, ' 'descriptor, or\n' ' generator instance.\n' '\n' ' New in version 3.3.\n' '\n' 'class.__mro__\n' '\n' ' This attribute is a tuple of classes that are considered ' 'when\n' ' looking for base classes during method resolution.\n' '\n' 'class.mro()\n' '\n' ' This method can be overridden by a metaclass to customize ' 'the\n' ' method resolution order for its instances. It is called ' 'at class\n' ' instantiation, and its result is stored in "__mro__".\n' '\n' 'class.__subclasses__()\n' '\n' ' Each class keeps a list of weak references to its ' 'immediate\n' ' subclasses. This method returns a list of all those ' 'references\n' ' still alive. The list is in definition order. Example:\n' '\n' ' >>> int.__subclasses__()\n' " [<class 'bool'>]\n" '\n' '-[ Footnotes ]-\n' '\n' '[1] Additional information on these special methods may be ' 'found in\n' ' the Python Reference Manual (Basic customization).\n' '\n' '[2] As a consequence, the list "[1, 2]" is considered equal ' 'to "[1.0,\n' ' 2.0]", and similarly for tuples.\n' '\n' '[3] They must have since the parser can’t tell the type of ' 'the\n' ' operands.\n' '\n' '[4] Cased characters are those with general category ' 'property being\n' ' one of “Lu” (Letter, uppercase), “Ll” (Letter, ' 'lowercase), or “Lt”\n' ' (Letter, titlecase).\n' '\n' '[5] To format only a tuple you should therefore provide a ' 'singleton\n' ' tuple whose only element is the tuple to be formatted.\n', 'specialnames': 'Special method names\n' '********************\n' '\n' 'A class can implement certain operations that are invoked by ' 'special\n' 'syntax (such as arithmetic operations or subscripting and ' 'slicing) by\n' 'defining methods with special names. This is Python’s ' 'approach to\n' '*operator overloading*, allowing classes to define their own ' 'behavior\n' 'with respect to language operators. For instance, if a ' 'class defines\n' 'a method named "__getitem__()", and "x" is an instance of ' 'this class,\n' 'then "x[i]" is roughly equivalent to "type(x).__getitem__(x, ' 'i)".\n' 'Except where mentioned, attempts to execute an operation ' 'raise an\n' 'exception when no appropriate method is defined (typically\n' '"AttributeError" or "TypeError").\n' '\n' 'Setting a special method to "None" indicates that the ' 'corresponding\n' 'operation is not available. For example, if a class sets ' '"__iter__()"\n' 'to "None", the class is not iterable, so calling "iter()" on ' 'its\n' 'instances will raise a "TypeError" (without falling back to\n' '"__getitem__()"). [2]\n' '\n' 'When implementing a class that emulates any built-in type, ' 'it is\n' 'important that the emulation only be implemented to the ' 'degree that it\n' 'makes sense for the object being modelled. For example, ' 'some\n' 'sequences may work well with retrieval of individual ' 'elements, but\n' 'extracting a slice may not make sense. (One example of this ' 'is the\n' '"NodeList" interface in the W3C’s Document Object Model.)\n' '\n' '\n' 'Basic customization\n' '===================\n' '\n' 'object.__new__(cls[, ...])\n' '\n' ' Called to create a new instance of class *cls*. ' '"__new__()" is a\n' ' static method (special-cased so you need not declare it ' 'as such)\n' ' that takes the class of which an instance was requested ' 'as its\n' ' first argument. The remaining arguments are those passed ' 'to the\n' ' object constructor expression (the call to the class). ' 'The return\n' ' value of "__new__()" should be the new object instance ' '(usually an\n' ' instance of *cls*).\n' '\n' ' Typical implementations create a new instance of the ' 'class by\n' ' invoking the superclass’s "__new__()" method using\n' ' "super().__new__(cls[, ...])" with appropriate arguments ' 'and then\n' ' modifying the newly-created instance as necessary before ' 'returning\n' ' it.\n' '\n' ' If "__new__()" is invoked during object construction and ' 'it returns\n' ' an instance or subclass of *cls*, then the new ' 'instance’s\n' ' "__init__()" method will be invoked like "__init__(self[, ' '...])",\n' ' where *self* is the new instance and the remaining ' 'arguments are\n' ' the same as were passed to the object constructor.\n' '\n' ' If "__new__()" does not return an instance of *cls*, then ' 'the new\n' ' instance’s "__init__()" method will not be invoked.\n' '\n' ' "__new__()" is intended mainly to allow subclasses of ' 'immutable\n' ' types (like int, str, or tuple) to customize instance ' 'creation. It\n' ' is also commonly overridden in custom metaclasses in ' 'order to\n' ' customize class creation.\n' '\n' 'object.__init__(self[, ...])\n' '\n' ' Called after the instance has been created (by ' '"__new__()"), but\n' ' before it is returned to the caller. The arguments are ' 'those\n' ' passed to the class constructor expression. If a base ' 'class has an\n' ' "__init__()" method, the derived class’s "__init__()" ' 'method, if\n' ' any, must explicitly call it to ensure proper ' 'initialization of the\n' ' base class part of the instance; for example:\n' ' "super().__init__([args...])".\n' '\n' ' Because "__new__()" and "__init__()" work together in ' 'constructing\n' ' objects ("__new__()" to create it, and "__init__()" to ' 'customize\n' ' it), no non-"None" value may be returned by "__init__()"; ' 'doing so\n' ' will cause a "TypeError" to be raised at runtime.\n' '\n' 'object.__del__(self)\n' '\n' ' Called when the instance is about to be destroyed. This ' 'is also\n' ' called a finalizer or (improperly) a destructor. If a ' 'base class\n' ' has a "__del__()" method, the derived class’s "__del__()" ' 'method,\n' ' if any, must explicitly call it to ensure proper deletion ' 'of the\n' ' base class part of the instance.\n' '\n' ' It is possible (though not recommended!) for the ' '"__del__()" method\n' ' to postpone destruction of the instance by creating a new ' 'reference\n' ' to it. This is called object *resurrection*. It is\n' ' implementation-dependent whether "__del__()" is called a ' 'second\n' ' time when a resurrected object is about to be destroyed; ' 'the\n' ' current *CPython* implementation only calls it once.\n' '\n' ' It is not guaranteed that "__del__()" methods are called ' 'for\n' ' objects that still exist when the interpreter exits.\n' '\n' ' Note:\n' '\n' ' "del x" doesn’t directly call "x.__del__()" — the ' 'former\n' ' decrements the reference count for "x" by one, and the ' 'latter is\n' ' only called when "x"’s reference count reaches zero.\n' '\n' ' **CPython implementation detail:** It is possible for a ' 'reference\n' ' cycle to prevent the reference count of an object from ' 'going to\n' ' zero. In this case, the cycle will be later detected and ' 'deleted\n' ' by the *cyclic garbage collector*. A common cause of ' 'reference\n' ' cycles is when an exception has been caught in a local ' 'variable.\n' ' The frame’s locals then reference the exception, which ' 'references\n' ' its own traceback, which references the locals of all ' 'frames caught\n' ' in the traceback.\n' '\n' ' See also: Documentation for the "gc" module.\n' '\n' ' Warning:\n' '\n' ' Due to the precarious circumstances under which ' '"__del__()"\n' ' methods are invoked, exceptions that occur during their ' 'execution\n' ' are ignored, and a warning is printed to "sys.stderr" ' 'instead.\n' ' In particular:\n' '\n' ' * "__del__()" can be invoked when arbitrary code is ' 'being\n' ' executed, including from any arbitrary thread. If ' '"__del__()"\n' ' needs to take a lock or invoke any other blocking ' 'resource, it\n' ' may deadlock as the resource may already be taken by ' 'the code\n' ' that gets interrupted to execute "__del__()".\n' '\n' ' * "__del__()" can be executed during interpreter ' 'shutdown. As a\n' ' consequence, the global variables it needs to access ' '(including\n' ' other modules) may already have been deleted or set ' 'to "None".\n' ' Python guarantees that globals whose name begins with ' 'a single\n' ' underscore are deleted from their module before other ' 'globals\n' ' are deleted; if no other references to such globals ' 'exist, this\n' ' may help in assuring that imported modules are still ' 'available\n' ' at the time when the "__del__()" method is called.\n' '\n' 'object.__repr__(self)\n' '\n' ' Called by the "repr()" built-in function to compute the ' '“official”\n' ' string representation of an object. If at all possible, ' 'this\n' ' should look like a valid Python expression that could be ' 'used to\n' ' recreate an object with the same value (given an ' 'appropriate\n' ' environment). If this is not possible, a string of the ' 'form\n' ' "<...some useful description...>" should be returned. The ' 'return\n' ' value must be a string object. If a class defines ' '"__repr__()" but\n' ' not "__str__()", then "__repr__()" is also used when an ' '“informal”\n' ' string representation of instances of that class is ' 'required.\n' '\n' ' This is typically used for debugging, so it is important ' 'that the\n' ' representation is information-rich and unambiguous.\n' '\n' 'object.__str__(self)\n' '\n' ' Called by "str(object)" and the built-in functions ' '"format()" and\n' ' "print()" to compute the “informal” or nicely printable ' 'string\n' ' representation of an object. The return value must be a ' 'string\n' ' object.\n' '\n' ' This method differs from "object.__repr__()" in that ' 'there is no\n' ' expectation that "__str__()" return a valid Python ' 'expression: a\n' ' more convenient or concise representation can be used.\n' '\n' ' The default implementation defined by the built-in type ' '"object"\n' ' calls "object.__repr__()".\n' '\n' 'object.__bytes__(self)\n' '\n' ' Called by bytes to compute a byte-string representation ' 'of an\n' ' object. This should return a "bytes" object.\n' '\n' 'object.__format__(self, format_spec)\n' '\n' ' Called by the "format()" built-in function, and by ' 'extension,\n' ' evaluation of formatted string literals and the ' '"str.format()"\n' ' method, to produce a “formatted” string representation of ' 'an\n' ' object. The *format_spec* argument is a string that ' 'contains a\n' ' description of the formatting options desired. The ' 'interpretation\n' ' of the *format_spec* argument is up to the type ' 'implementing\n' ' "__format__()", however most classes will either ' 'delegate\n' ' formatting to one of the built-in types, or use a ' 'similar\n' ' formatting option syntax.\n' '\n' ' See Format Specification Mini-Language for a description ' 'of the\n' ' standard formatting syntax.\n' '\n' ' The return value must be a string object.\n' '\n' ' Changed in version 3.4: The __format__ method of "object" ' 'itself\n' ' raises a "TypeError" if passed any non-empty string.\n' '\n' ' Changed in version 3.7: "object.__format__(x, \'\')" is ' 'now\n' ' equivalent to "str(x)" rather than "format(str(x), ' '\'\')".\n' '\n' 'object.__lt__(self, other)\n' 'object.__le__(self, other)\n' 'object.__eq__(self, other)\n' 'object.__ne__(self, other)\n' 'object.__gt__(self, other)\n' 'object.__ge__(self, other)\n' '\n' ' These are the so-called “rich comparison” methods. The\n' ' correspondence between operator symbols and method names ' 'is as\n' ' follows: "x<y" calls "x.__lt__(y)", "x<=y" calls ' '"x.__le__(y)",\n' ' "x==y" calls "x.__eq__(y)", "x!=y" calls "x.__ne__(y)", ' '"x>y" calls\n' ' "x.__gt__(y)", and "x>=y" calls "x.__ge__(y)".\n' '\n' ' A rich comparison method may return the singleton ' '"NotImplemented"\n' ' if it does not implement the operation for a given pair ' 'of\n' ' arguments. By convention, "False" and "True" are returned ' 'for a\n' ' successful comparison. However, these methods can return ' 'any value,\n' ' so if the comparison operator is used in a Boolean ' 'context (e.g.,\n' ' in the condition of an "if" statement), Python will call ' '"bool()"\n' ' on the value to determine if the result is true or ' 'false.\n' '\n' ' By default, "object" implements "__eq__()" by using "is", ' 'returning\n' ' "NotImplemented" in the case of a false comparison: "True ' 'if x is y\n' ' else NotImplemented". For "__ne__()", by default it ' 'delegates to\n' ' "__eq__()" and inverts the result unless it is ' '"NotImplemented".\n' ' There are no other implied relationships among the ' 'comparison\n' ' operators or default implementations; for example, the ' 'truth of\n' ' "(x<y or x==y)" does not imply "x<=y". To automatically ' 'generate\n' ' ordering operations from a single root operation, see\n' ' "functools.total_ordering()".\n' '\n' ' See the paragraph on "__hash__()" for some important ' 'notes on\n' ' creating *hashable* objects which support custom ' 'comparison\n' ' operations and are usable as dictionary keys.\n' '\n' ' There are no swapped-argument versions of these methods ' '(to be used\n' ' when the left argument does not support the operation but ' 'the right\n' ' argument does); rather, "__lt__()" and "__gt__()" are ' 'each other’s\n' ' reflection, "__le__()" and "__ge__()" are each other’s ' 'reflection,\n' ' and "__eq__()" and "__ne__()" are their own reflection. ' 'If the\n' ' operands are of different types, and right operand’s type ' 'is a\n' ' direct or indirect subclass of the left operand’s type, ' 'the\n' ' reflected method of the right operand has priority, ' 'otherwise the\n' ' left operand’s method has priority. Virtual subclassing ' 'is not\n' ' considered.\n' '\n' 'object.__hash__(self)\n' '\n' ' Called by built-in function "hash()" and for operations ' 'on members\n' ' of hashed collections including "set", "frozenset", and ' '"dict".\n' ' "__hash__()" should return an integer. The only required ' 'property\n' ' is that objects which compare equal have the same hash ' 'value; it is\n' ' advised to mix together the hash values of the components ' 'of the\n' ' object that also play a part in comparison of objects by ' 'packing\n' ' them into a tuple and hashing the tuple. Example:\n' '\n' ' def __hash__(self):\n' ' return hash((self.name, self.nick, self.color))\n' '\n' ' Note:\n' '\n' ' "hash()" truncates the value returned from an object’s ' 'custom\n' ' "__hash__()" method to the size of a "Py_ssize_t". ' 'This is\n' ' typically 8 bytes on 64-bit builds and 4 bytes on ' '32-bit builds.\n' ' If an object’s "__hash__()" must interoperate on ' 'builds of\n' ' different bit sizes, be sure to check the width on all ' 'supported\n' ' builds. An easy way to do this is with "python -c ' '"import sys;\n' ' print(sys.hash_info.width)"".\n' '\n' ' If a class does not define an "__eq__()" method it should ' 'not\n' ' define a "__hash__()" operation either; if it defines ' '"__eq__()"\n' ' but not "__hash__()", its instances will not be usable as ' 'items in\n' ' hashable collections. If a class defines mutable objects ' 'and\n' ' implements an "__eq__()" method, it should not implement\n' ' "__hash__()", since the implementation of hashable ' 'collections\n' ' requires that a key’s hash value is immutable (if the ' 'object’s hash\n' ' value changes, it will be in the wrong hash bucket).\n' '\n' ' User-defined classes have "__eq__()" and "__hash__()" ' 'methods by\n' ' default; with them, all objects compare unequal (except ' 'with\n' ' themselves) and "x.__hash__()" returns an appropriate ' 'value such\n' ' that "x == y" implies both that "x is y" and "hash(x) == ' 'hash(y)".\n' '\n' ' A class that overrides "__eq__()" and does not define ' '"__hash__()"\n' ' will have its "__hash__()" implicitly set to "None". ' 'When the\n' ' "__hash__()" method of a class is "None", instances of ' 'the class\n' ' will raise an appropriate "TypeError" when a program ' 'attempts to\n' ' retrieve their hash value, and will also be correctly ' 'identified as\n' ' unhashable when checking "isinstance(obj,\n' ' collections.abc.Hashable)".\n' '\n' ' If a class that overrides "__eq__()" needs to retain the\n' ' implementation of "__hash__()" from a parent class, the ' 'interpreter\n' ' must be told this explicitly by setting "__hash__ =\n' ' <ParentClass>.__hash__".\n' '\n' ' If a class that does not override "__eq__()" wishes to ' 'suppress\n' ' hash support, it should include "__hash__ = None" in the ' 'class\n' ' definition. A class which defines its own "__hash__()" ' 'that\n' ' explicitly raises a "TypeError" would be incorrectly ' 'identified as\n' ' hashable by an "isinstance(obj, ' 'collections.abc.Hashable)" call.\n' '\n' ' Note:\n' '\n' ' By default, the "__hash__()" values of str and bytes ' 'objects are\n' ' “salted” with an unpredictable random value. Although ' 'they\n' ' remain constant within an individual Python process, ' 'they are not\n' ' predictable between repeated invocations of Python.This ' 'is\n' ' intended to provide protection against a ' 'denial-of-service caused\n' ' by carefully-chosen inputs that exploit the worst case\n' ' performance of a dict insertion, O(n^2) complexity. ' 'See\n' ' http://www.ocert.org/advisories/ocert-2011-003.html ' 'for\n' ' details.Changing hash values affects the iteration ' 'order of sets.\n' ' Python has never made guarantees about this ordering ' '(and it\n' ' typically varies between 32-bit and 64-bit builds).See ' 'also\n' ' "PYTHONHASHSEED".\n' '\n' ' Changed in version 3.3: Hash randomization is enabled by ' 'default.\n' '\n' 'object.__bool__(self)\n' '\n' ' Called to implement truth value testing and the built-in ' 'operation\n' ' "bool()"; should return "False" or "True". When this ' 'method is not\n' ' defined, "__len__()" is called, if it is defined, and the ' 'object is\n' ' considered true if its result is nonzero. If a class ' 'defines\n' ' neither "__len__()" nor "__bool__()", all its instances ' 'are\n' ' considered true.\n' '\n' '\n' 'Customizing attribute access\n' '============================\n' '\n' 'The following methods can be defined to customize the ' 'meaning of\n' 'attribute access (use of, assignment to, or deletion of ' '"x.name") for\n' 'class instances.\n' '\n' 'object.__getattr__(self, name)\n' '\n' ' Called when the default attribute access fails with an\n' ' "AttributeError" (either "__getattribute__()" raises an\n' ' "AttributeError" because *name* is not an instance ' 'attribute or an\n' ' attribute in the class tree for "self"; or "__get__()" of ' 'a *name*\n' ' property raises "AttributeError"). This method should ' 'either\n' ' return the (computed) attribute value or raise an ' '"AttributeError"\n' ' exception.\n' '\n' ' Note that if the attribute is found through the normal ' 'mechanism,\n' ' "__getattr__()" is not called. (This is an intentional ' 'asymmetry\n' ' between "__getattr__()" and "__setattr__()".) This is ' 'done both for\n' ' efficiency reasons and because otherwise "__getattr__()" ' 'would have\n' ' no way to access other attributes of the instance. Note ' 'that at\n' ' least for instance variables, you can fake total control ' 'by not\n' ' inserting any values in the instance attribute dictionary ' '(but\n' ' instead inserting them in another object). See the\n' ' "__getattribute__()" method below for a way to actually ' 'get total\n' ' control over attribute access.\n' '\n' 'object.__getattribute__(self, name)\n' '\n' ' Called unconditionally to implement attribute accesses ' 'for\n' ' instances of the class. If the class also defines ' '"__getattr__()",\n' ' the latter will not be called unless "__getattribute__()" ' 'either\n' ' calls it explicitly or raises an "AttributeError". This ' 'method\n' ' should return the (computed) attribute value or raise an\n' ' "AttributeError" exception. In order to avoid infinite ' 'recursion in\n' ' this method, its implementation should always call the ' 'base class\n' ' method with the same name to access any attributes it ' 'needs, for\n' ' example, "object.__getattribute__(self, name)".\n' '\n' ' Note:\n' '\n' ' This method may still be bypassed when looking up ' 'special methods\n' ' as the result of implicit invocation via language ' 'syntax or\n' ' built-in functions. See Special method lookup.\n' '\n' ' For certain sensitive attribute accesses, raises an ' 'auditing event\n' ' "object.__getattr__" with arguments "obj" and "name".\n' '\n' 'object.__setattr__(self, name, value)\n' '\n' ' Called when an attribute assignment is attempted. This ' 'is called\n' ' instead of the normal mechanism (i.e. store the value in ' 'the\n' ' instance dictionary). *name* is the attribute name, ' '*value* is the\n' ' value to be assigned to it.\n' '\n' ' If "__setattr__()" wants to assign to an instance ' 'attribute, it\n' ' should call the base class method with the same name, for ' 'example,\n' ' "object.__setattr__(self, name, value)".\n' '\n' ' For certain sensitive attribute assignments, raises an ' 'auditing\n' ' event "object.__setattr__" with arguments "obj", "name", ' '"value".\n' '\n' 'object.__delattr__(self, name)\n' '\n' ' Like "__setattr__()" but for attribute deletion instead ' 'of\n' ' assignment. This should only be implemented if "del ' 'obj.name" is\n' ' meaningful for the object.\n' '\n' ' For certain sensitive attribute deletions, raises an ' 'auditing event\n' ' "object.__delattr__" with arguments "obj" and "name".\n' '\n' 'object.__dir__(self)\n' '\n' ' Called when "dir()" is called on the object. A sequence ' 'must be\n' ' returned. "dir()" converts the returned sequence to a ' 'list and\n' ' sorts it.\n' '\n' '\n' 'Customizing module attribute access\n' '-----------------------------------\n' '\n' 'Special names "__getattr__" and "__dir__" can be also used ' 'to\n' 'customize access to module attributes. The "__getattr__" ' 'function at\n' 'the module level should accept one argument which is the ' 'name of an\n' 'attribute and return the computed value or raise an ' '"AttributeError".\n' 'If an attribute is not found on a module object through the ' 'normal\n' 'lookup, i.e. "object.__getattribute__()", then "__getattr__" ' 'is\n' 'searched in the module "__dict__" before raising an ' '"AttributeError".\n' 'If found, it is called with the attribute name and the ' 'result is\n' 'returned.\n' '\n' 'The "__dir__" function should accept no arguments, and ' 'return a\n' 'sequence of strings that represents the names accessible on ' 'module. If\n' 'present, this function overrides the standard "dir()" search ' 'on a\n' 'module.\n' '\n' 'For a more fine grained customization of the module behavior ' '(setting\n' 'attributes, properties, etc.), one can set the "__class__" ' 'attribute\n' 'of a module object to a subclass of "types.ModuleType". For ' 'example:\n' '\n' ' import sys\n' ' from types import ModuleType\n' '\n' ' class VerboseModule(ModuleType):\n' ' def __repr__(self):\n' " return f'Verbose {self.__name__}'\n" '\n' ' def __setattr__(self, attr, value):\n' " print(f'Setting {attr}...')\n" ' super().__setattr__(attr, value)\n' '\n' ' sys.modules[__name__].__class__ = VerboseModule\n' '\n' 'Note:\n' '\n' ' Defining module "__getattr__" and setting module ' '"__class__" only\n' ' affect lookups made using the attribute access syntax – ' 'directly\n' ' accessing the module globals (whether by code within the ' 'module, or\n' ' via a reference to the module’s globals dictionary) is ' 'unaffected.\n' '\n' 'Changed in version 3.5: "__class__" module attribute is now ' 'writable.\n' '\n' 'New in version 3.7: "__getattr__" and "__dir__" module ' 'attributes.\n' '\n' 'See also:\n' '\n' ' **PEP 562** - Module __getattr__ and __dir__\n' ' Describes the "__getattr__" and "__dir__" functions on ' 'modules.\n' '\n' '\n' 'Implementing Descriptors\n' '------------------------\n' '\n' 'The following methods only apply when an instance of the ' 'class\n' 'containing the method (a so-called *descriptor* class) ' 'appears in an\n' '*owner* class (the descriptor must be in either the owner’s ' 'class\n' 'dictionary or in the class dictionary for one of its ' 'parents). In the\n' 'examples below, “the attribute” refers to the attribute ' 'whose name is\n' 'the key of the property in the owner class’ "__dict__".\n' '\n' 'object.__get__(self, instance, owner=None)\n' '\n' ' Called to get the attribute of the owner class (class ' 'attribute\n' ' access) or of an instance of that class (instance ' 'attribute\n' ' access). The optional *owner* argument is the owner ' 'class, while\n' ' *instance* is the instance that the attribute was ' 'accessed through,\n' ' or "None" when the attribute is accessed through the ' '*owner*.\n' '\n' ' This method should return the computed attribute value or ' 'raise an\n' ' "AttributeError" exception.\n' '\n' ' **PEP 252** specifies that "__get__()" is callable with ' 'one or two\n' ' arguments. Python’s own built-in descriptors support ' 'this\n' ' specification; however, it is likely that some ' 'third-party tools\n' ' have descriptors that require both arguments. Python’s ' 'own\n' ' "__getattribute__()" implementation always passes in both ' 'arguments\n' ' whether they are required or not.\n' '\n' 'object.__set__(self, instance, value)\n' '\n' ' Called to set the attribute on an instance *instance* of ' 'the owner\n' ' class to a new value, *value*.\n' '\n' ' Note, adding "__set__()" or "__delete__()" changes the ' 'kind of\n' ' descriptor to a “data descriptor”. See Invoking ' 'Descriptors for\n' ' more details.\n' '\n' 'object.__delete__(self, instance)\n' '\n' ' Called to delete the attribute on an instance *instance* ' 'of the\n' ' owner class.\n' '\n' 'object.__set_name__(self, owner, name)\n' '\n' ' Called at the time the owning class *owner* is created. ' 'The\n' ' descriptor has been assigned to *name*.\n' '\n' ' Note:\n' '\n' ' "__set_name__()" is only called implicitly as part of ' 'the "type"\n' ' constructor, so it will need to be called explicitly ' 'with the\n' ' appropriate parameters when a descriptor is added to a ' 'class\n' ' after initial creation:\n' '\n' ' class A:\n' ' pass\n' ' descr = custom_descriptor()\n' ' A.attr = descr\n' " descr.__set_name__(A, 'attr')\n" '\n' ' See Creating the class object for more details.\n' '\n' ' New in version 3.6.\n' '\n' 'The attribute "__objclass__" is interpreted by the "inspect" ' 'module as\n' 'specifying the class where this object was defined (setting ' 'this\n' 'appropriately can assist in runtime introspection of dynamic ' 'class\n' 'attributes). For callables, it may indicate that an instance ' 'of the\n' 'given type (or a subclass) is expected or required as the ' 'first\n' 'positional argument (for example, CPython sets this ' 'attribute for\n' 'unbound methods that are implemented in C).\n' '\n' '\n' 'Invoking Descriptors\n' '--------------------\n' '\n' 'In general, a descriptor is an object attribute with ' '“binding\n' 'behavior”, one whose attribute access has been overridden by ' 'methods\n' 'in the descriptor protocol: "__get__()", "__set__()", and\n' '"__delete__()". If any of those methods are defined for an ' 'object, it\n' 'is said to be a descriptor.\n' '\n' 'The default behavior for attribute access is to get, set, or ' 'delete\n' 'the attribute from an object’s dictionary. For instance, ' '"a.x" has a\n' 'lookup chain starting with "a.__dict__[\'x\']", then\n' '"type(a).__dict__[\'x\']", and continuing through the base ' 'classes of\n' '"type(a)" excluding metaclasses.\n' '\n' 'However, if the looked-up value is an object defining one of ' 'the\n' 'descriptor methods, then Python may override the default ' 'behavior and\n' 'invoke the descriptor method instead. Where this occurs in ' 'the\n' 'precedence chain depends on which descriptor methods were ' 'defined and\n' 'how they were called.\n' '\n' 'The starting point for descriptor invocation is a binding, ' '"a.x". How\n' 'the arguments are assembled depends on "a":\n' '\n' 'Direct Call\n' ' The simplest and least common call is when user code ' 'directly\n' ' invokes a descriptor method: "x.__get__(a)".\n' '\n' 'Instance Binding\n' ' If binding to an object instance, "a.x" is transformed ' 'into the\n' ' call: "type(a).__dict__[\'x\'].__get__(a, type(a))".\n' '\n' 'Class Binding\n' ' If binding to a class, "A.x" is transformed into the ' 'call:\n' ' "A.__dict__[\'x\'].__get__(None, A)".\n' '\n' 'Super Binding\n' ' If "a" is an instance of "super", then the binding ' '"super(B,\n' ' obj).m()" searches "obj.__class__.__mro__" for the base ' 'class "A"\n' ' immediately preceding "B" and then invokes the descriptor ' 'with the\n' ' call: "A.__dict__[\'m\'].__get__(obj, obj.__class__)".\n' '\n' 'For instance bindings, the precedence of descriptor ' 'invocation depends\n' 'on the which descriptor methods are defined. A descriptor ' 'can define\n' 'any combination of "__get__()", "__set__()" and ' '"__delete__()". If it\n' 'does not define "__get__()", then accessing the attribute ' 'will return\n' 'the descriptor object itself unless there is a value in the ' 'object’s\n' 'instance dictionary. If the descriptor defines "__set__()" ' 'and/or\n' '"__delete__()", it is a data descriptor; if it defines ' 'neither, it is\n' 'a non-data descriptor. Normally, data descriptors define ' 'both\n' '"__get__()" and "__set__()", while non-data descriptors have ' 'just the\n' '"__get__()" method. Data descriptors with "__get__()" and ' '"__set__()"\n' '(and/or "__delete__()") defined always override a ' 'redefinition in an\n' 'instance dictionary. In contrast, non-data descriptors can ' 'be\n' 'overridden by instances.\n' '\n' 'Python methods (including "staticmethod()" and ' '"classmethod()") are\n' 'implemented as non-data descriptors. Accordingly, instances ' 'can\n' 'redefine and override methods. This allows individual ' 'instances to\n' 'acquire behaviors that differ from other instances of the ' 'same class.\n' '\n' 'The "property()" function is implemented as a data ' 'descriptor.\n' 'Accordingly, instances cannot override the behavior of a ' 'property.\n' '\n' '\n' '__slots__\n' '---------\n' '\n' '*__slots__* allow us to explicitly declare data members ' '(like\n' 'properties) and deny the creation of *__dict__* and ' '*__weakref__*\n' '(unless explicitly declared in *__slots__* or available in a ' 'parent.)\n' '\n' 'The space saved over using *__dict__* can be significant. ' 'Attribute\n' 'lookup speed can be significantly improved as well.\n' '\n' 'object.__slots__\n' '\n' ' This class variable can be assigned a string, iterable, ' 'or sequence\n' ' of strings with variable names used by instances. ' '*__slots__*\n' ' reserves space for the declared variables and prevents ' 'the\n' ' automatic creation of *__dict__* and *__weakref__* for ' 'each\n' ' instance.\n' '\n' '\n' 'Notes on using *__slots__*\n' '~~~~~~~~~~~~~~~~~~~~~~~~~~\n' '\n' '* When inheriting from a class without *__slots__*, the ' '*__dict__* and\n' ' *__weakref__* attribute of the instances will always be ' 'accessible.\n' '\n' '* Without a *__dict__* variable, instances cannot be ' 'assigned new\n' ' variables not listed in the *__slots__* definition. ' 'Attempts to\n' ' assign to an unlisted variable name raises ' '"AttributeError". If\n' ' dynamic assignment of new variables is desired, then add\n' ' "\'__dict__\'" to the sequence of strings in the ' '*__slots__*\n' ' declaration.\n' '\n' '* Without a *__weakref__* variable for each instance, ' 'classes defining\n' ' *__slots__* do not support weak references to its ' 'instances. If weak\n' ' reference support is needed, then add "\'__weakref__\'" to ' 'the\n' ' sequence of strings in the *__slots__* declaration.\n' '\n' '* *__slots__* are implemented at the class level by ' 'creating\n' ' descriptors (Implementing Descriptors) for each variable ' 'name. As a\n' ' result, class attributes cannot be used to set default ' 'values for\n' ' instance variables defined by *__slots__*; otherwise, the ' 'class\n' ' attribute would overwrite the descriptor assignment.\n' '\n' '* The action of a *__slots__* declaration is not limited to ' 'the class\n' ' where it is defined. *__slots__* declared in parents are ' 'available\n' ' in child classes. However, child subclasses will get a ' '*__dict__*\n' ' and *__weakref__* unless they also define *__slots__* ' '(which should\n' ' only contain names of any *additional* slots).\n' '\n' '* If a class defines a slot also defined in a base class, ' 'the instance\n' ' variable defined by the base class slot is inaccessible ' '(except by\n' ' retrieving its descriptor directly from the base class). ' 'This\n' ' renders the meaning of the program undefined. In the ' 'future, a\n' ' check may be added to prevent this.\n' '\n' '* Nonempty *__slots__* does not work for classes derived ' 'from\n' ' “variable-length” built-in types such as "int", "bytes" ' 'and "tuple".\n' '\n' '* Any non-string iterable may be assigned to *__slots__*. ' 'Mappings may\n' ' also be used; however, in the future, special meaning may ' 'be\n' ' assigned to the values corresponding to each key.\n' '\n' '* *__class__* assignment works only if both classes have the ' 'same\n' ' *__slots__*.\n' '\n' '* Multiple inheritance with multiple slotted parent classes ' 'can be\n' ' used, but only one parent is allowed to have attributes ' 'created by\n' ' slots (the other bases must have empty slot layouts) - ' 'violations\n' ' raise "TypeError".\n' '\n' '* If an iterator is used for *__slots__* then a descriptor ' 'is created\n' ' for each of the iterator’s values. However, the ' '*__slots__*\n' ' attribute will be an empty iterator.\n' '\n' '\n' 'Customizing class creation\n' '==========================\n' '\n' 'Whenever a class inherits from another class, ' '*__init_subclass__* is\n' 'called on that class. This way, it is possible to write ' 'classes which\n' 'change the behavior of subclasses. This is closely related ' 'to class\n' 'decorators, but where class decorators only affect the ' 'specific class\n' 'they’re applied to, "__init_subclass__" solely applies to ' 'future\n' 'subclasses of the class defining the method.\n' '\n' 'classmethod object.__init_subclass__(cls)\n' '\n' ' This method is called whenever the containing class is ' 'subclassed.\n' ' *cls* is then the new subclass. If defined as a normal ' 'instance\n' ' method, this method is implicitly converted to a class ' 'method.\n' '\n' ' Keyword arguments which are given to a new class are ' 'passed to the\n' ' parent’s class "__init_subclass__". For compatibility ' 'with other\n' ' classes using "__init_subclass__", one should take out ' 'the needed\n' ' keyword arguments and pass the others over to the base ' 'class, as\n' ' in:\n' '\n' ' class Philosopher:\n' ' def __init_subclass__(cls, /, default_name, ' '**kwargs):\n' ' super().__init_subclass__(**kwargs)\n' ' cls.default_name = default_name\n' '\n' ' class AustralianPhilosopher(Philosopher, ' 'default_name="Bruce"):\n' ' pass\n' '\n' ' The default implementation "object.__init_subclass__" ' 'does nothing,\n' ' but raises an error if it is called with any arguments.\n' '\n' ' Note:\n' '\n' ' The metaclass hint "metaclass" is consumed by the rest ' 'of the\n' ' type machinery, and is never passed to ' '"__init_subclass__"\n' ' implementations. The actual metaclass (rather than the ' 'explicit\n' ' hint) can be accessed as "type(cls)".\n' '\n' ' New in version 3.6.\n' '\n' '\n' 'Metaclasses\n' '-----------\n' '\n' 'By default, classes are constructed using "type()". The ' 'class body is\n' 'executed in a new namespace and the class name is bound ' 'locally to the\n' 'result of "type(name, bases, namespace)".\n' '\n' 'The class creation process can be customized by passing the\n' '"metaclass" keyword argument in the class definition line, ' 'or by\n' 'inheriting from an existing class that included such an ' 'argument. In\n' 'the following example, both "MyClass" and "MySubclass" are ' 'instances\n' 'of "Meta":\n' '\n' ' class Meta(type):\n' ' pass\n' '\n' ' class MyClass(metaclass=Meta):\n' ' pass\n' '\n' ' class MySubclass(MyClass):\n' ' pass\n' '\n' 'Any other keyword arguments that are specified in the class ' 'definition\n' 'are passed through to all metaclass operations described ' 'below.\n' '\n' 'When a class definition is executed, the following steps ' 'occur:\n' '\n' '* MRO entries are resolved;\n' '\n' '* the appropriate metaclass is determined;\n' '\n' '* the class namespace is prepared;\n' '\n' '* the class body is executed;\n' '\n' '* the class object is created.\n' '\n' '\n' 'Resolving MRO entries\n' '---------------------\n' '\n' 'If a base that appears in class definition is not an ' 'instance of\n' '"type", then an "__mro_entries__" method is searched on it. ' 'If found,\n' 'it is called with the original bases tuple. This method must ' 'return a\n' 'tuple of classes that will be used instead of this base. The ' 'tuple may\n' 'be empty, in such case the original base is ignored.\n' '\n' 'See also:\n' '\n' ' **PEP 560** - Core support for typing module and generic ' 'types\n' '\n' '\n' 'Determining the appropriate metaclass\n' '-------------------------------------\n' '\n' 'The appropriate metaclass for a class definition is ' 'determined as\n' 'follows:\n' '\n' '* if no bases and no explicit metaclass are given, then ' '"type()" is\n' ' used;\n' '\n' '* if an explicit metaclass is given and it is *not* an ' 'instance of\n' ' "type()", then it is used directly as the metaclass;\n' '\n' '* if an instance of "type()" is given as the explicit ' 'metaclass, or\n' ' bases are defined, then the most derived metaclass is ' 'used.\n' '\n' 'The most derived metaclass is selected from the explicitly ' 'specified\n' 'metaclass (if any) and the metaclasses (i.e. "type(cls)") of ' 'all\n' 'specified base classes. The most derived metaclass is one ' 'which is a\n' 'subtype of *all* of these candidate metaclasses. If none of ' 'the\n' 'candidate metaclasses meets that criterion, then the class ' 'definition\n' 'will fail with "TypeError".\n' '\n' '\n' 'Preparing the class namespace\n' '-----------------------------\n' '\n' 'Once the appropriate metaclass has been identified, then the ' 'class\n' 'namespace is prepared. If the metaclass has a "__prepare__" ' 'attribute,\n' 'it is called as "namespace = metaclass.__prepare__(name, ' 'bases,\n' '**kwds)" (where the additional keyword arguments, if any, ' 'come from\n' 'the class definition). The "__prepare__" method should be ' 'implemented\n' 'as a "classmethod()". The namespace returned by ' '"__prepare__" is\n' 'passed in to "__new__", but when the final class object is ' 'created the\n' 'namespace is copied into a new "dict".\n' '\n' 'If the metaclass has no "__prepare__" attribute, then the ' 'class\n' 'namespace is initialised as an empty ordered mapping.\n' '\n' 'See also:\n' '\n' ' **PEP 3115** - Metaclasses in Python 3000\n' ' Introduced the "__prepare__" namespace hook\n' '\n' '\n' 'Executing the class body\n' '------------------------\n' '\n' 'The class body is executed (approximately) as "exec(body, ' 'globals(),\n' 'namespace)". The key difference from a normal call to ' '"exec()" is that\n' 'lexical scoping allows the class body (including any ' 'methods) to\n' 'reference names from the current and outer scopes when the ' 'class\n' 'definition occurs inside a function.\n' '\n' 'However, even when the class definition occurs inside the ' 'function,\n' 'methods defined inside the class still cannot see names ' 'defined at the\n' 'class scope. Class variables must be accessed through the ' 'first\n' 'parameter of instance or class methods, or through the ' 'implicit\n' 'lexically scoped "__class__" reference described in the next ' 'section.\n' '\n' '\n' 'Creating the class object\n' '-------------------------\n' '\n' 'Once the class namespace has been populated by executing the ' 'class\n' 'body, the class object is created by calling ' '"metaclass(name, bases,\n' 'namespace, **kwds)" (the additional keywords passed here are ' 'the same\n' 'as those passed to "__prepare__").\n' '\n' 'This class object is the one that will be referenced by the ' 'zero-\n' 'argument form of "super()". "__class__" is an implicit ' 'closure\n' 'reference created by the compiler if any methods in a class ' 'body refer\n' 'to either "__class__" or "super". This allows the zero ' 'argument form\n' 'of "super()" to correctly identify the class being defined ' 'based on\n' 'lexical scoping, while the class or instance that was used ' 'to make the\n' 'current call is identified based on the first argument ' 'passed to the\n' 'method.\n' '\n' '**CPython implementation detail:** In CPython 3.6 and later, ' 'the\n' '"__class__" cell is passed to the metaclass as a ' '"__classcell__" entry\n' 'in the class namespace. If present, this must be propagated ' 'up to the\n' '"type.__new__" call in order for the class to be ' 'initialised\n' 'correctly. Failing to do so will result in a "RuntimeError" ' 'in Python\n' '3.8.\n' '\n' 'When using the default metaclass "type", or any metaclass ' 'that\n' 'ultimately calls "type.__new__", the following additional\n' 'customisation steps are invoked after creating the class ' 'object:\n' '\n' '* first, "type.__new__" collects all of the descriptors in ' 'the class\n' ' namespace that define a "__set_name__()" method;\n' '\n' '* second, all of these "__set_name__" methods are called ' 'with the\n' ' class being defined and the assigned name of that ' 'particular\n' ' descriptor;\n' '\n' '* finally, the "__init_subclass__()" hook is called on the ' 'immediate\n' ' parent of the new class in its method resolution order.\n' '\n' 'After the class object is created, it is passed to the ' 'class\n' 'decorators included in the class definition (if any) and the ' 'resulting\n' 'object is bound in the local namespace as the defined ' 'class.\n' '\n' 'When a new class is created by "type.__new__", the object ' 'provided as\n' 'the namespace parameter is copied to a new ordered mapping ' 'and the\n' 'original object is discarded. The new copy is wrapped in a ' 'read-only\n' 'proxy, which becomes the "__dict__" attribute of the class ' 'object.\n' '\n' 'See also:\n' '\n' ' **PEP 3135** - New super\n' ' Describes the implicit "__class__" closure reference\n' '\n' '\n' 'Uses for metaclasses\n' '--------------------\n' '\n' 'The potential uses for metaclasses are boundless. Some ideas ' 'that have\n' 'been explored include enum, logging, interface checking, ' 'automatic\n' 'delegation, automatic property creation, proxies, ' 'frameworks, and\n' 'automatic resource locking/synchronization.\n' '\n' '\n' 'Customizing instance and subclass checks\n' '========================================\n' '\n' 'The following methods are used to override the default ' 'behavior of the\n' '"isinstance()" and "issubclass()" built-in functions.\n' '\n' 'In particular, the metaclass "abc.ABCMeta" implements these ' 'methods in\n' 'order to allow the addition of Abstract Base Classes (ABCs) ' 'as\n' '“virtual base classes” to any class or type (including ' 'built-in\n' 'types), including other ABCs.\n' '\n' 'class.__instancecheck__(self, instance)\n' '\n' ' Return true if *instance* should be considered a (direct ' 'or\n' ' indirect) instance of *class*. If defined, called to ' 'implement\n' ' "isinstance(instance, class)".\n' '\n' 'class.__subclasscheck__(self, subclass)\n' '\n' ' Return true if *subclass* should be considered a (direct ' 'or\n' ' indirect) subclass of *class*. If defined, called to ' 'implement\n' ' "issubclass(subclass, class)".\n' '\n' 'Note that these methods are looked up on the type ' '(metaclass) of a\n' 'class. They cannot be defined as class methods in the ' 'actual class.\n' 'This is consistent with the lookup of special methods that ' 'are called\n' 'on instances, only in this case the instance is itself a ' 'class.\n' '\n' 'See also:\n' '\n' ' **PEP 3119** - Introducing Abstract Base Classes\n' ' Includes the specification for customizing ' '"isinstance()" and\n' ' "issubclass()" behavior through "__instancecheck__()" ' 'and\n' ' "__subclasscheck__()", with motivation for this ' 'functionality in\n' ' the context of adding Abstract Base Classes (see the ' '"abc"\n' ' module) to the language.\n' '\n' '\n' 'Emulating generic types\n' '=======================\n' '\n' 'One can implement the generic class syntax as specified by ' '**PEP 484**\n' '(for example "List[int]") by defining a special method:\n' '\n' 'classmethod object.__class_getitem__(cls, key)\n' '\n' ' Return an object representing the specialization of a ' 'generic class\n' ' by type arguments found in *key*.\n' '\n' 'This method is looked up on the class object itself, and ' 'when defined\n' 'in the class body, this method is implicitly a class ' 'method. Note,\n' 'this mechanism is primarily reserved for use with static ' 'type hints,\n' 'other usage is discouraged.\n' '\n' 'See also:\n' '\n' ' **PEP 560** - Core support for typing module and generic ' 'types\n' '\n' '\n' 'Emulating callable objects\n' '==========================\n' '\n' 'object.__call__(self[, args...])\n' '\n' ' Called when the instance is “called” as a function; if ' 'this method\n' ' is defined, "x(arg1, arg2, ...)" roughly translates to\n' ' "type(x).__call__(x, arg1, ...)".\n' '\n' '\n' 'Emulating container types\n' '=========================\n' '\n' 'The following methods can be defined to implement container ' 'objects.\n' 'Containers usually are sequences (such as lists or tuples) ' 'or mappings\n' '(like dictionaries), but can represent other containers as ' 'well. The\n' 'first set of methods is used either to emulate a sequence or ' 'to\n' 'emulate a mapping; the difference is that for a sequence, ' 'the\n' 'allowable keys should be the integers *k* for which "0 <= k ' '< N" where\n' '*N* is the length of the sequence, or slice objects, which ' 'define a\n' 'range of items. It is also recommended that mappings ' 'provide the\n' 'methods "keys()", "values()", "items()", "get()", ' '"clear()",\n' '"setdefault()", "pop()", "popitem()", "copy()", and ' '"update()"\n' 'behaving similar to those for Python’s standard dictionary ' 'objects.\n' 'The "collections.abc" module provides a "MutableMapping" ' 'abstract base\n' 'class to help create those methods from a base set of ' '"__getitem__()",\n' '"__setitem__()", "__delitem__()", and "keys()". Mutable ' 'sequences\n' 'should provide methods "append()", "count()", "index()", ' '"extend()",\n' '"insert()", "pop()", "remove()", "reverse()" and "sort()", ' 'like Python\n' 'standard list objects. Finally, sequence types should ' 'implement\n' 'addition (meaning concatenation) and multiplication ' '(meaning\n' 'repetition) by defining the methods "__add__()", ' '"__radd__()",\n' '"__iadd__()", "__mul__()", "__rmul__()" and "__imul__()" ' 'described\n' 'below; they should not define other numerical operators. It ' 'is\n' 'recommended that both mappings and sequences implement the\n' '"__contains__()" method to allow efficient use of the "in" ' 'operator;\n' 'for mappings, "in" should search the mapping’s keys; for ' 'sequences, it\n' 'should search through the values. It is further recommended ' 'that both\n' 'mappings and sequences implement the "__iter__()" method to ' 'allow\n' 'efficient iteration through the container; for mappings, ' '"__iter__()"\n' 'should iterate through the object’s keys; for sequences, it ' 'should\n' 'iterate through the values.\n' '\n' 'object.__len__(self)\n' '\n' ' Called to implement the built-in function "len()". ' 'Should return\n' ' the length of the object, an integer ">=" 0. Also, an ' 'object that\n' ' doesn’t define a "__bool__()" method and whose ' '"__len__()" method\n' ' returns zero is considered to be false in a Boolean ' 'context.\n' '\n' ' **CPython implementation detail:** In CPython, the length ' 'is\n' ' required to be at most "sys.maxsize". If the length is ' 'larger than\n' ' "sys.maxsize" some features (such as "len()") may raise\n' ' "OverflowError". To prevent raising "OverflowError" by ' 'truth value\n' ' testing, an object must define a "__bool__()" method.\n' '\n' 'object.__length_hint__(self)\n' '\n' ' Called to implement "operator.length_hint()". Should ' 'return an\n' ' estimated length for the object (which may be greater or ' 'less than\n' ' the actual length). The length must be an integer ">=" 0. ' 'The\n' ' return value may also be "NotImplemented", which is ' 'treated the\n' ' same as if the "__length_hint__" method didn’t exist at ' 'all. This\n' ' method is purely an optimization and is never required ' 'for\n' ' correctness.\n' '\n' ' New in version 3.4.\n' '\n' 'Note:\n' '\n' ' Slicing is done exclusively with the following three ' 'methods. A\n' ' call like\n' '\n' ' a[1:2] = b\n' '\n' ' is translated to\n' '\n' ' a[slice(1, 2, None)] = b\n' '\n' ' and so forth. Missing slice items are always filled in ' 'with "None".\n' '\n' 'object.__getitem__(self, key)\n' '\n' ' Called to implement evaluation of "self[key]". For ' 'sequence types,\n' ' the accepted keys should be integers and slice objects. ' 'Note that\n' ' the special interpretation of negative indexes (if the ' 'class wishes\n' ' to emulate a sequence type) is up to the "__getitem__()" ' 'method. If\n' ' *key* is of an inappropriate type, "TypeError" may be ' 'raised; if of\n' ' a value outside the set of indexes for the sequence ' '(after any\n' ' special interpretation of negative values), "IndexError" ' 'should be\n' ' raised. For mapping types, if *key* is missing (not in ' 'the\n' ' container), "KeyError" should be raised.\n' '\n' ' Note:\n' '\n' ' "for" loops expect that an "IndexError" will be raised ' 'for\n' ' illegal indexes to allow proper detection of the end of ' 'the\n' ' sequence.\n' '\n' 'object.__setitem__(self, key, value)\n' '\n' ' Called to implement assignment to "self[key]". Same note ' 'as for\n' ' "__getitem__()". This should only be implemented for ' 'mappings if\n' ' the objects support changes to the values for keys, or if ' 'new keys\n' ' can be added, or for sequences if elements can be ' 'replaced. The\n' ' same exceptions should be raised for improper *key* ' 'values as for\n' ' the "__getitem__()" method.\n' '\n' 'object.__delitem__(self, key)\n' '\n' ' Called to implement deletion of "self[key]". Same note ' 'as for\n' ' "__getitem__()". This should only be implemented for ' 'mappings if\n' ' the objects support removal of keys, or for sequences if ' 'elements\n' ' can be removed from the sequence. The same exceptions ' 'should be\n' ' raised for improper *key* values as for the ' '"__getitem__()" method.\n' '\n' 'object.__missing__(self, key)\n' '\n' ' Called by "dict"."__getitem__()" to implement "self[key]" ' 'for dict\n' ' subclasses when key is not in the dictionary.\n' '\n' 'object.__iter__(self)\n' '\n' ' This method is called when an iterator is required for a ' 'container.\n' ' This method should return a new iterator object that can ' 'iterate\n' ' over all the objects in the container. For mappings, it ' 'should\n' ' iterate over the keys of the container.\n' '\n' ' Iterator objects also need to implement this method; they ' 'are\n' ' required to return themselves. For more information on ' 'iterator\n' ' objects, see Iterator Types.\n' '\n' 'object.__reversed__(self)\n' '\n' ' Called (if present) by the "reversed()" built-in to ' 'implement\n' ' reverse iteration. It should return a new iterator ' 'object that\n' ' iterates over all the objects in the container in reverse ' 'order.\n' '\n' ' If the "__reversed__()" method is not provided, the ' '"reversed()"\n' ' built-in will fall back to using the sequence protocol ' '("__len__()"\n' ' and "__getitem__()"). Objects that support the sequence ' 'protocol\n' ' should only provide "__reversed__()" if they can provide ' 'an\n' ' implementation that is more efficient than the one ' 'provided by\n' ' "reversed()".\n' '\n' 'The membership test operators ("in" and "not in") are ' 'normally\n' 'implemented as an iteration through a container. However, ' 'container\n' 'objects can supply the following special method with a more ' 'efficient\n' 'implementation, which also does not require the object be ' 'iterable.\n' '\n' 'object.__contains__(self, item)\n' '\n' ' Called to implement membership test operators. Should ' 'return true\n' ' if *item* is in *self*, false otherwise. For mapping ' 'objects, this\n' ' should consider the keys of the mapping rather than the ' 'values or\n' ' the key-item pairs.\n' '\n' ' For objects that don’t define "__contains__()", the ' 'membership test\n' ' first tries iteration via "__iter__()", then the old ' 'sequence\n' ' iteration protocol via "__getitem__()", see this section ' 'in the\n' ' language reference.\n' '\n' '\n' 'Emulating numeric types\n' '=======================\n' '\n' 'The following methods can be defined to emulate numeric ' 'objects.\n' 'Methods corresponding to operations that are not supported ' 'by the\n' 'particular kind of number implemented (e.g., bitwise ' 'operations for\n' 'non-integral numbers) should be left undefined.\n' '\n' 'object.__add__(self, other)\n' 'object.__sub__(self, other)\n' 'object.__mul__(self, other)\n' 'object.__matmul__(self, other)\n' 'object.__truediv__(self, other)\n' 'object.__floordiv__(self, other)\n' 'object.__mod__(self, other)\n' 'object.__divmod__(self, other)\n' 'object.__pow__(self, other[, modulo])\n' 'object.__lshift__(self, other)\n' 'object.__rshift__(self, other)\n' 'object.__and__(self, other)\n' 'object.__xor__(self, other)\n' 'object.__or__(self, other)\n' '\n' ' These methods are called to implement the binary ' 'arithmetic\n' ' operations ("+", "-", "*", "@", "/", "//", "%", ' '"divmod()",\n' ' "pow()", "**", "<<", ">>", "&", "^", "|"). For instance, ' 'to\n' ' evaluate the expression "x + y", where *x* is an instance ' 'of a\n' ' class that has an "__add__()" method, "x.__add__(y)" is ' 'called.\n' ' The "__divmod__()" method should be the equivalent to ' 'using\n' ' "__floordiv__()" and "__mod__()"; it should not be ' 'related to\n' ' "__truediv__()". Note that "__pow__()" should be defined ' 'to accept\n' ' an optional third argument if the ternary version of the ' 'built-in\n' ' "pow()" function is to be supported.\n' '\n' ' If one of those methods does not support the operation ' 'with the\n' ' supplied arguments, it should return "NotImplemented".\n' '\n' 'object.__radd__(self, other)\n' 'object.__rsub__(self, other)\n' 'object.__rmul__(self, other)\n' 'object.__rmatmul__(self, other)\n' 'object.__rtruediv__(self, other)\n' 'object.__rfloordiv__(self, other)\n' 'object.__rmod__(self, other)\n' 'object.__rdivmod__(self, other)\n' 'object.__rpow__(self, other[, modulo])\n' 'object.__rlshift__(self, other)\n' 'object.__rrshift__(self, other)\n' 'object.__rand__(self, other)\n' 'object.__rxor__(self, other)\n' 'object.__ror__(self, other)\n' '\n' ' These methods are called to implement the binary ' 'arithmetic\n' ' operations ("+", "-", "*", "@", "/", "//", "%", ' '"divmod()",\n' ' "pow()", "**", "<<", ">>", "&", "^", "|") with reflected ' '(swapped)\n' ' operands. These functions are only called if the left ' 'operand does\n' ' not support the corresponding operation [3] and the ' 'operands are of\n' ' different types. [4] For instance, to evaluate the ' 'expression "x -\n' ' y", where *y* is an instance of a class that has an ' '"__rsub__()"\n' ' method, "y.__rsub__(x)" is called if "x.__sub__(y)" ' 'returns\n' ' *NotImplemented*.\n' '\n' ' Note that ternary "pow()" will not try calling ' '"__rpow__()" (the\n' ' coercion rules would become too complicated).\n' '\n' ' Note:\n' '\n' ' If the right operand’s type is a subclass of the left ' 'operand’s\n' ' type and that subclass provides a different ' 'implementation of the\n' ' reflected method for the operation, this method will be ' 'called\n' ' before the left operand’s non-reflected method. This ' 'behavior\n' ' allows subclasses to override their ancestors’ ' 'operations.\n' '\n' 'object.__iadd__(self, other)\n' 'object.__isub__(self, other)\n' 'object.__imul__(self, other)\n' 'object.__imatmul__(self, other)\n' 'object.__itruediv__(self, other)\n' 'object.__ifloordiv__(self, other)\n' 'object.__imod__(self, other)\n' 'object.__ipow__(self, other[, modulo])\n' 'object.__ilshift__(self, other)\n' 'object.__irshift__(self, other)\n' 'object.__iand__(self, other)\n' 'object.__ixor__(self, other)\n' 'object.__ior__(self, other)\n' '\n' ' These methods are called to implement the augmented ' 'arithmetic\n' ' assignments ("+=", "-=", "*=", "@=", "/=", "//=", "%=", ' '"**=",\n' ' "<<=", ">>=", "&=", "^=", "|="). These methods should ' 'attempt to\n' ' do the operation in-place (modifying *self*) and return ' 'the result\n' ' (which could be, but does not have to be, *self*). If a ' 'specific\n' ' method is not defined, the augmented assignment falls ' 'back to the\n' ' normal methods. For instance, if *x* is an instance of a ' 'class\n' ' with an "__iadd__()" method, "x += y" is equivalent to "x ' '=\n' ' x.__iadd__(y)" . Otherwise, "x.__add__(y)" and ' '"y.__radd__(x)" are\n' ' considered, as with the evaluation of "x + y". In ' 'certain\n' ' situations, augmented assignment can result in unexpected ' 'errors\n' ' (see Why does a_tuple[i] += [‘item’] raise an exception ' 'when the\n' ' addition works?), but this behavior is in fact part of ' 'the data\n' ' model.\n' '\n' 'object.__neg__(self)\n' 'object.__pos__(self)\n' 'object.__abs__(self)\n' 'object.__invert__(self)\n' '\n' ' Called to implement the unary arithmetic operations ("-", ' '"+",\n' ' "abs()" and "~").\n' '\n' 'object.__complex__(self)\n' 'object.__int__(self)\n' 'object.__float__(self)\n' '\n' ' Called to implement the built-in functions "complex()", ' '"int()" and\n' ' "float()". Should return a value of the appropriate ' 'type.\n' '\n' 'object.__index__(self)\n' '\n' ' Called to implement "operator.index()", and whenever ' 'Python needs\n' ' to losslessly convert the numeric object to an integer ' 'object (such\n' ' as in slicing, or in the built-in "bin()", "hex()" and ' '"oct()"\n' ' functions). Presence of this method indicates that the ' 'numeric\n' ' object is an integer type. Must return an integer.\n' '\n' ' If "__int__()", "__float__()" and "__complex__()" are not ' 'defined\n' ' then corresponding built-in functions "int()", "float()" ' 'and\n' ' "complex()" fall back to "__index__()".\n' '\n' 'object.__round__(self[, ndigits])\n' 'object.__trunc__(self)\n' 'object.__floor__(self)\n' 'object.__ceil__(self)\n' '\n' ' Called to implement the built-in function "round()" and ' '"math"\n' ' functions "trunc()", "floor()" and "ceil()". Unless ' '*ndigits* is\n' ' passed to "__round__()" all these methods should return ' 'the value\n' ' of the object truncated to an "Integral" (typically an ' '"int").\n' '\n' ' If "__int__()" is not defined then the built-in function ' '"int()"\n' ' falls back to "__trunc__()".\n' '\n' '\n' 'With Statement Context Managers\n' '===============================\n' '\n' 'A *context manager* is an object that defines the runtime ' 'context to\n' 'be established when executing a "with" statement. The ' 'context manager\n' 'handles the entry into, and the exit from, the desired ' 'runtime context\n' 'for the execution of the block of code. Context managers ' 'are normally\n' 'invoked using the "with" statement (described in section The ' 'with\n' 'statement), but can also be used by directly invoking their ' 'methods.\n' '\n' 'Typical uses of context managers include saving and ' 'restoring various\n' 'kinds of global state, locking and unlocking resources, ' 'closing opened\n' 'files, etc.\n' '\n' 'For more information on context managers, see Context ' 'Manager Types.\n' '\n' 'object.__enter__(self)\n' '\n' ' Enter the runtime context related to this object. The ' '"with"\n' ' statement will bind this method’s return value to the ' 'target(s)\n' ' specified in the "as" clause of the statement, if any.\n' '\n' 'object.__exit__(self, exc_type, exc_value, traceback)\n' '\n' ' Exit the runtime context related to this object. The ' 'parameters\n' ' describe the exception that caused the context to be ' 'exited. If the\n' ' context was exited without an exception, all three ' 'arguments will\n' ' be "None".\n' '\n' ' If an exception is supplied, and the method wishes to ' 'suppress the\n' ' exception (i.e., prevent it from being propagated), it ' 'should\n' ' return a true value. Otherwise, the exception will be ' 'processed\n' ' normally upon exit from this method.\n' '\n' ' Note that "__exit__()" methods should not reraise the ' 'passed-in\n' ' exception; this is the caller’s responsibility.\n' '\n' 'See also:\n' '\n' ' **PEP 343** - The “with” statement\n' ' The specification, background, and examples for the ' 'Python "with"\n' ' statement.\n' '\n' '\n' 'Special method lookup\n' '=====================\n' '\n' 'For custom classes, implicit invocations of special methods ' 'are only\n' 'guaranteed to work correctly if defined on an object’s type, ' 'not in\n' 'the object’s instance dictionary. That behaviour is the ' 'reason why\n' 'the following code raises an exception:\n' '\n' ' >>> class C:\n' ' ... pass\n' ' ...\n' ' >>> c = C()\n' ' >>> c.__len__ = lambda: 5\n' ' >>> len(c)\n' ' Traceback (most recent call last):\n' ' File "<stdin>", line 1, in <module>\n' " TypeError: object of type 'C' has no len()\n" '\n' 'The rationale behind this behaviour lies with a number of ' 'special\n' 'methods such as "__hash__()" and "__repr__()" that are ' 'implemented by\n' 'all objects, including type objects. If the implicit lookup ' 'of these\n' 'methods used the conventional lookup process, they would ' 'fail when\n' 'invoked on the type object itself:\n' '\n' ' >>> 1 .__hash__() == hash(1)\n' ' True\n' ' >>> int.__hash__() == hash(int)\n' ' Traceback (most recent call last):\n' ' File "<stdin>", line 1, in <module>\n' " TypeError: descriptor '__hash__' of 'int' object needs an " 'argument\n' '\n' 'Incorrectly attempting to invoke an unbound method of a ' 'class in this\n' 'way is sometimes referred to as ‘metaclass confusion’, and ' 'is avoided\n' 'by bypassing the instance when looking up special methods:\n' '\n' ' >>> type(1).__hash__(1) == hash(1)\n' ' True\n' ' >>> type(int).__hash__(int) == hash(int)\n' ' True\n' '\n' 'In addition to bypassing any instance attributes in the ' 'interest of\n' 'correctness, implicit special method lookup generally also ' 'bypasses\n' 'the "__getattribute__()" method even of the object’s ' 'metaclass:\n' '\n' ' >>> class Meta(type):\n' ' ... def __getattribute__(*args):\n' ' ... print("Metaclass getattribute invoked")\n' ' ... return type.__getattribute__(*args)\n' ' ...\n' ' >>> class C(object, metaclass=Meta):\n' ' ... def __len__(self):\n' ' ... return 10\n' ' ... def __getattribute__(*args):\n' ' ... print("Class getattribute invoked")\n' ' ... return object.__getattribute__(*args)\n' ' ...\n' ' >>> c = C()\n' ' >>> c.__len__() # Explicit lookup via ' 'instance\n' ' Class getattribute invoked\n' ' 10\n' ' >>> type(c).__len__(c) # Explicit lookup via ' 'type\n' ' Metaclass getattribute invoked\n' ' 10\n' ' >>> len(c) # Implicit lookup\n' ' 10\n' '\n' 'Bypassing the "__getattribute__()" machinery in this fashion ' 'provides\n' 'significant scope for speed optimisations within the ' 'interpreter, at\n' 'the cost of some flexibility in the handling of special ' 'methods (the\n' 'special method *must* be set on the class object itself in ' 'order to be\n' 'consistently invoked by the interpreter).\n', 'string-methods': 'String Methods\n' '**************\n' '\n' 'Strings implement all of the common sequence operations, ' 'along with\n' 'the additional methods described below.\n' '\n' 'Strings also support two styles of string formatting, one ' 'providing a\n' 'large degree of flexibility and customization (see ' '"str.format()",\n' 'Format String Syntax and Custom String Formatting) and the ' 'other based\n' 'on C "printf" style formatting that handles a narrower ' 'range of types\n' 'and is slightly harder to use correctly, but is often ' 'faster for the\n' 'cases it can handle (printf-style String Formatting).\n' '\n' 'The Text Processing Services section of the standard ' 'library covers a\n' 'number of other modules that provide various text related ' 'utilities\n' '(including regular expression support in the "re" ' 'module).\n' '\n' 'str.capitalize()\n' '\n' ' Return a copy of the string with its first character ' 'capitalized\n' ' and the rest lowercased.\n' '\n' ' Changed in version 3.8: The first character is now put ' 'into\n' ' titlecase rather than uppercase. This means that ' 'characters like\n' ' digraphs will only have their first letter capitalized, ' 'instead of\n' ' the full character.\n' '\n' 'str.casefold()\n' '\n' ' Return a casefolded copy of the string. Casefolded ' 'strings may be\n' ' used for caseless matching.\n' '\n' ' Casefolding is similar to lowercasing but more ' 'aggressive because\n' ' it is intended to remove all case distinctions in a ' 'string. For\n' ' example, the German lowercase letter "\'ß\'" is ' 'equivalent to ""ss"".\n' ' Since it is already lowercase, "lower()" would do ' 'nothing to "\'ß\'";\n' ' "casefold()" converts it to ""ss"".\n' '\n' ' The casefolding algorithm is described in section 3.13 ' 'of the\n' ' Unicode Standard.\n' '\n' ' New in version 3.3.\n' '\n' 'str.center(width[, fillchar])\n' '\n' ' Return centered in a string of length *width*. Padding ' 'is done\n' ' using the specified *fillchar* (default is an ASCII ' 'space). The\n' ' original string is returned if *width* is less than or ' 'equal to\n' ' "len(s)".\n' '\n' 'str.count(sub[, start[, end]])\n' '\n' ' Return the number of non-overlapping occurrences of ' 'substring *sub*\n' ' in the range [*start*, *end*]. Optional arguments ' '*start* and\n' ' *end* are interpreted as in slice notation.\n' '\n' "str.encode(encoding='utf-8', errors='strict')\n" '\n' ' Return an encoded version of the string as a bytes ' 'object. Default\n' ' encoding is "\'utf-8\'". *errors* may be given to set a ' 'different\n' ' error handling scheme. The default for *errors* is ' '"\'strict\'",\n' ' meaning that encoding errors raise a "UnicodeError". ' 'Other possible\n' ' values are "\'ignore\'", "\'replace\'", ' '"\'xmlcharrefreplace\'",\n' ' "\'backslashreplace\'" and any other name registered ' 'via\n' ' "codecs.register_error()", see section Error Handlers. ' 'For a list\n' ' of possible encodings, see section Standard Encodings.\n' '\n' ' By default, the *errors* argument is not checked for ' 'best\n' ' performances, but only used at the first encoding ' 'error. Enable the\n' ' Python Development Mode, or use a debug build to check ' '*errors*.\n' '\n' ' Changed in version 3.1: Support for keyword arguments ' 'added.\n' '\n' ' Changed in version 3.9: The *errors* is now checked in ' 'development\n' ' mode and in debug mode.\n' '\n' 'str.endswith(suffix[, start[, end]])\n' '\n' ' Return "True" if the string ends with the specified ' '*suffix*,\n' ' otherwise return "False". *suffix* can also be a tuple ' 'of suffixes\n' ' to look for. With optional *start*, test beginning at ' 'that\n' ' position. With optional *end*, stop comparing at that ' 'position.\n' '\n' 'str.expandtabs(tabsize=8)\n' '\n' ' Return a copy of the string where all tab characters ' 'are replaced\n' ' by one or more spaces, depending on the current column ' 'and the\n' ' given tab size. Tab positions occur every *tabsize* ' 'characters\n' ' (default is 8, giving tab positions at columns 0, 8, 16 ' 'and so on).\n' ' To expand the string, the current column is set to zero ' 'and the\n' ' string is examined character by character. If the ' 'character is a\n' ' tab ("\\t"), one or more space characters are inserted ' 'in the result\n' ' until the current column is equal to the next tab ' 'position. (The\n' ' tab character itself is not copied.) If the character ' 'is a newline\n' ' ("\\n") or return ("\\r"), it is copied and the current ' 'column is\n' ' reset to zero. Any other character is copied unchanged ' 'and the\n' ' current column is incremented by one regardless of how ' 'the\n' ' character is represented when printed.\n' '\n' " >>> '01\\t012\\t0123\\t01234'.expandtabs()\n" " '01 012 0123 01234'\n" " >>> '01\\t012\\t0123\\t01234'.expandtabs(4)\n" " '01 012 0123 01234'\n" '\n' 'str.find(sub[, start[, end]])\n' '\n' ' Return the lowest index in the string where substring ' '*sub* is\n' ' found within the slice "s[start:end]". Optional ' 'arguments *start*\n' ' and *end* are interpreted as in slice notation. Return ' '"-1" if\n' ' *sub* is not found.\n' '\n' ' Note:\n' '\n' ' The "find()" method should be used only if you need ' 'to know the\n' ' position of *sub*. To check if *sub* is a substring ' 'or not, use\n' ' the "in" operator:\n' '\n' " >>> 'Py' in 'Python'\n" ' True\n' '\n' 'str.format(*args, **kwargs)\n' '\n' ' Perform a string formatting operation. The string on ' 'which this\n' ' method is called can contain literal text or ' 'replacement fields\n' ' delimited by braces "{}". Each replacement field ' 'contains either\n' ' the numeric index of a positional argument, or the name ' 'of a\n' ' keyword argument. Returns a copy of the string where ' 'each\n' ' replacement field is replaced with the string value of ' 'the\n' ' corresponding argument.\n' '\n' ' >>> "The sum of 1 + 2 is {0}".format(1+2)\n' " 'The sum of 1 + 2 is 3'\n" '\n' ' See Format String Syntax for a description of the ' 'various\n' ' formatting options that can be specified in format ' 'strings.\n' '\n' ' Note:\n' '\n' ' When formatting a number ("int", "float", "complex",\n' ' "decimal.Decimal" and subclasses) with the "n" type ' '(ex:\n' ' "\'{:n}\'.format(1234)"), the function temporarily ' 'sets the\n' ' "LC_CTYPE" locale to the "LC_NUMERIC" locale to ' 'decode\n' ' "decimal_point" and "thousands_sep" fields of ' '"localeconv()" if\n' ' they are non-ASCII or longer than 1 byte, and the ' '"LC_NUMERIC"\n' ' locale is different than the "LC_CTYPE" locale. This ' 'temporary\n' ' change affects other threads.\n' '\n' ' Changed in version 3.7: When formatting a number with ' 'the "n" type,\n' ' the function sets temporarily the "LC_CTYPE" locale to ' 'the\n' ' "LC_NUMERIC" locale in some cases.\n' '\n' 'str.format_map(mapping)\n' '\n' ' Similar to "str.format(**mapping)", except that ' '"mapping" is used\n' ' directly and not copied to a "dict". This is useful if ' 'for example\n' ' "mapping" is a dict subclass:\n' '\n' ' >>> class Default(dict):\n' ' ... def __missing__(self, key):\n' ' ... return key\n' ' ...\n' " >>> '{name} was born in " "{country}'.format_map(Default(name='Guido'))\n" " 'Guido was born in country'\n" '\n' ' New in version 3.2.\n' '\n' 'str.index(sub[, start[, end]])\n' '\n' ' Like "find()", but raise "ValueError" when the ' 'substring is not\n' ' found.\n' '\n' 'str.isalnum()\n' '\n' ' Return "True" if all characters in the string are ' 'alphanumeric and\n' ' there is at least one character, "False" otherwise. A ' 'character\n' ' "c" is alphanumeric if one of the following returns ' '"True":\n' ' "c.isalpha()", "c.isdecimal()", "c.isdigit()", or ' '"c.isnumeric()".\n' '\n' 'str.isalpha()\n' '\n' ' Return "True" if all characters in the string are ' 'alphabetic and\n' ' there is at least one character, "False" otherwise. ' 'Alphabetic\n' ' characters are those characters defined in the Unicode ' 'character\n' ' database as “Letter”, i.e., those with general category ' 'property\n' ' being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note ' 'that this is\n' ' different from the “Alphabetic” property defined in the ' 'Unicode\n' ' Standard.\n' '\n' 'str.isascii()\n' '\n' ' Return "True" if the string is empty or all characters ' 'in the\n' ' string are ASCII, "False" otherwise. ASCII characters ' 'have code\n' ' points in the range U+0000-U+007F.\n' '\n' ' New in version 3.7.\n' '\n' 'str.isdecimal()\n' '\n' ' Return "True" if all characters in the string are ' 'decimal\n' ' characters and there is at least one character, "False" ' 'otherwise.\n' ' Decimal characters are those that can be used to form ' 'numbers in\n' ' base 10, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. ' 'Formally a decimal\n' ' character is a character in the Unicode General ' 'Category “Nd”.\n' '\n' 'str.isdigit()\n' '\n' ' Return "True" if all characters in the string are ' 'digits and there\n' ' is at least one character, "False" otherwise. Digits ' 'include\n' ' decimal characters and digits that need special ' 'handling, such as\n' ' the compatibility superscript digits. This covers ' 'digits which\n' ' cannot be used to form numbers in base 10, like the ' 'Kharosthi\n' ' numbers. Formally, a digit is a character that has the ' 'property\n' ' value Numeric_Type=Digit or Numeric_Type=Decimal.\n' '\n' 'str.isidentifier()\n' '\n' ' Return "True" if the string is a valid identifier ' 'according to the\n' ' language definition, section Identifiers and keywords.\n' '\n' ' Call "keyword.iskeyword()" to test whether string "s" ' 'is a reserved\n' ' identifier, such as "def" and "class".\n' '\n' ' Example:\n' '\n' ' >>> from keyword import iskeyword\n' '\n' " >>> 'hello'.isidentifier(), iskeyword('hello')\n" ' True, False\n' " >>> 'def'.isidentifier(), iskeyword('def')\n" ' True, True\n' '\n' 'str.islower()\n' '\n' ' Return "True" if all cased characters [4] in the string ' 'are\n' ' lowercase and there is at least one cased character, ' '"False"\n' ' otherwise.\n' '\n' 'str.isnumeric()\n' '\n' ' Return "True" if all characters in the string are ' 'numeric\n' ' characters, and there is at least one character, ' '"False" otherwise.\n' ' Numeric characters include digit characters, and all ' 'characters\n' ' that have the Unicode numeric value property, e.g. ' 'U+2155, VULGAR\n' ' FRACTION ONE FIFTH. Formally, numeric characters are ' 'those with\n' ' the property value Numeric_Type=Digit, ' 'Numeric_Type=Decimal or\n' ' Numeric_Type=Numeric.\n' '\n' 'str.isprintable()\n' '\n' ' Return "True" if all characters in the string are ' 'printable or the\n' ' string is empty, "False" otherwise. Nonprintable ' 'characters are\n' ' those characters defined in the Unicode character ' 'database as\n' ' “Other” or “Separator”, excepting the ASCII space ' '(0x20) which is\n' ' considered printable. (Note that printable characters ' 'in this\n' ' context are those which should not be escaped when ' '"repr()" is\n' ' invoked on a string. It has no bearing on the handling ' 'of strings\n' ' written to "sys.stdout" or "sys.stderr".)\n' '\n' 'str.isspace()\n' '\n' ' Return "True" if there are only whitespace characters ' 'in the string\n' ' and there is at least one character, "False" ' 'otherwise.\n' '\n' ' A character is *whitespace* if in the Unicode character ' 'database\n' ' (see "unicodedata"), either its general category is ' '"Zs"\n' ' (“Separator, space”), or its bidirectional class is one ' 'of "WS",\n' ' "B", or "S".\n' '\n' 'str.istitle()\n' '\n' ' Return "True" if the string is a titlecased string and ' 'there is at\n' ' least one character, for example uppercase characters ' 'may only\n' ' follow uncased characters and lowercase characters only ' 'cased ones.\n' ' Return "False" otherwise.\n' '\n' 'str.isupper()\n' '\n' ' Return "True" if all cased characters [4] in the string ' 'are\n' ' uppercase and there is at least one cased character, ' '"False"\n' ' otherwise.\n' '\n' " >>> 'BANANA'.isupper()\n" ' True\n' " >>> 'banana'.isupper()\n" ' False\n' " >>> 'baNana'.isupper()\n" ' False\n' " >>> ' '.isupper()\n" ' False\n' '\n' 'str.join(iterable)\n' '\n' ' Return a string which is the concatenation of the ' 'strings in\n' ' *iterable*. A "TypeError" will be raised if there are ' 'any non-\n' ' string values in *iterable*, including "bytes" ' 'objects. The\n' ' separator between elements is the string providing this ' 'method.\n' '\n' 'str.ljust(width[, fillchar])\n' '\n' ' Return the string left justified in a string of length ' '*width*.\n' ' Padding is done using the specified *fillchar* (default ' 'is an ASCII\n' ' space). The original string is returned if *width* is ' 'less than or\n' ' equal to "len(s)".\n' '\n' 'str.lower()\n' '\n' ' Return a copy of the string with all the cased ' 'characters [4]\n' ' converted to lowercase.\n' '\n' ' The lowercasing algorithm used is described in section ' '3.13 of the\n' ' Unicode Standard.\n' '\n' 'str.lstrip([chars])\n' '\n' ' Return a copy of the string with leading characters ' 'removed. The\n' ' *chars* argument is a string specifying the set of ' 'characters to be\n' ' removed. If omitted or "None", the *chars* argument ' 'defaults to\n' ' removing whitespace. The *chars* argument is not a ' 'prefix; rather,\n' ' all combinations of its values are stripped:\n' '\n' " >>> ' spacious '.lstrip()\n" " 'spacious '\n" " >>> 'www.example.com'.lstrip('cmowz.')\n" " 'example.com'\n" '\n' ' See "str.removeprefix()" for a method that will remove ' 'a single\n' ' prefix string rather than all of a set of characters. ' 'For example:\n' '\n' " >>> 'Arthur: three!'.lstrip('Arthur: ')\n" " 'ee!'\n" " >>> 'Arthur: three!'.removeprefix('Arthur: ')\n" " 'three!'\n" '\n' 'static str.maketrans(x[, y[, z]])\n' '\n' ' This static method returns a translation table usable ' 'for\n' ' "str.translate()".\n' '\n' ' If there is only one argument, it must be a dictionary ' 'mapping\n' ' Unicode ordinals (integers) or characters (strings of ' 'length 1) to\n' ' Unicode ordinals, strings (of arbitrary lengths) or ' '"None".\n' ' Character keys will then be converted to ordinals.\n' '\n' ' If there are two arguments, they must be strings of ' 'equal length,\n' ' and in the resulting dictionary, each character in x ' 'will be mapped\n' ' to the character at the same position in y. If there ' 'is a third\n' ' argument, it must be a string, whose characters will be ' 'mapped to\n' ' "None" in the result.\n' '\n' 'str.partition(sep)\n' '\n' ' Split the string at the first occurrence of *sep*, and ' 'return a\n' ' 3-tuple containing the part before the separator, the ' 'separator\n' ' itself, and the part after the separator. If the ' 'separator is not\n' ' found, return a 3-tuple containing the string itself, ' 'followed by\n' ' two empty strings.\n' '\n' 'str.removeprefix(prefix, /)\n' '\n' ' If the string starts with the *prefix* string, return\n' ' "string[len(prefix):]". Otherwise, return a copy of the ' 'original\n' ' string:\n' '\n' " >>> 'TestHook'.removeprefix('Test')\n" " 'Hook'\n" " >>> 'BaseTestCase'.removeprefix('Test')\n" " 'BaseTestCase'\n" '\n' ' New in version 3.9.\n' '\n' 'str.removesuffix(suffix, /)\n' '\n' ' If the string ends with the *suffix* string and that ' '*suffix* is\n' ' not empty, return "string[:-len(suffix)]". Otherwise, ' 'return a copy\n' ' of the original string:\n' '\n' " >>> 'MiscTests'.removesuffix('Tests')\n" " 'Misc'\n" " >>> 'TmpDirMixin'.removesuffix('Tests')\n" " 'TmpDirMixin'\n" '\n' ' New in version 3.9.\n' '\n' 'str.replace(old, new[, count])\n' '\n' ' Return a copy of the string with all occurrences of ' 'substring *old*\n' ' replaced by *new*. If the optional argument *count* is ' 'given, only\n' ' the first *count* occurrences are replaced.\n' '\n' 'str.rfind(sub[, start[, end]])\n' '\n' ' Return the highest index in the string where substring ' '*sub* is\n' ' found, such that *sub* is contained within ' '"s[start:end]".\n' ' Optional arguments *start* and *end* are interpreted as ' 'in slice\n' ' notation. Return "-1" on failure.\n' '\n' 'str.rindex(sub[, start[, end]])\n' '\n' ' Like "rfind()" but raises "ValueError" when the ' 'substring *sub* is\n' ' not found.\n' '\n' 'str.rjust(width[, fillchar])\n' '\n' ' Return the string right justified in a string of length ' '*width*.\n' ' Padding is done using the specified *fillchar* (default ' 'is an ASCII\n' ' space). The original string is returned if *width* is ' 'less than or\n' ' equal to "len(s)".\n' '\n' 'str.rpartition(sep)\n' '\n' ' Split the string at the last occurrence of *sep*, and ' 'return a\n' ' 3-tuple containing the part before the separator, the ' 'separator\n' ' itself, and the part after the separator. If the ' 'separator is not\n' ' found, return a 3-tuple containing two empty strings, ' 'followed by\n' ' the string itself.\n' '\n' 'str.rsplit(sep=None, maxsplit=- 1)\n' '\n' ' Return a list of the words in the string, using *sep* ' 'as the\n' ' delimiter string. If *maxsplit* is given, at most ' '*maxsplit* splits\n' ' are done, the *rightmost* ones. If *sep* is not ' 'specified or\n' ' "None", any whitespace string is a separator. Except ' 'for splitting\n' ' from the right, "rsplit()" behaves like "split()" which ' 'is\n' ' described in detail below.\n' '\n' 'str.rstrip([chars])\n' '\n' ' Return a copy of the string with trailing characters ' 'removed. The\n' ' *chars* argument is a string specifying the set of ' 'characters to be\n' ' removed. If omitted or "None", the *chars* argument ' 'defaults to\n' ' removing whitespace. The *chars* argument is not a ' 'suffix; rather,\n' ' all combinations of its values are stripped:\n' '\n' " >>> ' spacious '.rstrip()\n" " ' spacious'\n" " >>> 'mississippi'.rstrip('ipz')\n" " 'mississ'\n" '\n' ' See "str.removesuffix()" for a method that will remove ' 'a single\n' ' suffix string rather than all of a set of characters. ' 'For example:\n' '\n' " >>> 'Monty Python'.rstrip(' Python')\n" " 'M'\n" " >>> 'Monty Python'.removesuffix(' Python')\n" " 'Monty'\n" '\n' 'str.split(sep=None, maxsplit=- 1)\n' '\n' ' Return a list of the words in the string, using *sep* ' 'as the\n' ' delimiter string. If *maxsplit* is given, at most ' '*maxsplit*\n' ' splits are done (thus, the list will have at most ' '"maxsplit+1"\n' ' elements). If *maxsplit* is not specified or "-1", ' 'then there is\n' ' no limit on the number of splits (all possible splits ' 'are made).\n' '\n' ' If *sep* is given, consecutive delimiters are not ' 'grouped together\n' ' and are deemed to delimit empty strings (for example,\n' ' "\'1,,2\'.split(\',\')" returns "[\'1\', \'\', ' '\'2\']"). The *sep* argument\n' ' may consist of multiple characters (for example,\n' ' "\'1<>2<>3\'.split(\'<>\')" returns "[\'1\', \'2\', ' '\'3\']"). Splitting an\n' ' empty string with a specified separator returns ' '"[\'\']".\n' '\n' ' For example:\n' '\n' " >>> '1,2,3'.split(',')\n" " ['1', '2', '3']\n" " >>> '1,2,3'.split(',', maxsplit=1)\n" " ['1', '2,3']\n" " >>> '1,2,,3,'.split(',')\n" " ['1', '2', '', '3', '']\n" '\n' ' If *sep* is not specified or is "None", a different ' 'splitting\n' ' algorithm is applied: runs of consecutive whitespace ' 'are regarded\n' ' as a single separator, and the result will contain no ' 'empty strings\n' ' at the start or end if the string has leading or ' 'trailing\n' ' whitespace. Consequently, splitting an empty string or ' 'a string\n' ' consisting of just whitespace with a "None" separator ' 'returns "[]".\n' '\n' ' For example:\n' '\n' " >>> '1 2 3'.split()\n" " ['1', '2', '3']\n" " >>> '1 2 3'.split(maxsplit=1)\n" " ['1', '2 3']\n" " >>> ' 1 2 3 '.split()\n" " ['1', '2', '3']\n" '\n' 'str.splitlines([keepends])\n' '\n' ' Return a list of the lines in the string, breaking at ' 'line\n' ' boundaries. Line breaks are not included in the ' 'resulting list\n' ' unless *keepends* is given and true.\n' '\n' ' This method splits on the following line boundaries. ' 'In\n' ' particular, the boundaries are a superset of *universal ' 'newlines*.\n' '\n' ' ' '+-------------------------+-------------------------------+\n' ' | Representation | ' 'Description |\n' ' ' '|=========================|===============================|\n' ' | "\\n" | Line ' 'Feed |\n' ' ' '+-------------------------+-------------------------------+\n' ' | "\\r" | Carriage ' 'Return |\n' ' ' '+-------------------------+-------------------------------+\n' ' | "\\r\\n" | Carriage Return + Line ' 'Feed |\n' ' ' '+-------------------------+-------------------------------+\n' ' | "\\v" or "\\x0b" | Line ' 'Tabulation |\n' ' ' '+-------------------------+-------------------------------+\n' ' | "\\f" or "\\x0c" | Form ' 'Feed |\n' ' ' '+-------------------------+-------------------------------+\n' ' | "\\x1c" | File ' 'Separator |\n' ' ' '+-------------------------+-------------------------------+\n' ' | "\\x1d" | Group ' 'Separator |\n' ' ' '+-------------------------+-------------------------------+\n' ' | "\\x1e" | Record ' 'Separator |\n' ' ' '+-------------------------+-------------------------------+\n' ' | "\\x85" | Next Line (C1 Control ' 'Code) |\n' ' ' '+-------------------------+-------------------------------+\n' ' | "\\u2028" | Line ' 'Separator |\n' ' ' '+-------------------------+-------------------------------+\n' ' | "\\u2029" | Paragraph ' 'Separator |\n' ' ' '+-------------------------+-------------------------------+\n' '\n' ' Changed in version 3.2: "\\v" and "\\f" added to list ' 'of line\n' ' boundaries.\n' '\n' ' For example:\n' '\n' " >>> 'ab c\\n\\nde fg\\rkl\\r\\n'.splitlines()\n" " ['ab c', '', 'de fg', 'kl']\n" " >>> 'ab c\\n\\nde " "fg\\rkl\\r\\n'.splitlines(keepends=True)\n" " ['ab c\\n', '\\n', 'de fg\\r', 'kl\\r\\n']\n" '\n' ' Unlike "split()" when a delimiter string *sep* is ' 'given, this\n' ' method returns an empty list for the empty string, and ' 'a terminal\n' ' line break does not result in an extra line:\n' '\n' ' >>> "".splitlines()\n' ' []\n' ' >>> "One line\\n".splitlines()\n' " ['One line']\n" '\n' ' For comparison, "split(\'\\n\')" gives:\n' '\n' " >>> ''.split('\\n')\n" " ['']\n" " >>> 'Two lines\\n'.split('\\n')\n" " ['Two lines', '']\n" '\n' 'str.startswith(prefix[, start[, end]])\n' '\n' ' Return "True" if string starts with the *prefix*, ' 'otherwise return\n' ' "False". *prefix* can also be a tuple of prefixes to ' 'look for.\n' ' With optional *start*, test string beginning at that ' 'position.\n' ' With optional *end*, stop comparing string at that ' 'position.\n' '\n' 'str.strip([chars])\n' '\n' ' Return a copy of the string with the leading and ' 'trailing\n' ' characters removed. The *chars* argument is a string ' 'specifying the\n' ' set of characters to be removed. If omitted or "None", ' 'the *chars*\n' ' argument defaults to removing whitespace. The *chars* ' 'argument is\n' ' not a prefix or suffix; rather, all combinations of its ' 'values are\n' ' stripped:\n' '\n' " >>> ' spacious '.strip()\n" " 'spacious'\n" " >>> 'www.example.com'.strip('cmowz.')\n" " 'example'\n" '\n' ' The outermost leading and trailing *chars* argument ' 'values are\n' ' stripped from the string. Characters are removed from ' 'the leading\n' ' end until reaching a string character that is not ' 'contained in the\n' ' set of characters in *chars*. A similar action takes ' 'place on the\n' ' trailing end. For example:\n' '\n' " >>> comment_string = '#....... Section 3.2.1 Issue " "#32 .......'\n" " >>> comment_string.strip('.#! ')\n" " 'Section 3.2.1 Issue #32'\n" '\n' 'str.swapcase()\n' '\n' ' Return a copy of the string with uppercase characters ' 'converted to\n' ' lowercase and vice versa. Note that it is not ' 'necessarily true that\n' ' "s.swapcase().swapcase() == s".\n' '\n' 'str.title()\n' '\n' ' Return a titlecased version of the string where words ' 'start with an\n' ' uppercase character and the remaining characters are ' 'lowercase.\n' '\n' ' For example:\n' '\n' " >>> 'Hello world'.title()\n" " 'Hello World'\n" '\n' ' The algorithm uses a simple language-independent ' 'definition of a\n' ' word as groups of consecutive letters. The definition ' 'works in\n' ' many contexts but it means that apostrophes in ' 'contractions and\n' ' possessives form word boundaries, which may not be the ' 'desired\n' ' result:\n' '\n' ' >>> "they\'re bill\'s friends from the UK".title()\n' ' "They\'Re Bill\'S Friends From The Uk"\n' '\n' ' A workaround for apostrophes can be constructed using ' 'regular\n' ' expressions:\n' '\n' ' >>> import re\n' ' >>> def titlecase(s):\n' ' ... return re.sub(r"[A-Za-z]+(\'[A-Za-z]+)?",\n' ' ... lambda mo: ' 'mo.group(0).capitalize(),\n' ' ... s)\n' ' ...\n' ' >>> titlecase("they\'re bill\'s friends.")\n' ' "They\'re Bill\'s Friends."\n' '\n' 'str.translate(table)\n' '\n' ' Return a copy of the string in which each character has ' 'been mapped\n' ' through the given translation table. The table must be ' 'an object\n' ' that implements indexing via "__getitem__()", typically ' 'a *mapping*\n' ' or *sequence*. When indexed by a Unicode ordinal (an ' 'integer), the\n' ' table object can do any of the following: return a ' 'Unicode ordinal\n' ' or a string, to map the character to one or more other ' 'characters;\n' ' return "None", to delete the character from the return ' 'string; or\n' ' raise a "LookupError" exception, to map the character ' 'to itself.\n' '\n' ' You can use "str.maketrans()" to create a translation ' 'map from\n' ' character-to-character mappings in different formats.\n' '\n' ' See also the "codecs" module for a more flexible ' 'approach to custom\n' ' character mappings.\n' '\n' 'str.upper()\n' '\n' ' Return a copy of the string with all the cased ' 'characters [4]\n' ' converted to uppercase. Note that ' '"s.upper().isupper()" might be\n' ' "False" if "s" contains uncased characters or if the ' 'Unicode\n' ' category of the resulting character(s) is not “Lu” ' '(Letter,\n' ' uppercase), but e.g. “Lt” (Letter, titlecase).\n' '\n' ' The uppercasing algorithm used is described in section ' '3.13 of the\n' ' Unicode Standard.\n' '\n' 'str.zfill(width)\n' '\n' ' Return a copy of the string left filled with ASCII ' '"\'0\'" digits to\n' ' make a string of length *width*. A leading sign prefix\n' ' ("\'+\'"/"\'-\'") is handled by inserting the padding ' '*after* the sign\n' ' character rather than before. The original string is ' 'returned if\n' ' *width* is less than or equal to "len(s)".\n' '\n' ' For example:\n' '\n' ' >>> "42".zfill(5)\n' " '00042'\n" ' >>> "-42".zfill(5)\n' " '-0042'\n", 'strings': 'String and Bytes literals\n' '*************************\n' '\n' 'String literals are described by the following lexical ' 'definitions:\n' '\n' ' stringliteral ::= [stringprefix](shortstring | longstring)\n' ' stringprefix ::= "r" | "u" | "R" | "U" | "f" | "F"\n' ' | "fr" | "Fr" | "fR" | "FR" | "rf" | "rF" | ' '"Rf" | "RF"\n' ' shortstring ::= "\'" shortstringitem* "\'" | \'"\' ' 'shortstringitem* \'"\'\n' ' longstring ::= "\'\'\'" longstringitem* "\'\'\'" | ' '\'"""\' longstringitem* \'"""\'\n' ' shortstringitem ::= shortstringchar | stringescapeseq\n' ' longstringitem ::= longstringchar | stringescapeseq\n' ' shortstringchar ::= <any source character except "\\" or ' 'newline or the quote>\n' ' longstringchar ::= <any source character except "\\">\n' ' stringescapeseq ::= "\\" <any source character>\n' '\n' ' bytesliteral ::= bytesprefix(shortbytes | longbytes)\n' ' bytesprefix ::= "b" | "B" | "br" | "Br" | "bR" | "BR" | ' '"rb" | "rB" | "Rb" | "RB"\n' ' shortbytes ::= "\'" shortbytesitem* "\'" | \'"\' ' 'shortbytesitem* \'"\'\n' ' longbytes ::= "\'\'\'" longbytesitem* "\'\'\'" | \'"""\' ' 'longbytesitem* \'"""\'\n' ' shortbytesitem ::= shortbyteschar | bytesescapeseq\n' ' longbytesitem ::= longbyteschar | bytesescapeseq\n' ' shortbyteschar ::= <any ASCII character except "\\" or newline ' 'or the quote>\n' ' longbyteschar ::= <any ASCII character except "\\">\n' ' bytesescapeseq ::= "\\" <any ASCII character>\n' '\n' 'One syntactic restriction not indicated by these productions is ' 'that\n' 'whitespace is not allowed between the "stringprefix" or ' '"bytesprefix"\n' 'and the rest of the literal. The source character set is defined ' 'by\n' 'the encoding declaration; it is UTF-8 if no encoding declaration ' 'is\n' 'given in the source file; see section Encoding declarations.\n' '\n' 'In plain English: Both types of literals can be enclosed in ' 'matching\n' 'single quotes ("\'") or double quotes ("""). They can also be ' 'enclosed\n' 'in matching groups of three single or double quotes (these are\n' 'generally referred to as *triple-quoted strings*). The ' 'backslash\n' '("\\") character is used to escape characters that otherwise have ' 'a\n' 'special meaning, such as newline, backslash itself, or the quote\n' 'character.\n' '\n' 'Bytes literals are always prefixed with "\'b\'" or "\'B\'"; they ' 'produce\n' 'an instance of the "bytes" type instead of the "str" type. They ' 'may\n' 'only contain ASCII characters; bytes with a numeric value of 128 ' 'or\n' 'greater must be expressed with escapes.\n' '\n' 'Both string and bytes literals may optionally be prefixed with a\n' 'letter "\'r\'" or "\'R\'"; such strings are called *raw strings* ' 'and treat\n' 'backslashes as literal characters. As a result, in string ' 'literals,\n' '"\'\\U\'" and "\'\\u\'" escapes in raw strings are not treated ' 'specially.\n' 'Given that Python 2.x’s raw unicode literals behave differently ' 'than\n' 'Python 3.x’s the "\'ur\'" syntax is not supported.\n' '\n' 'New in version 3.3: The "\'rb\'" prefix of raw bytes literals has ' 'been\n' 'added as a synonym of "\'br\'".\n' '\n' 'New in version 3.3: Support for the unicode legacy literal\n' '("u\'value\'") was reintroduced to simplify the maintenance of ' 'dual\n' 'Python 2.x and 3.x codebases. See **PEP 414** for more ' 'information.\n' '\n' 'A string literal with "\'f\'" or "\'F\'" in its prefix is a ' '*formatted\n' 'string literal*; see Formatted string literals. The "\'f\'" may ' 'be\n' 'combined with "\'r\'", but not with "\'b\'" or "\'u\'", therefore ' 'raw\n' 'formatted strings are possible, but formatted bytes literals are ' 'not.\n' '\n' 'In triple-quoted literals, unescaped newlines and quotes are ' 'allowed\n' '(and are retained), except that three unescaped quotes in a row\n' 'terminate the literal. (A “quote” is the character used to open ' 'the\n' 'literal, i.e. either "\'" or """.)\n' '\n' 'Unless an "\'r\'" or "\'R\'" prefix is present, escape sequences ' 'in string\n' 'and bytes literals are interpreted according to rules similar to ' 'those\n' 'used by Standard C. The recognized escape sequences are:\n' '\n' '+-------------------+-----------------------------------+---------+\n' '| Escape Sequence | Meaning | Notes ' '|\n' '|===================|===================================|=========|\n' '| "\\newline" | Backslash and newline ignored ' '| |\n' '+-------------------+-----------------------------------+---------+\n' '| "\\\\" | Backslash ("\\") ' '| |\n' '+-------------------+-----------------------------------+---------+\n' '| "\\\'" | Single quote ("\'") ' '| |\n' '+-------------------+-----------------------------------+---------+\n' '| "\\"" | Double quote (""") ' '| |\n' '+-------------------+-----------------------------------+---------+\n' '| "\\a" | ASCII Bell (BEL) ' '| |\n' '+-------------------+-----------------------------------+---------+\n' '| "\\b" | ASCII Backspace (BS) ' '| |\n' '+-------------------+-----------------------------------+---------+\n' '| "\\f" | ASCII Formfeed (FF) ' '| |\n' '+-------------------+-----------------------------------+---------+\n' '| "\\n" | ASCII Linefeed (LF) ' '| |\n' '+-------------------+-----------------------------------+---------+\n' '| "\\r" | ASCII Carriage Return (CR) ' '| |\n' '+-------------------+-----------------------------------+---------+\n' '| "\\t" | ASCII Horizontal Tab (TAB) ' '| |\n' '+-------------------+-----------------------------------+---------+\n' '| "\\v" | ASCII Vertical Tab (VT) ' '| |\n' '+-------------------+-----------------------------------+---------+\n' '| "\\ooo" | Character with octal value *ooo* | ' '(1,3) |\n' '+-------------------+-----------------------------------+---------+\n' '| "\\xhh" | Character with hex value *hh* | ' '(2,3) |\n' '+-------------------+-----------------------------------+---------+\n' '\n' 'Escape sequences only recognized in string literals are:\n' '\n' '+-------------------+-----------------------------------+---------+\n' '| Escape Sequence | Meaning | Notes ' '|\n' '|===================|===================================|=========|\n' '| "\\N{name}" | Character named *name* in the | ' '(4) |\n' '| | Unicode database | ' '|\n' '+-------------------+-----------------------------------+---------+\n' '| "\\uxxxx" | Character with 16-bit hex value | ' '(5) |\n' '| | *xxxx* | ' '|\n' '+-------------------+-----------------------------------+---------+\n' '| "\\Uxxxxxxxx" | Character with 32-bit hex value | ' '(6) |\n' '| | *xxxxxxxx* | ' '|\n' '+-------------------+-----------------------------------+---------+\n' '\n' 'Notes:\n' '\n' '1. As in Standard C, up to three octal digits are accepted.\n' '\n' '2. Unlike in Standard C, exactly two hex digits are required.\n' '\n' '3. In a bytes literal, hexadecimal and octal escapes denote the ' 'byte\n' ' with the given value. In a string literal, these escapes ' 'denote a\n' ' Unicode character with the given value.\n' '\n' '4. Changed in version 3.3: Support for name aliases [1] has been\n' ' added.\n' '\n' '5. Exactly four hex digits are required.\n' '\n' '6. Any Unicode character can be encoded this way. Exactly eight ' 'hex\n' ' digits are required.\n' '\n' 'Unlike Standard C, all unrecognized escape sequences are left in ' 'the\n' 'string unchanged, i.e., *the backslash is left in the result*. ' '(This\n' 'behavior is useful when debugging: if an escape sequence is ' 'mistyped,\n' 'the resulting output is more easily recognized as broken.) It is ' 'also\n' 'important to note that the escape sequences only recognized in ' 'string\n' 'literals fall into the category of unrecognized escapes for ' 'bytes\n' 'literals.\n' '\n' ' Changed in version 3.6: Unrecognized escape sequences produce ' 'a\n' ' "DeprecationWarning". In a future Python version they will be ' 'a\n' ' "SyntaxWarning" and eventually a "SyntaxError".\n' '\n' 'Even in a raw literal, quotes can be escaped with a backslash, ' 'but the\n' 'backslash remains in the result; for example, "r"\\""" is a ' 'valid\n' 'string literal consisting of two characters: a backslash and a ' 'double\n' 'quote; "r"\\"" is not a valid string literal (even a raw string ' 'cannot\n' 'end in an odd number of backslashes). Specifically, *a raw ' 'literal\n' 'cannot end in a single backslash* (since the backslash would ' 'escape\n' 'the following quote character). Note also that a single ' 'backslash\n' 'followed by a newline is interpreted as those two characters as ' 'part\n' 'of the literal, *not* as a line continuation.\n', 'subscriptions': 'Subscriptions\n' '*************\n' '\n' 'Subscription of a sequence (string, tuple or list) or ' 'mapping\n' '(dictionary) object usually selects an item from the ' 'collection:\n' '\n' ' subscription ::= primary "[" expression_list "]"\n' '\n' 'The primary must evaluate to an object that supports ' 'subscription\n' '(lists or dictionaries for example). User-defined objects ' 'can support\n' 'subscription by defining a "__getitem__()" method.\n' '\n' 'For built-in objects, there are two types of objects that ' 'support\n' 'subscription:\n' '\n' 'If the primary is a mapping, the expression list must ' 'evaluate to an\n' 'object whose value is one of the keys of the mapping, and ' 'the\n' 'subscription selects the value in the mapping that ' 'corresponds to that\n' 'key. (The expression list is a tuple except if it has ' 'exactly one\n' 'item.)\n' '\n' 'If the primary is a sequence, the expression list must ' 'evaluate to an\n' 'integer or a slice (as discussed in the following ' 'section).\n' '\n' 'The formal syntax makes no special provision for negative ' 'indices in\n' 'sequences; however, built-in sequences all provide a ' '"__getitem__()"\n' 'method that interprets negative indices by adding the ' 'length of the\n' 'sequence to the index (so that "x[-1]" selects the last ' 'item of "x").\n' 'The resulting value must be a nonnegative integer less than ' 'the number\n' 'of items in the sequence, and the subscription selects the ' 'item whose\n' 'index is that value (counting from zero). Since the support ' 'for\n' 'negative indices and slicing occurs in the object’s ' '"__getitem__()"\n' 'method, subclasses overriding this method will need to ' 'explicitly add\n' 'that support.\n' '\n' 'A string’s items are characters. A character is not a ' 'separate data\n' 'type but a string of exactly one character.\n' '\n' 'Subscription of certain *classes* or *types* creates a ' 'generic alias.\n' 'In this case, user-defined classes can support subscription ' 'by\n' 'providing a "__class_getitem__()" classmethod.\n', 'truth': 'Truth Value Testing\n' '*******************\n' '\n' 'Any object can be tested for truth value, for use in an "if" or\n' '"while" condition or as operand of the Boolean operations below.\n' '\n' 'By default, an object is considered true unless its class defines\n' 'either a "__bool__()" method that returns "False" or a "__len__()"\n' 'method that returns zero, when called with the object. [1] Here ' 'are\n' 'most of the built-in objects considered false:\n' '\n' '* constants defined to be false: "None" and "False".\n' '\n' '* zero of any numeric type: "0", "0.0", "0j", "Decimal(0)",\n' ' "Fraction(0, 1)"\n' '\n' '* empty sequences and collections: "\'\'", "()", "[]", "{}", ' '"set()",\n' ' "range(0)"\n' '\n' 'Operations and built-in functions that have a Boolean result ' 'always\n' 'return "0" or "False" for false and "1" or "True" for true, unless\n' 'otherwise stated. (Important exception: the Boolean operations ' '"or"\n' 'and "and" always return one of their operands.)\n', 'try': 'The "try" statement\n' '*******************\n' '\n' 'The "try" statement specifies exception handlers and/or cleanup code\n' 'for a group of statements:\n' '\n' ' try_stmt ::= try1_stmt | try2_stmt\n' ' try1_stmt ::= "try" ":" suite\n' ' ("except" [expression ["as" identifier]] ":" ' 'suite)+\n' ' ["else" ":" suite]\n' ' ["finally" ":" suite]\n' ' try2_stmt ::= "try" ":" suite\n' ' "finally" ":" suite\n' '\n' 'The "except" clause(s) specify one or more exception handlers. When ' 'no\n' 'exception occurs in the "try" clause, no exception handler is\n' 'executed. When an exception occurs in the "try" suite, a search for ' 'an\n' 'exception handler is started. This search inspects the except ' 'clauses\n' 'in turn until one is found that matches the exception. An ' 'expression-\n' 'less except clause, if present, must be last; it matches any\n' 'exception. For an except clause with an expression, that expression\n' 'is evaluated, and the clause matches the exception if the resulting\n' 'object is “compatible” with the exception. An object is compatible\n' 'with an exception if it is the class or a base class of the ' 'exception\n' 'object, or a tuple containing an item that is the class or a base\n' 'class of the exception object.\n' '\n' 'If no except clause matches the exception, the search for an ' 'exception\n' 'handler continues in the surrounding code and on the invocation ' 'stack.\n' '[1]\n' '\n' 'If the evaluation of an expression in the header of an except clause\n' 'raises an exception, the original search for a handler is canceled ' 'and\n' 'a search starts for the new exception in the surrounding code and on\n' 'the call stack (it is treated as if the entire "try" statement ' 'raised\n' 'the exception).\n' '\n' 'When a matching except clause is found, the exception is assigned to\n' 'the target specified after the "as" keyword in that except clause, ' 'if\n' 'present, and the except clause’s suite is executed. All except\n' 'clauses must have an executable block. When the end of this block ' 'is\n' 'reached, execution continues normally after the entire try ' 'statement.\n' '(This means that if two nested handlers exist for the same ' 'exception,\n' 'and the exception occurs in the try clause of the inner handler, the\n' 'outer handler will not handle the exception.)\n' '\n' 'When an exception has been assigned using "as target", it is cleared\n' 'at the end of the except clause. This is as if\n' '\n' ' except E as N:\n' ' foo\n' '\n' 'was translated to\n' '\n' ' except E as N:\n' ' try:\n' ' foo\n' ' finally:\n' ' del N\n' '\n' 'This means the exception must be assigned to a different name to be\n' 'able to refer to it after the except clause. Exceptions are cleared\n' 'because with the traceback attached to them, they form a reference\n' 'cycle with the stack frame, keeping all locals in that frame alive\n' 'until the next garbage collection occurs.\n' '\n' 'Before an except clause’s suite is executed, details about the\n' 'exception are stored in the "sys" module and can be accessed via\n' '"sys.exc_info()". "sys.exc_info()" returns a 3-tuple consisting of ' 'the\n' 'exception class, the exception instance and a traceback object (see\n' 'section The standard type hierarchy) identifying the point in the\n' 'program where the exception occurred. The details about the ' 'exception\n' 'accessed via "sys.exc_info()" are restored to their previous values\n' 'when leaving an exception handler:\n' '\n' ' >>> print(sys.exc_info())\n' ' (None, None, None)\n' ' >>> try:\n' ' ... raise TypeError\n' ' ... except:\n' ' ... print(sys.exc_info())\n' ' ... try:\n' ' ... raise ValueError\n' ' ... except:\n' ' ... print(sys.exc_info())\n' ' ... print(sys.exc_info())\n' ' ...\n' " (<class 'TypeError'>, TypeError(), <traceback object at " '0x10efad080>)\n' " (<class 'ValueError'>, ValueError(), <traceback object at " '0x10efad040>)\n' " (<class 'TypeError'>, TypeError(), <traceback object at " '0x10efad080>)\n' ' >>> print(sys.exc_info())\n' ' (None, None, None)\n' '\n' 'The optional "else" clause is executed if the control flow leaves ' 'the\n' '"try" suite, no exception was raised, and no "return", "continue", ' 'or\n' '"break" statement was executed. Exceptions in the "else" clause are\n' 'not handled by the preceding "except" clauses.\n' '\n' 'If "finally" is present, it specifies a ‘cleanup’ handler. The ' '"try"\n' 'clause is executed, including any "except" and "else" clauses. If ' 'an\n' 'exception occurs in any of the clauses and is not handled, the\n' 'exception is temporarily saved. The "finally" clause is executed. ' 'If\n' 'there is a saved exception it is re-raised at the end of the ' '"finally"\n' 'clause. If the "finally" clause raises another exception, the saved\n' 'exception is set as the context of the new exception. If the ' '"finally"\n' 'clause executes a "return", "break" or "continue" statement, the ' 'saved\n' 'exception is discarded:\n' '\n' ' >>> def f():\n' ' ... try:\n' ' ... 1/0\n' ' ... finally:\n' ' ... return 42\n' ' ...\n' ' >>> f()\n' ' 42\n' '\n' 'The exception information is not available to the program during\n' 'execution of the "finally" clause.\n' '\n' 'When a "return", "break" or "continue" statement is executed in the\n' '"try" suite of a "try"…"finally" statement, the "finally" clause is\n' 'also executed ‘on the way out.’\n' '\n' 'The return value of a function is determined by the last "return"\n' 'statement executed. Since the "finally" clause always executes, a\n' '"return" statement executed in the "finally" clause will always be ' 'the\n' 'last one executed:\n' '\n' ' >>> def foo():\n' ' ... try:\n' " ... return 'try'\n" ' ... finally:\n' " ... return 'finally'\n" ' ...\n' ' >>> foo()\n' " 'finally'\n" '\n' 'Additional information on exceptions can be found in section\n' 'Exceptions, and information on using the "raise" statement to ' 'generate\n' 'exceptions may be found in section The raise statement.\n' '\n' 'Changed in version 3.8: Prior to Python 3.8, a "continue" statement\n' 'was illegal in the "finally" clause due to a problem with the\n' 'implementation.\n', 'types': 'The standard type hierarchy\n' '***************************\n' '\n' 'Below is a list of the types that are built into Python. ' 'Extension\n' 'modules (written in C, Java, or other languages, depending on the\n' 'implementation) can define additional types. Future versions of\n' 'Python may add types to the type hierarchy (e.g., rational ' 'numbers,\n' 'efficiently stored arrays of integers, etc.), although such ' 'additions\n' 'will often be provided via the standard library instead.\n' '\n' 'Some of the type descriptions below contain a paragraph listing\n' '‘special attributes.’ These are attributes that provide access to ' 'the\n' 'implementation and are not intended for general use. Their ' 'definition\n' 'may change in the future.\n' '\n' 'None\n' ' This type has a single value. There is a single object with ' 'this\n' ' value. This object is accessed through the built-in name "None". ' 'It\n' ' is used to signify the absence of a value in many situations, ' 'e.g.,\n' ' it is returned from functions that don’t explicitly return\n' ' anything. Its truth value is false.\n' '\n' 'NotImplemented\n' ' This type has a single value. There is a single object with ' 'this\n' ' value. This object is accessed through the built-in name\n' ' "NotImplemented". Numeric methods and rich comparison methods\n' ' should return this value if they do not implement the operation ' 'for\n' ' the operands provided. (The interpreter will then try the\n' ' reflected operation, or some other fallback, depending on the\n' ' operator.) It should not be evaluated in a boolean context.\n' '\n' ' See Implementing the arithmetic operations for more details.\n' '\n' ' Changed in version 3.9: Evaluating "NotImplemented" in a ' 'boolean\n' ' context is deprecated. While it currently evaluates as true, it\n' ' will emit a "DeprecationWarning". It will raise a "TypeError" in ' 'a\n' ' future version of Python.\n' '\n' 'Ellipsis\n' ' This type has a single value. There is a single object with ' 'this\n' ' value. This object is accessed through the literal "..." or the\n' ' built-in name "Ellipsis". Its truth value is true.\n' '\n' '"numbers.Number"\n' ' These are created by numeric literals and returned as results ' 'by\n' ' arithmetic operators and arithmetic built-in functions. ' 'Numeric\n' ' objects are immutable; once created their value never changes.\n' ' Python numbers are of course strongly related to mathematical\n' ' numbers, but subject to the limitations of numerical ' 'representation\n' ' in computers.\n' '\n' ' The string representations of the numeric classes, computed by\n' ' "__repr__()" and "__str__()", have the following properties:\n' '\n' ' * They are valid numeric literals which, when passed to their ' 'class\n' ' constructor, produce an object having the value of the ' 'original\n' ' numeric.\n' '\n' ' * The representation is in base 10, when possible.\n' '\n' ' * Leading zeros, possibly excepting a single zero before a ' 'decimal\n' ' point, are not shown.\n' '\n' ' * Trailing zeros, possibly excepting a single zero after a ' 'decimal\n' ' point, are not shown.\n' '\n' ' * A sign is shown only when the number is negative.\n' '\n' ' Python distinguishes between integers, floating point numbers, ' 'and\n' ' complex numbers:\n' '\n' ' "numbers.Integral"\n' ' These represent elements from the mathematical set of ' 'integers\n' ' (positive and negative).\n' '\n' ' There are two types of integers:\n' '\n' ' Integers ("int")\n' ' These represent numbers in an unlimited range, subject to\n' ' available (virtual) memory only. For the purpose of ' 'shift\n' ' and mask operations, a binary representation is assumed, ' 'and\n' ' negative numbers are represented in a variant of 2’s\n' ' complement which gives the illusion of an infinite string ' 'of\n' ' sign bits extending to the left.\n' '\n' ' Booleans ("bool")\n' ' These represent the truth values False and True. The two\n' ' objects representing the values "False" and "True" are ' 'the\n' ' only Boolean objects. The Boolean type is a subtype of ' 'the\n' ' integer type, and Boolean values behave like the values 0 ' 'and\n' ' 1, respectively, in almost all contexts, the exception ' 'being\n' ' that when converted to a string, the strings ""False"" or\n' ' ""True"" are returned, respectively.\n' '\n' ' The rules for integer representation are intended to give ' 'the\n' ' most meaningful interpretation of shift and mask operations\n' ' involving negative integers.\n' '\n' ' "numbers.Real" ("float")\n' ' These represent machine-level double precision floating ' 'point\n' ' numbers. You are at the mercy of the underlying machine\n' ' architecture (and C or Java implementation) for the accepted\n' ' range and handling of overflow. Python does not support ' 'single-\n' ' precision floating point numbers; the savings in processor ' 'and\n' ' memory usage that are usually the reason for using these are\n' ' dwarfed by the overhead of using objects in Python, so there ' 'is\n' ' no reason to complicate the language with two kinds of ' 'floating\n' ' point numbers.\n' '\n' ' "numbers.Complex" ("complex")\n' ' These represent complex numbers as a pair of machine-level\n' ' double precision floating point numbers. The same caveats ' 'apply\n' ' as for floating point numbers. The real and imaginary parts ' 'of a\n' ' complex number "z" can be retrieved through the read-only\n' ' attributes "z.real" and "z.imag".\n' '\n' 'Sequences\n' ' These represent finite ordered sets indexed by non-negative\n' ' numbers. The built-in function "len()" returns the number of ' 'items\n' ' of a sequence. When the length of a sequence is *n*, the index ' 'set\n' ' contains the numbers 0, 1, …, *n*-1. Item *i* of sequence *a* ' 'is\n' ' selected by "a[i]".\n' '\n' ' Sequences also support slicing: "a[i:j]" selects all items with\n' ' index *k* such that *i* "<=" *k* "<" *j*. When used as an\n' ' expression, a slice is a sequence of the same type. This ' 'implies\n' ' that the index set is renumbered so that it starts at 0.\n' '\n' ' Some sequences also support “extended slicing” with a third ' '“step”\n' ' parameter: "a[i:j:k]" selects all items of *a* with index *x* ' 'where\n' ' "x = i + n*k", *n* ">=" "0" and *i* "<=" *x* "<" *j*.\n' '\n' ' Sequences are distinguished according to their mutability:\n' '\n' ' Immutable sequences\n' ' An object of an immutable sequence type cannot change once it ' 'is\n' ' created. (If the object contains references to other ' 'objects,\n' ' these other objects may be mutable and may be changed; ' 'however,\n' ' the collection of objects directly referenced by an ' 'immutable\n' ' object cannot change.)\n' '\n' ' The following types are immutable sequences:\n' '\n' ' Strings\n' ' A string is a sequence of values that represent Unicode ' 'code\n' ' points. All the code points in the range "U+0000 - ' 'U+10FFFF"\n' ' can be represented in a string. Python doesn’t have a ' '*char*\n' ' type; instead, every code point in the string is ' 'represented\n' ' as a string object with length "1". The built-in ' 'function\n' ' "ord()" converts a code point from its string form to an\n' ' integer in the range "0 - 10FFFF"; "chr()" converts an\n' ' integer in the range "0 - 10FFFF" to the corresponding ' 'length\n' ' "1" string object. "str.encode()" can be used to convert ' 'a\n' ' "str" to "bytes" using the given text encoding, and\n' ' "bytes.decode()" can be used to achieve the opposite.\n' '\n' ' Tuples\n' ' The items of a tuple are arbitrary Python objects. Tuples ' 'of\n' ' two or more items are formed by comma-separated lists of\n' ' expressions. A tuple of one item (a ‘singleton’) can be\n' ' formed by affixing a comma to an expression (an expression ' 'by\n' ' itself does not create a tuple, since parentheses must be\n' ' usable for grouping of expressions). An empty tuple can ' 'be\n' ' formed by an empty pair of parentheses.\n' '\n' ' Bytes\n' ' A bytes object is an immutable array. The items are ' '8-bit\n' ' bytes, represented by integers in the range 0 <= x < 256.\n' ' Bytes literals (like "b\'abc\'") and the built-in ' '"bytes()"\n' ' constructor can be used to create bytes objects. Also, ' 'bytes\n' ' objects can be decoded to strings via the "decode()" ' 'method.\n' '\n' ' Mutable sequences\n' ' Mutable sequences can be changed after they are created. ' 'The\n' ' subscription and slicing notations can be used as the target ' 'of\n' ' assignment and "del" (delete) statements.\n' '\n' ' There are currently two intrinsic mutable sequence types:\n' '\n' ' Lists\n' ' The items of a list are arbitrary Python objects. Lists ' 'are\n' ' formed by placing a comma-separated list of expressions ' 'in\n' ' square brackets. (Note that there are no special cases ' 'needed\n' ' to form lists of length 0 or 1.)\n' '\n' ' Byte Arrays\n' ' A bytearray object is a mutable array. They are created ' 'by\n' ' the built-in "bytearray()" constructor. Aside from being\n' ' mutable (and hence unhashable), byte arrays otherwise ' 'provide\n' ' the same interface and functionality as immutable "bytes"\n' ' objects.\n' '\n' ' The extension module "array" provides an additional example ' 'of a\n' ' mutable sequence type, as does the "collections" module.\n' '\n' 'Set types\n' ' These represent unordered, finite sets of unique, immutable\n' ' objects. As such, they cannot be indexed by any subscript. ' 'However,\n' ' they can be iterated over, and the built-in function "len()"\n' ' returns the number of items in a set. Common uses for sets are ' 'fast\n' ' membership testing, removing duplicates from a sequence, and\n' ' computing mathematical operations such as intersection, union,\n' ' difference, and symmetric difference.\n' '\n' ' For set elements, the same immutability rules apply as for\n' ' dictionary keys. Note that numeric types obey the normal rules ' 'for\n' ' numeric comparison: if two numbers compare equal (e.g., "1" and\n' ' "1.0"), only one of them can be contained in a set.\n' '\n' ' There are currently two intrinsic set types:\n' '\n' ' Sets\n' ' These represent a mutable set. They are created by the ' 'built-in\n' ' "set()" constructor and can be modified afterwards by ' 'several\n' ' methods, such as "add()".\n' '\n' ' Frozen sets\n' ' These represent an immutable set. They are created by the\n' ' built-in "frozenset()" constructor. As a frozenset is ' 'immutable\n' ' and *hashable*, it can be used again as an element of ' 'another\n' ' set, or as a dictionary key.\n' '\n' 'Mappings\n' ' These represent finite sets of objects indexed by arbitrary ' 'index\n' ' sets. The subscript notation "a[k]" selects the item indexed by ' '"k"\n' ' from the mapping "a"; this can be used in expressions and as ' 'the\n' ' target of assignments or "del" statements. The built-in ' 'function\n' ' "len()" returns the number of items in a mapping.\n' '\n' ' There is currently a single intrinsic mapping type:\n' '\n' ' Dictionaries\n' ' These represent finite sets of objects indexed by nearly\n' ' arbitrary values. The only types of values not acceptable ' 'as\n' ' keys are values containing lists or dictionaries or other\n' ' mutable types that are compared by value rather than by ' 'object\n' ' identity, the reason being that the efficient implementation ' 'of\n' ' dictionaries requires a key’s hash value to remain constant.\n' ' Numeric types used for keys obey the normal rules for ' 'numeric\n' ' comparison: if two numbers compare equal (e.g., "1" and ' '"1.0")\n' ' then they can be used interchangeably to index the same\n' ' dictionary entry.\n' '\n' ' Dictionaries preserve insertion order, meaning that keys will ' 'be\n' ' produced in the same order they were added sequentially over ' 'the\n' ' dictionary. Replacing an existing key does not change the ' 'order,\n' ' however removing a key and re-inserting it will add it to ' 'the\n' ' end instead of keeping its old place.\n' '\n' ' Dictionaries are mutable; they can be created by the "{...}"\n' ' notation (see section Dictionary displays).\n' '\n' ' The extension modules "dbm.ndbm" and "dbm.gnu" provide\n' ' additional examples of mapping types, as does the ' '"collections"\n' ' module.\n' '\n' ' Changed in version 3.7: Dictionaries did not preserve ' 'insertion\n' ' order in versions of Python before 3.6. In CPython 3.6,\n' ' insertion order was preserved, but it was considered an\n' ' implementation detail at that time rather than a language\n' ' guarantee.\n' '\n' 'Callable types\n' ' These are the types to which the function call operation (see\n' ' section Calls) can be applied:\n' '\n' ' User-defined functions\n' ' A user-defined function object is created by a function\n' ' definition (see section Function definitions). It should be\n' ' called with an argument list containing the same number of ' 'items\n' ' as the function’s formal parameter list.\n' '\n' ' Special attributes:\n' '\n' ' ' '+---------------------------+---------------------------------+-------------+\n' ' | Attribute | Meaning ' '| |\n' ' ' '|===========================|=================================|=============|\n' ' | "__doc__" | The function’s documentation ' '| Writable |\n' ' | | string, or "None" if ' '| |\n' ' | | unavailable; not inherited by ' '| |\n' ' | | subclasses. ' '| |\n' ' ' '+---------------------------+---------------------------------+-------------+\n' ' | "__name__" | The function’s name. ' '| Writable |\n' ' ' '+---------------------------+---------------------------------+-------------+\n' ' | "__qualname__" | The function’s *qualified ' '| Writable |\n' ' | | name*. New in version 3.3. ' '| |\n' ' ' '+---------------------------+---------------------------------+-------------+\n' ' | "__module__" | The name of the module the ' '| Writable |\n' ' | | function was defined in, or ' '| |\n' ' | | "None" if unavailable. ' '| |\n' ' ' '+---------------------------+---------------------------------+-------------+\n' ' | "__defaults__" | A tuple containing default ' '| Writable |\n' ' | | argument values for those ' '| |\n' ' | | arguments that have defaults, ' '| |\n' ' | | or "None" if no arguments have ' '| |\n' ' | | a default value. ' '| |\n' ' ' '+---------------------------+---------------------------------+-------------+\n' ' | "__code__" | The code object representing ' '| Writable |\n' ' | | the compiled function body. ' '| |\n' ' ' '+---------------------------+---------------------------------+-------------+\n' ' | "__globals__" | A reference to the dictionary ' '| Read-only |\n' ' | | that holds the function’s ' '| |\n' ' | | global variables — the global ' '| |\n' ' | | namespace of the module in ' '| |\n' ' | | which the function was defined. ' '| |\n' ' ' '+---------------------------+---------------------------------+-------------+\n' ' | "__dict__" | The namespace supporting ' '| Writable |\n' ' | | arbitrary function attributes. ' '| |\n' ' ' '+---------------------------+---------------------------------+-------------+\n' ' | "__closure__" | "None" or a tuple of cells that ' '| Read-only |\n' ' | | contain bindings for the ' '| |\n' ' | | function’s free variables. See ' '| |\n' ' | | below for information on the ' '| |\n' ' | | "cell_contents" attribute. ' '| |\n' ' ' '+---------------------------+---------------------------------+-------------+\n' ' | "__annotations__" | A dict containing annotations ' '| Writable |\n' ' | | of parameters. The keys of the ' '| |\n' ' | | dict are the parameter names, ' '| |\n' ' | | and "\'return\'" for the ' 'return | |\n' ' | | annotation, if provided. ' '| |\n' ' ' '+---------------------------+---------------------------------+-------------+\n' ' | "__kwdefaults__" | A dict containing defaults for ' '| Writable |\n' ' | | keyword-only parameters. ' '| |\n' ' ' '+---------------------------+---------------------------------+-------------+\n' '\n' ' Most of the attributes labelled “Writable” check the type of ' 'the\n' ' assigned value.\n' '\n' ' Function objects also support getting and setting arbitrary\n' ' attributes, which can be used, for example, to attach ' 'metadata\n' ' to functions. Regular attribute dot-notation is used to get ' 'and\n' ' set such attributes. *Note that the current implementation ' 'only\n' ' supports function attributes on user-defined functions. ' 'Function\n' ' attributes on built-in functions may be supported in the\n' ' future.*\n' '\n' ' A cell object has the attribute "cell_contents". This can be\n' ' used to get the value of the cell, as well as set the value.\n' '\n' ' Additional information about a function’s definition can be\n' ' retrieved from its code object; see the description of ' 'internal\n' ' types below. The "cell" type can be accessed in the "types"\n' ' module.\n' '\n' ' Instance methods\n' ' An instance method object combines a class, a class instance ' 'and\n' ' any callable object (normally a user-defined function).\n' '\n' ' Special read-only attributes: "__self__" is the class ' 'instance\n' ' object, "__func__" is the function object; "__doc__" is the\n' ' method’s documentation (same as "__func__.__doc__"); ' '"__name__"\n' ' is the method name (same as "__func__.__name__"); ' '"__module__"\n' ' is the name of the module the method was defined in, or ' '"None"\n' ' if unavailable.\n' '\n' ' Methods also support accessing (but not setting) the ' 'arbitrary\n' ' function attributes on the underlying function object.\n' '\n' ' User-defined method objects may be created when getting an\n' ' attribute of a class (perhaps via an instance of that class), ' 'if\n' ' that attribute is a user-defined function object or a class\n' ' method object.\n' '\n' ' When an instance method object is created by retrieving a ' 'user-\n' ' defined function object from a class via one of its ' 'instances,\n' ' its "__self__" attribute is the instance, and the method ' 'object\n' ' is said to be bound. The new method’s "__func__" attribute ' 'is\n' ' the original function object.\n' '\n' ' When an instance method object is created by retrieving a ' 'class\n' ' method object from a class or instance, its "__self__" ' 'attribute\n' ' is the class itself, and its "__func__" attribute is the\n' ' function object underlying the class method.\n' '\n' ' When an instance method object is called, the underlying\n' ' function ("__func__") is called, inserting the class ' 'instance\n' ' ("__self__") in front of the argument list. For instance, ' 'when\n' ' "C" is a class which contains a definition for a function ' '"f()",\n' ' and "x" is an instance of "C", calling "x.f(1)" is equivalent ' 'to\n' ' calling "C.f(x, 1)".\n' '\n' ' When an instance method object is derived from a class ' 'method\n' ' object, the “class instance” stored in "__self__" will ' 'actually\n' ' be the class itself, so that calling either "x.f(1)" or ' '"C.f(1)"\n' ' is equivalent to calling "f(C,1)" where "f" is the ' 'underlying\n' ' function.\n' '\n' ' Note that the transformation from function object to ' 'instance\n' ' method object happens each time the attribute is retrieved ' 'from\n' ' the instance. In some cases, a fruitful optimization is to\n' ' assign the attribute to a local variable and call that local\n' ' variable. Also notice that this transformation only happens ' 'for\n' ' user-defined functions; other callable objects (and all non-\n' ' callable objects) are retrieved without transformation. It ' 'is\n' ' also important to note that user-defined functions which are\n' ' attributes of a class instance are not converted to bound\n' ' methods; this *only* happens when the function is an ' 'attribute\n' ' of the class.\n' '\n' ' Generator functions\n' ' A function or method which uses the "yield" statement (see\n' ' section The yield statement) is called a *generator ' 'function*.\n' ' Such a function, when called, always returns an iterator ' 'object\n' ' which can be used to execute the body of the function: ' 'calling\n' ' the iterator’s "iterator.__next__()" method will cause the\n' ' function to execute until it provides a value using the ' '"yield"\n' ' statement. When the function executes a "return" statement ' 'or\n' ' falls off the end, a "StopIteration" exception is raised and ' 'the\n' ' iterator will have reached the end of the set of values to ' 'be\n' ' returned.\n' '\n' ' Coroutine functions\n' ' A function or method which is defined using "async def" is\n' ' called a *coroutine function*. Such a function, when ' 'called,\n' ' returns a *coroutine* object. It may contain "await"\n' ' expressions, as well as "async with" and "async for" ' 'statements.\n' ' See also the Coroutine Objects section.\n' '\n' ' Asynchronous generator functions\n' ' A function or method which is defined using "async def" and\n' ' which uses the "yield" statement is called a *asynchronous\n' ' generator function*. Such a function, when called, returns ' 'an\n' ' asynchronous iterator object which can be used in an "async ' 'for"\n' ' statement to execute the body of the function.\n' '\n' ' Calling the asynchronous iterator’s "aiterator.__anext__()"\n' ' method will return an *awaitable* which when awaited will\n' ' execute until it provides a value using the "yield" ' 'expression.\n' ' When the function executes an empty "return" statement or ' 'falls\n' ' off the end, a "StopAsyncIteration" exception is raised and ' 'the\n' ' asynchronous iterator will have reached the end of the set ' 'of\n' ' values to be yielded.\n' '\n' ' Built-in functions\n' ' A built-in function object is a wrapper around a C function.\n' ' Examples of built-in functions are "len()" and "math.sin()"\n' ' ("math" is a standard built-in module). The number and type ' 'of\n' ' the arguments are determined by the C function. Special ' 'read-\n' ' only attributes: "__doc__" is the function’s documentation\n' ' string, or "None" if unavailable; "__name__" is the ' 'function’s\n' ' name; "__self__" is set to "None" (but see the next item);\n' ' "__module__" is the name of the module the function was ' 'defined\n' ' in or "None" if unavailable.\n' '\n' ' Built-in methods\n' ' This is really a different disguise of a built-in function, ' 'this\n' ' time containing an object passed to the C function as an\n' ' implicit extra argument. An example of a built-in method is\n' ' "alist.append()", assuming *alist* is a list object. In this\n' ' case, the special read-only attribute "__self__" is set to ' 'the\n' ' object denoted by *alist*.\n' '\n' ' Classes\n' ' Classes are callable. These objects normally act as ' 'factories\n' ' for new instances of themselves, but variations are possible ' 'for\n' ' class types that override "__new__()". The arguments of the\n' ' call are passed to "__new__()" and, in the typical case, to\n' ' "__init__()" to initialize the new instance.\n' '\n' ' Class Instances\n' ' Instances of arbitrary classes can be made callable by ' 'defining\n' ' a "__call__()" method in their class.\n' '\n' 'Modules\n' ' Modules are a basic organizational unit of Python code, and are\n' ' created by the import system as invoked either by the "import"\n' ' statement, or by calling functions such as\n' ' "importlib.import_module()" and built-in "__import__()". A ' 'module\n' ' object has a namespace implemented by a dictionary object (this ' 'is\n' ' the dictionary referenced by the "__globals__" attribute of\n' ' functions defined in the module). Attribute references are\n' ' translated to lookups in this dictionary, e.g., "m.x" is ' 'equivalent\n' ' to "m.__dict__["x"]". A module object does not contain the code\n' ' object used to initialize the module (since it isn’t needed ' 'once\n' ' the initialization is done).\n' '\n' ' Attribute assignment updates the module’s namespace dictionary,\n' ' e.g., "m.x = 1" is equivalent to "m.__dict__["x"] = 1".\n' '\n' ' Predefined (writable) attributes: "__name__" is the module’s ' 'name;\n' ' "__doc__" is the module’s documentation string, or "None" if\n' ' unavailable; "__annotations__" (optional) is a dictionary\n' ' containing *variable annotations* collected during module body\n' ' execution; "__file__" is the pathname of the file from which ' 'the\n' ' module was loaded, if it was loaded from a file. The "__file__"\n' ' attribute may be missing for certain types of modules, such as ' 'C\n' ' modules that are statically linked into the interpreter; for\n' ' extension modules loaded dynamically from a shared library, it ' 'is\n' ' the pathname of the shared library file.\n' '\n' ' Special read-only attribute: "__dict__" is the module’s ' 'namespace\n' ' as a dictionary object.\n' '\n' ' **CPython implementation detail:** Because of the way CPython\n' ' clears module dictionaries, the module dictionary will be ' 'cleared\n' ' when the module falls out of scope even if the dictionary still ' 'has\n' ' live references. To avoid this, copy the dictionary or keep ' 'the\n' ' module around while using its dictionary directly.\n' '\n' 'Custom classes\n' ' Custom class types are typically created by class definitions ' '(see\n' ' section Class definitions). A class has a namespace implemented ' 'by\n' ' a dictionary object. Class attribute references are translated ' 'to\n' ' lookups in this dictionary, e.g., "C.x" is translated to\n' ' "C.__dict__["x"]" (although there are a number of hooks which ' 'allow\n' ' for other means of locating attributes). When the attribute name ' 'is\n' ' not found there, the attribute search continues in the base\n' ' classes. This search of the base classes uses the C3 method\n' ' resolution order which behaves correctly even in the presence ' 'of\n' ' ‘diamond’ inheritance structures where there are multiple\n' ' inheritance paths leading back to a common ancestor. Additional\n' ' details on the C3 MRO used by Python can be found in the\n' ' documentation accompanying the 2.3 release at\n' ' https://www.python.org/download/releases/2.3/mro/.\n' '\n' ' When a class attribute reference (for class "C", say) would ' 'yield a\n' ' class method object, it is transformed into an instance method\n' ' object whose "__self__" attribute is "C". When it would yield ' 'a\n' ' static method object, it is transformed into the object wrapped ' 'by\n' ' the static method object. See section Implementing Descriptors ' 'for\n' ' another way in which attributes retrieved from a class may ' 'differ\n' ' from those actually contained in its "__dict__".\n' '\n' ' Class attribute assignments update the class’s dictionary, ' 'never\n' ' the dictionary of a base class.\n' '\n' ' A class object can be called (see above) to yield a class ' 'instance\n' ' (see below).\n' '\n' ' Special attributes: "__name__" is the class name; "__module__" ' 'is\n' ' the module name in which the class was defined; "__dict__" is ' 'the\n' ' dictionary containing the class’s namespace; "__bases__" is a ' 'tuple\n' ' containing the base classes, in the order of their occurrence ' 'in\n' ' the base class list; "__doc__" is the class’s documentation ' 'string,\n' ' or "None" if undefined; "__annotations__" (optional) is a\n' ' dictionary containing *variable annotations* collected during ' 'class\n' ' body execution.\n' '\n' 'Class instances\n' ' A class instance is created by calling a class object (see ' 'above).\n' ' A class instance has a namespace implemented as a dictionary ' 'which\n' ' is the first place in which attribute references are searched.\n' ' When an attribute is not found there, and the instance’s class ' 'has\n' ' an attribute by that name, the search continues with the class\n' ' attributes. If a class attribute is found that is a ' 'user-defined\n' ' function object, it is transformed into an instance method ' 'object\n' ' whose "__self__" attribute is the instance. Static method and\n' ' class method objects are also transformed; see above under\n' ' “Classes”. See section Implementing Descriptors for another way ' 'in\n' ' which attributes of a class retrieved via its instances may ' 'differ\n' ' from the objects actually stored in the class’s "__dict__". If ' 'no\n' ' class attribute is found, and the object’s class has a\n' ' "__getattr__()" method, that is called to satisfy the lookup.\n' '\n' ' Attribute assignments and deletions update the instance’s\n' ' dictionary, never a class’s dictionary. If the class has a\n' ' "__setattr__()" or "__delattr__()" method, this is called ' 'instead\n' ' of updating the instance dictionary directly.\n' '\n' ' Class instances can pretend to be numbers, sequences, or ' 'mappings\n' ' if they have methods with certain special names. See section\n' ' Special method names.\n' '\n' ' Special attributes: "__dict__" is the attribute dictionary;\n' ' "__class__" is the instance’s class.\n' '\n' 'I/O objects (also known as file objects)\n' ' A *file object* represents an open file. Various shortcuts are\n' ' available to create file objects: the "open()" built-in ' 'function,\n' ' and also "os.popen()", "os.fdopen()", and the "makefile()" ' 'method\n' ' of socket objects (and perhaps by other functions or methods\n' ' provided by extension modules).\n' '\n' ' The objects "sys.stdin", "sys.stdout" and "sys.stderr" are\n' ' initialized to file objects corresponding to the interpreter’s\n' ' standard input, output and error streams; they are all open in ' 'text\n' ' mode and therefore follow the interface defined by the\n' ' "io.TextIOBase" abstract class.\n' '\n' 'Internal types\n' ' A few types used internally by the interpreter are exposed to ' 'the\n' ' user. Their definitions may change with future versions of the\n' ' interpreter, but they are mentioned here for completeness.\n' '\n' ' Code objects\n' ' Code objects represent *byte-compiled* executable Python ' 'code,\n' ' or *bytecode*. The difference between a code object and a\n' ' function object is that the function object contains an ' 'explicit\n' ' reference to the function’s globals (the module in which it ' 'was\n' ' defined), while a code object contains no context; also the\n' ' default argument values are stored in the function object, ' 'not\n' ' in the code object (because they represent values calculated ' 'at\n' ' run-time). Unlike function objects, code objects are ' 'immutable\n' ' and contain no references (directly or indirectly) to ' 'mutable\n' ' objects.\n' '\n' ' Special read-only attributes: "co_name" gives the function ' 'name;\n' ' "co_argcount" is the total number of positional arguments\n' ' (including positional-only arguments and arguments with ' 'default\n' ' values); "co_posonlyargcount" is the number of ' 'positional-only\n' ' arguments (including arguments with default values);\n' ' "co_kwonlyargcount" is the number of keyword-only arguments\n' ' (including arguments with default values); "co_nlocals" is ' 'the\n' ' number of local variables used by the function (including\n' ' arguments); "co_varnames" is a tuple containing the names of ' 'the\n' ' local variables (starting with the argument names);\n' ' "co_cellvars" is a tuple containing the names of local ' 'variables\n' ' that are referenced by nested functions; "co_freevars" is a\n' ' tuple containing the names of free variables; "co_code" is a\n' ' string representing the sequence of bytecode instructions;\n' ' "co_consts" is a tuple containing the literals used by the\n' ' bytecode; "co_names" is a tuple containing the names used by ' 'the\n' ' bytecode; "co_filename" is the filename from which the code ' 'was\n' ' compiled; "co_firstlineno" is the first line number of the\n' ' function; "co_lnotab" is a string encoding the mapping from\n' ' bytecode offsets to line numbers (for details see the source\n' ' code of the interpreter); "co_stacksize" is the required ' 'stack\n' ' size; "co_flags" is an integer encoding a number of flags ' 'for\n' ' the interpreter.\n' '\n' ' The following flag bits are defined for "co_flags": bit ' '"0x04"\n' ' is set if the function uses the "*arguments" syntax to accept ' 'an\n' ' arbitrary number of positional arguments; bit "0x08" is set ' 'if\n' ' the function uses the "**keywords" syntax to accept ' 'arbitrary\n' ' keyword arguments; bit "0x20" is set if the function is a\n' ' generator.\n' '\n' ' Future feature declarations ("from __future__ import ' 'division")\n' ' also use bits in "co_flags" to indicate whether a code ' 'object\n' ' was compiled with a particular feature enabled: bit "0x2000" ' 'is\n' ' set if the function was compiled with future division ' 'enabled;\n' ' bits "0x10" and "0x1000" were used in earlier versions of\n' ' Python.\n' '\n' ' Other bits in "co_flags" are reserved for internal use.\n' '\n' ' If a code object represents a function, the first item in\n' ' "co_consts" is the documentation string of the function, or\n' ' "None" if undefined.\n' '\n' ' Frame objects\n' ' Frame objects represent execution frames. They may occur in\n' ' traceback objects (see below), and are also passed to ' 'registered\n' ' trace functions.\n' '\n' ' Special read-only attributes: "f_back" is to the previous ' 'stack\n' ' frame (towards the caller), or "None" if this is the bottom\n' ' stack frame; "f_code" is the code object being executed in ' 'this\n' ' frame; "f_locals" is the dictionary used to look up local\n' ' variables; "f_globals" is used for global variables;\n' ' "f_builtins" is used for built-in (intrinsic) names; ' '"f_lasti"\n' ' gives the precise instruction (this is an index into the\n' ' bytecode string of the code object).\n' '\n' ' Special writable attributes: "f_trace", if not "None", is a\n' ' function called for various events during code execution ' '(this\n' ' is used by the debugger). Normally an event is triggered for\n' ' each new source line - this can be disabled by setting\n' ' "f_trace_lines" to "False".\n' '\n' ' Implementations *may* allow per-opcode events to be requested ' 'by\n' ' setting "f_trace_opcodes" to "True". Note that this may lead ' 'to\n' ' undefined interpreter behaviour if exceptions raised by the\n' ' trace function escape to the function being traced.\n' '\n' ' "f_lineno" is the current line number of the frame — writing ' 'to\n' ' this from within a trace function jumps to the given line ' '(only\n' ' for the bottom-most frame). A debugger can implement a Jump\n' ' command (aka Set Next Statement) by writing to f_lineno.\n' '\n' ' Frame objects support one method:\n' '\n' ' frame.clear()\n' '\n' ' This method clears all references to local variables held ' 'by\n' ' the frame. Also, if the frame belonged to a generator, ' 'the\n' ' generator is finalized. This helps break reference ' 'cycles\n' ' involving frame objects (for example when catching an\n' ' exception and storing its traceback for later use).\n' '\n' ' "RuntimeError" is raised if the frame is currently ' 'executing.\n' '\n' ' New in version 3.4.\n' '\n' ' Traceback objects\n' ' Traceback objects represent a stack trace of an exception. ' 'A\n' ' traceback object is implicitly created when an exception ' 'occurs,\n' ' and may also be explicitly created by calling\n' ' "types.TracebackType".\n' '\n' ' For implicitly created tracebacks, when the search for an\n' ' exception handler unwinds the execution stack, at each ' 'unwound\n' ' level a traceback object is inserted in front of the current\n' ' traceback. When an exception handler is entered, the stack\n' ' trace is made available to the program. (See section The try\n' ' statement.) It is accessible as the third item of the tuple\n' ' returned by "sys.exc_info()", and as the "__traceback__"\n' ' attribute of the caught exception.\n' '\n' ' When the program contains no suitable handler, the stack ' 'trace\n' ' is written (nicely formatted) to the standard error stream; ' 'if\n' ' the interpreter is interactive, it is also made available to ' 'the\n' ' user as "sys.last_traceback".\n' '\n' ' For explicitly created tracebacks, it is up to the creator ' 'of\n' ' the traceback to determine how the "tb_next" attributes ' 'should\n' ' be linked to form a full stack trace.\n' '\n' ' Special read-only attributes: "tb_frame" points to the ' 'execution\n' ' frame of the current level; "tb_lineno" gives the line ' 'number\n' ' where the exception occurred; "tb_lasti" indicates the ' 'precise\n' ' instruction. The line number and last instruction in the\n' ' traceback may differ from the line number of its frame object ' 'if\n' ' the exception occurred in a "try" statement with no matching\n' ' except clause or with a finally clause.\n' '\n' ' Special writable attribute: "tb_next" is the next level in ' 'the\n' ' stack trace (towards the frame where the exception occurred), ' 'or\n' ' "None" if there is no next level.\n' '\n' ' Changed in version 3.7: Traceback objects can now be ' 'explicitly\n' ' instantiated from Python code, and the "tb_next" attribute ' 'of\n' ' existing instances can be updated.\n' '\n' ' Slice objects\n' ' Slice objects are used to represent slices for ' '"__getitem__()"\n' ' methods. They are also created by the built-in "slice()"\n' ' function.\n' '\n' ' Special read-only attributes: "start" is the lower bound; ' '"stop"\n' ' is the upper bound; "step" is the step value; each is "None" ' 'if\n' ' omitted. These attributes can have any type.\n' '\n' ' Slice objects support one method:\n' '\n' ' slice.indices(self, length)\n' '\n' ' This method takes a single integer argument *length* and\n' ' computes information about the slice that the slice ' 'object\n' ' would describe if applied to a sequence of *length* ' 'items.\n' ' It returns a tuple of three integers; respectively these ' 'are\n' ' the *start* and *stop* indices and the *step* or stride\n' ' length of the slice. Missing or out-of-bounds indices are\n' ' handled in a manner consistent with regular slices.\n' '\n' ' Static method objects\n' ' Static method objects provide a way of defeating the\n' ' transformation of function objects to method objects ' 'described\n' ' above. A static method object is a wrapper around any other\n' ' object, usually a user-defined method object. When a static\n' ' method object is retrieved from a class or a class instance, ' 'the\n' ' object actually returned is the wrapped object, which is not\n' ' subject to any further transformation. Static method objects ' 'are\n' ' not themselves callable, although the objects they wrap ' 'usually\n' ' are. Static method objects are created by the built-in\n' ' "staticmethod()" constructor.\n' '\n' ' Class method objects\n' ' A class method object, like a static method object, is a ' 'wrapper\n' ' around another object that alters the way in which that ' 'object\n' ' is retrieved from classes and class instances. The behaviour ' 'of\n' ' class method objects upon such retrieval is described above,\n' ' under “User-defined methods”. Class method objects are ' 'created\n' ' by the built-in "classmethod()" constructor.\n', 'typesfunctions': 'Functions\n' '*********\n' '\n' 'Function objects are created by function definitions. The ' 'only\n' 'operation on a function object is to call it: ' '"func(argument-list)".\n' '\n' 'There are really two flavors of function objects: built-in ' 'functions\n' 'and user-defined functions. Both support the same ' 'operation (to call\n' 'the function), but the implementation is different, hence ' 'the\n' 'different object types.\n' '\n' 'See Function definitions for more information.\n', 'typesmapping': 'Mapping Types — "dict"\n' '**********************\n' '\n' 'A *mapping* object maps *hashable* values to arbitrary ' 'objects.\n' 'Mappings are mutable objects. There is currently only one ' 'standard\n' 'mapping type, the *dictionary*. (For other containers see ' 'the built-\n' 'in "list", "set", and "tuple" classes, and the "collections" ' 'module.)\n' '\n' 'A dictionary’s keys are *almost* arbitrary values. Values ' 'that are\n' 'not *hashable*, that is, values containing lists, ' 'dictionaries or\n' 'other mutable types (that are compared by value rather than ' 'by object\n' 'identity) may not be used as keys. Numeric types used for ' 'keys obey\n' 'the normal rules for numeric comparison: if two numbers ' 'compare equal\n' '(such as "1" and "1.0") then they can be used ' 'interchangeably to index\n' 'the same dictionary entry. (Note however, that since ' 'computers store\n' 'floating-point numbers as approximations it is usually ' 'unwise to use\n' 'them as dictionary keys.)\n' '\n' 'Dictionaries can be created by placing a comma-separated ' 'list of "key:\n' 'value" pairs within braces, for example: "{\'jack\': 4098, ' "'sjoerd':\n" '4127}" or "{4098: \'jack\', 4127: \'sjoerd\'}", or by the ' '"dict"\n' 'constructor.\n' '\n' 'class dict(**kwarg)\n' 'class dict(mapping, **kwarg)\n' 'class dict(iterable, **kwarg)\n' '\n' ' Return a new dictionary initialized from an optional ' 'positional\n' ' argument and a possibly empty set of keyword arguments.\n' '\n' ' Dictionaries can be created by several means:\n' '\n' ' * Use a comma-separated list of "key: value" pairs within ' 'braces:\n' ' "{\'jack\': 4098, \'sjoerd\': 4127}" or "{4098: ' "'jack', 4127:\n" ' \'sjoerd\'}"\n' '\n' ' * Use a dict comprehension: "{}", "{x: x ** 2 for x in ' 'range(10)}"\n' '\n' ' * Use the type constructor: "dict()", "dict([(\'foo\', ' "100), ('bar',\n" ' 200)])", "dict(foo=100, bar=200)"\n' '\n' ' If no positional argument is given, an empty dictionary ' 'is created.\n' ' If a positional argument is given and it is a mapping ' 'object, a\n' ' dictionary is created with the same key-value pairs as ' 'the mapping\n' ' object. Otherwise, the positional argument must be an ' '*iterable*\n' ' object. Each item in the iterable must itself be an ' 'iterable with\n' ' exactly two objects. The first object of each item ' 'becomes a key\n' ' in the new dictionary, and the second object the ' 'corresponding\n' ' value. If a key occurs more than once, the last value ' 'for that key\n' ' becomes the corresponding value in the new dictionary.\n' '\n' ' If keyword arguments are given, the keyword arguments and ' 'their\n' ' values are added to the dictionary created from the ' 'positional\n' ' argument. If a key being added is already present, the ' 'value from\n' ' the keyword argument replaces the value from the ' 'positional\n' ' argument.\n' '\n' ' To illustrate, the following examples all return a ' 'dictionary equal\n' ' to "{"one": 1, "two": 2, "three": 3}":\n' '\n' ' >>> a = dict(one=1, two=2, three=3)\n' " >>> b = {'one': 1, 'two': 2, 'three': 3}\n" " >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))\n" " >>> d = dict([('two', 2), ('one', 1), ('three', 3)])\n" " >>> e = dict({'three': 3, 'one': 1, 'two': 2})\n" " >>> f = dict({'one': 1, 'three': 3}, two=2)\n" ' >>> a == b == c == d == e == f\n' ' True\n' '\n' ' Providing keyword arguments as in the first example only ' 'works for\n' ' keys that are valid Python identifiers. Otherwise, any ' 'valid keys\n' ' can be used.\n' '\n' ' These are the operations that dictionaries support (and ' 'therefore,\n' ' custom mapping types should support too):\n' '\n' ' list(d)\n' '\n' ' Return a list of all the keys used in the dictionary ' '*d*.\n' '\n' ' len(d)\n' '\n' ' Return the number of items in the dictionary *d*.\n' '\n' ' d[key]\n' '\n' ' Return the item of *d* with key *key*. Raises a ' '"KeyError" if\n' ' *key* is not in the map.\n' '\n' ' If a subclass of dict defines a method "__missing__()" ' 'and *key*\n' ' is not present, the "d[key]" operation calls that ' 'method with\n' ' the key *key* as argument. The "d[key]" operation ' 'then returns\n' ' or raises whatever is returned or raised by the\n' ' "__missing__(key)" call. No other operations or ' 'methods invoke\n' ' "__missing__()". If "__missing__()" is not defined, ' '"KeyError"\n' ' is raised. "__missing__()" must be a method; it cannot ' 'be an\n' ' instance variable:\n' '\n' ' >>> class Counter(dict):\n' ' ... def __missing__(self, key):\n' ' ... return 0\n' ' >>> c = Counter()\n' " >>> c['red']\n" ' 0\n' " >>> c['red'] += 1\n" " >>> c['red']\n" ' 1\n' '\n' ' The example above shows part of the implementation of\n' ' "collections.Counter". A different "__missing__" ' 'method is used\n' ' by "collections.defaultdict".\n' '\n' ' d[key] = value\n' '\n' ' Set "d[key]" to *value*.\n' '\n' ' del d[key]\n' '\n' ' Remove "d[key]" from *d*. Raises a "KeyError" if ' '*key* is not\n' ' in the map.\n' '\n' ' key in d\n' '\n' ' Return "True" if *d* has a key *key*, else "False".\n' '\n' ' key not in d\n' '\n' ' Equivalent to "not key in d".\n' '\n' ' iter(d)\n' '\n' ' Return an iterator over the keys of the dictionary. ' 'This is a\n' ' shortcut for "iter(d.keys())".\n' '\n' ' clear()\n' '\n' ' Remove all items from the dictionary.\n' '\n' ' copy()\n' '\n' ' Return a shallow copy of the dictionary.\n' '\n' ' classmethod fromkeys(iterable[, value])\n' '\n' ' Create a new dictionary with keys from *iterable* and ' 'values set\n' ' to *value*.\n' '\n' ' "fromkeys()" is a class method that returns a new ' 'dictionary.\n' ' *value* defaults to "None". All of the values refer ' 'to just a\n' ' single instance, so it generally doesn’t make sense ' 'for *value*\n' ' to be a mutable object such as an empty list. To get ' 'distinct\n' ' values, use a dict comprehension instead.\n' '\n' ' get(key[, default])\n' '\n' ' Return the value for *key* if *key* is in the ' 'dictionary, else\n' ' *default*. If *default* is not given, it defaults to ' '"None", so\n' ' that this method never raises a "KeyError".\n' '\n' ' items()\n' '\n' ' Return a new view of the dictionary’s items ("(key, ' 'value)"\n' ' pairs). See the documentation of view objects.\n' '\n' ' keys()\n' '\n' ' Return a new view of the dictionary’s keys. See the\n' ' documentation of view objects.\n' '\n' ' pop(key[, default])\n' '\n' ' If *key* is in the dictionary, remove it and return ' 'its value,\n' ' else return *default*. If *default* is not given and ' '*key* is\n' ' not in the dictionary, a "KeyError" is raised.\n' '\n' ' popitem()\n' '\n' ' Remove and return a "(key, value)" pair from the ' 'dictionary.\n' ' Pairs are returned in LIFO (last-in, first-out) ' 'order.\n' '\n' ' "popitem()" is useful to destructively iterate over a\n' ' dictionary, as often used in set algorithms. If the ' 'dictionary\n' ' is empty, calling "popitem()" raises a "KeyError".\n' '\n' ' Changed in version 3.7: LIFO order is now guaranteed. ' 'In prior\n' ' versions, "popitem()" would return an arbitrary ' 'key/value pair.\n' '\n' ' reversed(d)\n' '\n' ' Return a reverse iterator over the keys of the ' 'dictionary. This\n' ' is a shortcut for "reversed(d.keys())".\n' '\n' ' New in version 3.8.\n' '\n' ' setdefault(key[, default])\n' '\n' ' If *key* is in the dictionary, return its value. If ' 'not, insert\n' ' *key* with a value of *default* and return *default*. ' '*default*\n' ' defaults to "None".\n' '\n' ' update([other])\n' '\n' ' Update the dictionary with the key/value pairs from ' '*other*,\n' ' overwriting existing keys. Return "None".\n' '\n' ' "update()" accepts either another dictionary object or ' 'an\n' ' iterable of key/value pairs (as tuples or other ' 'iterables of\n' ' length two). If keyword arguments are specified, the ' 'dictionary\n' ' is then updated with those key/value pairs: ' '"d.update(red=1,\n' ' blue=2)".\n' '\n' ' values()\n' '\n' ' Return a new view of the dictionary’s values. See ' 'the\n' ' documentation of view objects.\n' '\n' ' An equality comparison between one "dict.values()" ' 'view and\n' ' another will always return "False". This also applies ' 'when\n' ' comparing "dict.values()" to itself:\n' '\n' " >>> d = {'a': 1}\n" ' >>> d.values() == d.values()\n' ' False\n' '\n' ' d | other\n' '\n' ' Create a new dictionary with the merged keys and ' 'values of *d*\n' ' and *other*, which must both be dictionaries. The ' 'values of\n' ' *other* take priority when *d* and *other* share ' 'keys.\n' '\n' ' New in version 3.9.\n' '\n' ' d |= other\n' '\n' ' Update the dictionary *d* with keys and values from ' '*other*,\n' ' which may be either a *mapping* or an *iterable* of ' 'key/value\n' ' pairs. The values of *other* take priority when *d* ' 'and *other*\n' ' share keys.\n' '\n' ' New in version 3.9.\n' '\n' ' Dictionaries compare equal if and only if they have the ' 'same "(key,\n' ' value)" pairs (regardless of ordering). Order comparisons ' '(‘<’,\n' ' ‘<=’, ‘>=’, ‘>’) raise "TypeError".\n' '\n' ' Dictionaries preserve insertion order. Note that ' 'updating a key\n' ' does not affect the order. Keys added after deletion are ' 'inserted\n' ' at the end.\n' '\n' ' >>> d = {"one": 1, "two": 2, "three": 3, "four": 4}\n' ' >>> d\n' " {'one': 1, 'two': 2, 'three': 3, 'four': 4}\n" ' >>> list(d)\n' " ['one', 'two', 'three', 'four']\n" ' >>> list(d.values())\n' ' [1, 2, 3, 4]\n' ' >>> d["one"] = 42\n' ' >>> d\n' " {'one': 42, 'two': 2, 'three': 3, 'four': 4}\n" ' >>> del d["two"]\n' ' >>> d["two"] = None\n' ' >>> d\n' " {'one': 42, 'three': 3, 'four': 4, 'two': None}\n" '\n' ' Changed in version 3.7: Dictionary order is guaranteed to ' 'be\n' ' insertion order. This behavior was an implementation ' 'detail of\n' ' CPython from 3.6.\n' '\n' ' Dictionaries and dictionary views are reversible.\n' '\n' ' >>> d = {"one": 1, "two": 2, "three": 3, "four": 4}\n' ' >>> d\n' " {'one': 1, 'two': 2, 'three': 3, 'four': 4}\n" ' >>> list(reversed(d))\n' " ['four', 'three', 'two', 'one']\n" ' >>> list(reversed(d.values()))\n' ' [4, 3, 2, 1]\n' ' >>> list(reversed(d.items()))\n' " [('four', 4), ('three', 3), ('two', 2), ('one', 1)]\n" '\n' ' Changed in version 3.8: Dictionaries are now reversible.\n' '\n' 'See also:\n' '\n' ' "types.MappingProxyType" can be used to create a read-only ' 'view of a\n' ' "dict".\n' '\n' '\n' 'Dictionary view objects\n' '=======================\n' '\n' 'The objects returned by "dict.keys()", "dict.values()" and\n' '"dict.items()" are *view objects*. They provide a dynamic ' 'view on the\n' 'dictionary’s entries, which means that when the dictionary ' 'changes,\n' 'the view reflects these changes.\n' '\n' 'Dictionary views can be iterated over to yield their ' 'respective data,\n' 'and support membership tests:\n' '\n' 'len(dictview)\n' '\n' ' Return the number of entries in the dictionary.\n' '\n' 'iter(dictview)\n' '\n' ' Return an iterator over the keys, values or items ' '(represented as\n' ' tuples of "(key, value)") in the dictionary.\n' '\n' ' Keys and values are iterated over in insertion order. ' 'This allows\n' ' the creation of "(value, key)" pairs using "zip()": ' '"pairs =\n' ' zip(d.values(), d.keys())". Another way to create the ' 'same list is\n' ' "pairs = [(v, k) for (k, v) in d.items()]".\n' '\n' ' Iterating views while adding or deleting entries in the ' 'dictionary\n' ' may raise a "RuntimeError" or fail to iterate over all ' 'entries.\n' '\n' ' Changed in version 3.7: Dictionary order is guaranteed to ' 'be\n' ' insertion order.\n' '\n' 'x in dictview\n' '\n' ' Return "True" if *x* is in the underlying dictionary’s ' 'keys, values\n' ' or items (in the latter case, *x* should be a "(key, ' 'value)"\n' ' tuple).\n' '\n' 'reversed(dictview)\n' '\n' ' Return a reverse iterator over the keys, values or items ' 'of the\n' ' dictionary. The view will be iterated in reverse order of ' 'the\n' ' insertion.\n' '\n' ' Changed in version 3.8: Dictionary views are now ' 'reversible.\n' '\n' 'dictview.mapping\n' '\n' ' Return a "types.MappingProxyType" that wraps the ' 'original\n' ' dictionary to which the view refers.\n' '\n' ' New in version 3.10.\n' '\n' 'Keys views are set-like since their entries are unique and ' 'hashable.\n' 'If all values are hashable, so that "(key, value)" pairs are ' 'unique\n' 'and hashable, then the items view is also set-like. (Values ' 'views are\n' 'not treated as set-like since the entries are generally not ' 'unique.)\n' 'For set-like views, all of the operations defined for the ' 'abstract\n' 'base class "collections.abc.Set" are available (for example, ' '"==",\n' '"<", or "^").\n' '\n' 'An example of dictionary view usage:\n' '\n' " >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, " "'spam': 500}\n" ' >>> keys = dishes.keys()\n' ' >>> values = dishes.values()\n' '\n' ' >>> # iteration\n' ' >>> n = 0\n' ' >>> for val in values:\n' ' ... n += val\n' ' >>> print(n)\n' ' 504\n' '\n' ' >>> # keys and values are iterated over in the same order ' '(insertion order)\n' ' >>> list(keys)\n' " ['eggs', 'sausage', 'bacon', 'spam']\n" ' >>> list(values)\n' ' [2, 1, 1, 500]\n' '\n' ' >>> # view objects are dynamic and reflect dict changes\n' " >>> del dishes['eggs']\n" " >>> del dishes['sausage']\n" ' >>> list(keys)\n' " ['bacon', 'spam']\n" '\n' ' >>> # set operations\n' " >>> keys & {'eggs', 'bacon', 'salad'}\n" " {'bacon'}\n" " >>> keys ^ {'sausage', 'juice'}\n" " {'juice', 'sausage', 'bacon', 'spam'}\n" '\n' ' >>> # get back a read-only proxy for the original ' 'dictionary\n' ' >>> values.mapping\n' " mappingproxy({'eggs': 2, 'sausage': 1, 'bacon': 1, " "'spam': 500})\n" " >>> values.mapping['spam']\n" ' 500\n', 'typesmethods': 'Methods\n' '*******\n' '\n' 'Methods are functions that are called using the attribute ' 'notation.\n' 'There are two flavors: built-in methods (such as "append()" ' 'on lists)\n' 'and class instance methods. Built-in methods are described ' 'with the\n' 'types that support them.\n' '\n' 'If you access a method (a function defined in a class ' 'namespace)\n' 'through an instance, you get a special object: a *bound ' 'method* (also\n' 'called *instance method*) object. When called, it will add ' 'the "self"\n' 'argument to the argument list. Bound methods have two ' 'special read-\n' 'only attributes: "m.__self__" is the object on which the ' 'method\n' 'operates, and "m.__func__" is the function implementing the ' 'method.\n' 'Calling "m(arg-1, arg-2, ..., arg-n)" is completely ' 'equivalent to\n' 'calling "m.__func__(m.__self__, arg-1, arg-2, ..., arg-n)".\n' '\n' 'Like function objects, bound method objects support getting ' 'arbitrary\n' 'attributes. However, since method attributes are actually ' 'stored on\n' 'the underlying function object ("meth.__func__"), setting ' 'method\n' 'attributes on bound methods is disallowed. Attempting to ' 'set an\n' 'attribute on a method results in an "AttributeError" being ' 'raised. In\n' 'order to set a method attribute, you need to explicitly set ' 'it on the\n' 'underlying function object:\n' '\n' ' >>> class C:\n' ' ... def method(self):\n' ' ... pass\n' ' ...\n' ' >>> c = C()\n' " >>> c.method.whoami = 'my name is method' # can't set on " 'the method\n' ' Traceback (most recent call last):\n' ' File "<stdin>", line 1, in <module>\n' " AttributeError: 'method' object has no attribute " "'whoami'\n" " >>> c.method.__func__.whoami = 'my name is method'\n" ' >>> c.method.whoami\n' " 'my name is method'\n" '\n' 'See The standard type hierarchy for more information.\n', 'typesmodules': 'Modules\n' '*******\n' '\n' 'The only special operation on a module is attribute access: ' '"m.name",\n' 'where *m* is a module and *name* accesses a name defined in ' '*m*’s\n' 'symbol table. Module attributes can be assigned to. (Note ' 'that the\n' '"import" statement is not, strictly speaking, an operation ' 'on a module\n' 'object; "import foo" does not require a module object named ' '*foo* to\n' 'exist, rather it requires an (external) *definition* for a ' 'module\n' 'named *foo* somewhere.)\n' '\n' 'A special attribute of every module is "__dict__". This is ' 'the\n' 'dictionary containing the module’s symbol table. Modifying ' 'this\n' 'dictionary will actually change the module’s symbol table, ' 'but direct\n' 'assignment to the "__dict__" attribute is not possible (you ' 'can write\n' '"m.__dict__[\'a\'] = 1", which defines "m.a" to be "1", but ' 'you can’t\n' 'write "m.__dict__ = {}"). Modifying "__dict__" directly is ' 'not\n' 'recommended.\n' '\n' 'Modules built into the interpreter are written like this: ' '"<module\n' '\'sys\' (built-in)>". If loaded from a file, they are ' 'written as\n' '"<module \'os\' from ' '\'/usr/local/lib/pythonX.Y/os.pyc\'>".\n', 'typesseq': 'Sequence Types — "list", "tuple", "range"\n' '*****************************************\n' '\n' 'There are three basic sequence types: lists, tuples, and range\n' 'objects. Additional sequence types tailored for processing of ' 'binary\n' 'data and text strings are described in dedicated sections.\n' '\n' '\n' 'Common Sequence Operations\n' '==========================\n' '\n' 'The operations in the following table are supported by most ' 'sequence\n' 'types, both mutable and immutable. The ' '"collections.abc.Sequence" ABC\n' 'is provided to make it easier to correctly implement these ' 'operations\n' 'on custom sequence types.\n' '\n' 'This table lists the sequence operations sorted in ascending ' 'priority.\n' 'In the table, *s* and *t* are sequences of the same type, *n*, ' '*i*,\n' '*j* and *k* are integers and *x* is an arbitrary object that ' 'meets any\n' 'type and value restrictions imposed by *s*.\n' '\n' 'The "in" and "not in" operations have the same priorities as ' 'the\n' 'comparison operations. The "+" (concatenation) and "*" ' '(repetition)\n' 'operations have the same priority as the corresponding numeric\n' 'operations. [3]\n' '\n' '+----------------------------+----------------------------------+------------+\n' '| Operation | Result ' '| Notes |\n' '|============================|==================================|============|\n' '| "x in s" | "True" if an item of *s* is ' '| (1) |\n' '| | equal to *x*, else "False" ' '| |\n' '+----------------------------+----------------------------------+------------+\n' '| "x not in s" | "False" if an item of *s* is ' '| (1) |\n' '| | equal to *x*, else "True" ' '| |\n' '+----------------------------+----------------------------------+------------+\n' '| "s + t" | the concatenation of *s* and *t* ' '| (6)(7) |\n' '+----------------------------+----------------------------------+------------+\n' '| "s * n" or "n * s" | equivalent to adding *s* to ' '| (2)(7) |\n' '| | itself *n* times ' '| |\n' '+----------------------------+----------------------------------+------------+\n' '| "s[i]" | *i*th item of *s*, origin 0 ' '| (3) |\n' '+----------------------------+----------------------------------+------------+\n' '| "s[i:j]" | slice of *s* from *i* to *j* ' '| (3)(4) |\n' '+----------------------------+----------------------------------+------------+\n' '| "s[i:j:k]" | slice of *s* from *i* to *j* ' '| (3)(5) |\n' '| | with step *k* ' '| |\n' '+----------------------------+----------------------------------+------------+\n' '| "len(s)" | length of *s* ' '| |\n' '+----------------------------+----------------------------------+------------+\n' '| "min(s)" | smallest item of *s* ' '| |\n' '+----------------------------+----------------------------------+------------+\n' '| "max(s)" | largest item of *s* ' '| |\n' '+----------------------------+----------------------------------+------------+\n' '| "s.index(x[, i[, j]])" | index of the first occurrence of ' '| (8) |\n' '| | *x* in *s* (at or after index ' '| |\n' '| | *i* and before index *j*) ' '| |\n' '+----------------------------+----------------------------------+------------+\n' '| "s.count(x)" | total number of occurrences of ' '| |\n' '| | *x* in *s* ' '| |\n' '+----------------------------+----------------------------------+------------+\n' '\n' 'Sequences of the same type also support comparisons. In ' 'particular,\n' 'tuples and lists are compared lexicographically by comparing\n' 'corresponding elements. This means that to compare equal, every\n' 'element must compare equal and the two sequences must be of the ' 'same\n' 'type and have the same length. (For full details see ' 'Comparisons in\n' 'the language reference.)\n' '\n' 'Notes:\n' '\n' '1. While the "in" and "not in" operations are used only for ' 'simple\n' ' containment testing in the general case, some specialised ' 'sequences\n' ' (such as "str", "bytes" and "bytearray") also use them for\n' ' subsequence testing:\n' '\n' ' >>> "gg" in "eggs"\n' ' True\n' '\n' '2. Values of *n* less than "0" are treated as "0" (which yields ' 'an\n' ' empty sequence of the same type as *s*). Note that items in ' 'the\n' ' sequence *s* are not copied; they are referenced multiple ' 'times.\n' ' This often haunts new Python programmers; consider:\n' '\n' ' >>> lists = [[]] * 3\n' ' >>> lists\n' ' [[], [], []]\n' ' >>> lists[0].append(3)\n' ' >>> lists\n' ' [[3], [3], [3]]\n' '\n' ' What has happened is that "[[]]" is a one-element list ' 'containing\n' ' an empty list, so all three elements of "[[]] * 3" are ' 'references\n' ' to this single empty list. Modifying any of the elements of\n' ' "lists" modifies this single list. You can create a list of\n' ' different lists this way:\n' '\n' ' >>> lists = [[] for i in range(3)]\n' ' >>> lists[0].append(3)\n' ' >>> lists[1].append(5)\n' ' >>> lists[2].append(7)\n' ' >>> lists\n' ' [[3], [5], [7]]\n' '\n' ' Further explanation is available in the FAQ entry How do I ' 'create a\n' ' multidimensional list?.\n' '\n' '3. If *i* or *j* is negative, the index is relative to the end ' 'of\n' ' sequence *s*: "len(s) + i" or "len(s) + j" is substituted. ' 'But\n' ' note that "-0" is still "0".\n' '\n' '4. The slice of *s* from *i* to *j* is defined as the sequence ' 'of\n' ' items with index *k* such that "i <= k < j". If *i* or *j* ' 'is\n' ' greater than "len(s)", use "len(s)". If *i* is omitted or ' '"None",\n' ' use "0". If *j* is omitted or "None", use "len(s)". If *i* ' 'is\n' ' greater than or equal to *j*, the slice is empty.\n' '\n' '5. The slice of *s* from *i* to *j* with step *k* is defined as ' 'the\n' ' sequence of items with index "x = i + n*k" such that "0 <= n ' '<\n' ' (j-i)/k". In other words, the indices are "i", "i+k", ' '"i+2*k",\n' ' "i+3*k" and so on, stopping when *j* is reached (but never\n' ' including *j*). When *k* is positive, *i* and *j* are ' 'reduced to\n' ' "len(s)" if they are greater. When *k* is negative, *i* and ' '*j* are\n' ' reduced to "len(s) - 1" if they are greater. If *i* or *j* ' 'are\n' ' omitted or "None", they become “end” values (which end ' 'depends on\n' ' the sign of *k*). Note, *k* cannot be zero. If *k* is ' '"None", it\n' ' is treated like "1".\n' '\n' '6. Concatenating immutable sequences always results in a new ' 'object.\n' ' This means that building up a sequence by repeated ' 'concatenation\n' ' will have a quadratic runtime cost in the total sequence ' 'length.\n' ' To get a linear runtime cost, you must switch to one of the\n' ' alternatives below:\n' '\n' ' * if concatenating "str" objects, you can build a list and ' 'use\n' ' "str.join()" at the end or else write to an "io.StringIO"\n' ' instance and retrieve its value when complete\n' '\n' ' * if concatenating "bytes" objects, you can similarly use\n' ' "bytes.join()" or "io.BytesIO", or you can do in-place\n' ' concatenation with a "bytearray" object. "bytearray" ' 'objects are\n' ' mutable and have an efficient overallocation mechanism\n' '\n' ' * if concatenating "tuple" objects, extend a "list" instead\n' '\n' ' * for other types, investigate the relevant class ' 'documentation\n' '\n' '7. Some sequence types (such as "range") only support item ' 'sequences\n' ' that follow specific patterns, and hence don’t support ' 'sequence\n' ' concatenation or repetition.\n' '\n' '8. "index" raises "ValueError" when *x* is not found in *s*. Not ' 'all\n' ' implementations support passing the additional arguments *i* ' 'and\n' ' *j*. These arguments allow efficient searching of subsections ' 'of\n' ' the sequence. Passing the extra arguments is roughly ' 'equivalent to\n' ' using "s[i:j].index(x)", only without copying any data and ' 'with the\n' ' returned index being relative to the start of the sequence ' 'rather\n' ' than the start of the slice.\n' '\n' '\n' 'Immutable Sequence Types\n' '========================\n' '\n' 'The only operation that immutable sequence types generally ' 'implement\n' 'that is not also implemented by mutable sequence types is ' 'support for\n' 'the "hash()" built-in.\n' '\n' 'This support allows immutable sequences, such as "tuple" ' 'instances, to\n' 'be used as "dict" keys and stored in "set" and "frozenset" ' 'instances.\n' '\n' 'Attempting to hash an immutable sequence that contains ' 'unhashable\n' 'values will result in "TypeError".\n' '\n' '\n' 'Mutable Sequence Types\n' '======================\n' '\n' 'The operations in the following table are defined on mutable ' 'sequence\n' 'types. The "collections.abc.MutableSequence" ABC is provided to ' 'make\n' 'it easier to correctly implement these operations on custom ' 'sequence\n' 'types.\n' '\n' 'In the table *s* is an instance of a mutable sequence type, *t* ' 'is any\n' 'iterable object and *x* is an arbitrary object that meets any ' 'type and\n' 'value restrictions imposed by *s* (for example, "bytearray" ' 'only\n' 'accepts integers that meet the value restriction "0 <= x <= ' '255").\n' '\n' '+--------------------------------+----------------------------------+-----------------------+\n' '| Operation | ' 'Result | Notes |\n' '|================================|==================================|=======================|\n' '| "s[i] = x" | item *i* of *s* is replaced ' 'by | |\n' '| | ' '*x* | |\n' '+--------------------------------+----------------------------------+-----------------------+\n' '| "s[i:j] = t" | slice of *s* from *i* to *j* ' 'is | |\n' '| | replaced by the contents of ' 'the | |\n' '| | iterable ' '*t* | |\n' '+--------------------------------+----------------------------------+-----------------------+\n' '| "del s[i:j]" | same as "s[i:j] = ' '[]" | |\n' '+--------------------------------+----------------------------------+-----------------------+\n' '| "s[i:j:k] = t" | the elements of "s[i:j:k]" ' 'are | (1) |\n' '| | replaced by those of ' '*t* | |\n' '+--------------------------------+----------------------------------+-----------------------+\n' '| "del s[i:j:k]" | removes the elements ' 'of | |\n' '| | "s[i:j:k]" from the ' 'list | |\n' '+--------------------------------+----------------------------------+-----------------------+\n' '| "s.append(x)" | appends *x* to the end of ' 'the | |\n' '| | sequence (same ' 'as | |\n' '| | "s[len(s):len(s)] = ' '[x]") | |\n' '+--------------------------------+----------------------------------+-----------------------+\n' '| "s.clear()" | removes all items from *s* ' '(same | (5) |\n' '| | as "del ' 's[:]") | |\n' '+--------------------------------+----------------------------------+-----------------------+\n' '| "s.copy()" | creates a shallow copy of ' '*s* | (5) |\n' '| | (same as ' '"s[:]") | |\n' '+--------------------------------+----------------------------------+-----------------------+\n' '| "s.extend(t)" or "s += t" | extends *s* with the contents ' 'of | |\n' '| | *t* (for the most part the ' 'same | |\n' '| | as "s[len(s):len(s)] = ' 't") | |\n' '+--------------------------------+----------------------------------+-----------------------+\n' '| "s *= n" | updates *s* with its ' 'contents | (6) |\n' '| | repeated *n* ' 'times | |\n' '+--------------------------------+----------------------------------+-----------------------+\n' '| "s.insert(i, x)" | inserts *x* into *s* at ' 'the | |\n' '| | index given by *i* (same ' 'as | |\n' '| | "s[i:i] = ' '[x]") | |\n' '+--------------------------------+----------------------------------+-----------------------+\n' '| "s.pop([i])" | retrieves the item at *i* ' 'and | (2) |\n' '| | also removes it from ' '*s* | |\n' '+--------------------------------+----------------------------------+-----------------------+\n' '| "s.remove(x)" | remove the first item from ' '*s* | (3) |\n' '| | where "s[i]" is equal to ' '*x* | |\n' '+--------------------------------+----------------------------------+-----------------------+\n' '| "s.reverse()" | reverses the items of *s* ' 'in | (4) |\n' '| | ' 'place | |\n' '+--------------------------------+----------------------------------+-----------------------+\n' '\n' 'Notes:\n' '\n' '1. *t* must have the same length as the slice it is replacing.\n' '\n' '2. The optional argument *i* defaults to "-1", so that by ' 'default the\n' ' last item is removed and returned.\n' '\n' '3. "remove()" raises "ValueError" when *x* is not found in *s*.\n' '\n' '4. The "reverse()" method modifies the sequence in place for ' 'economy\n' ' of space when reversing a large sequence. To remind users ' 'that it\n' ' operates by side effect, it does not return the reversed ' 'sequence.\n' '\n' '5. "clear()" and "copy()" are included for consistency with the\n' ' interfaces of mutable containers that don’t support slicing\n' ' operations (such as "dict" and "set"). "copy()" is not part ' 'of the\n' ' "collections.abc.MutableSequence" ABC, but most concrete ' 'mutable\n' ' sequence classes provide it.\n' '\n' ' New in version 3.3: "clear()" and "copy()" methods.\n' '\n' '6. The value *n* is an integer, or an object implementing\n' ' "__index__()". Zero and negative values of *n* clear the ' 'sequence.\n' ' Items in the sequence are not copied; they are referenced ' 'multiple\n' ' times, as explained for "s * n" under Common Sequence ' 'Operations.\n' '\n' '\n' 'Lists\n' '=====\n' '\n' 'Lists are mutable sequences, typically used to store collections ' 'of\n' 'homogeneous items (where the precise degree of similarity will ' 'vary by\n' 'application).\n' '\n' 'class list([iterable])\n' '\n' ' Lists may be constructed in several ways:\n' '\n' ' * Using a pair of square brackets to denote the empty list: ' '"[]"\n' '\n' ' * Using square brackets, separating items with commas: "[a]", ' '"[a,\n' ' b, c]"\n' '\n' ' * Using a list comprehension: "[x for x in iterable]"\n' '\n' ' * Using the type constructor: "list()" or "list(iterable)"\n' '\n' ' The constructor builds a list whose items are the same and in ' 'the\n' ' same order as *iterable*’s items. *iterable* may be either ' 'a\n' ' sequence, a container that supports iteration, or an ' 'iterator\n' ' object. If *iterable* is already a list, a copy is made and\n' ' returned, similar to "iterable[:]". For example, ' '"list(\'abc\')"\n' ' returns "[\'a\', \'b\', \'c\']" and "list( (1, 2, 3) )" ' 'returns "[1, 2,\n' ' 3]". If no argument is given, the constructor creates a new ' 'empty\n' ' list, "[]".\n' '\n' ' Many other operations also produce lists, including the ' '"sorted()"\n' ' built-in.\n' '\n' ' Lists implement all of the common and mutable sequence ' 'operations.\n' ' Lists also provide the following additional method:\n' '\n' ' sort(*, key=None, reverse=False)\n' '\n' ' This method sorts the list in place, using only "<" ' 'comparisons\n' ' between items. Exceptions are not suppressed - if any ' 'comparison\n' ' operations fail, the entire sort operation will fail (and ' 'the\n' ' list will likely be left in a partially modified state).\n' '\n' ' "sort()" accepts two arguments that can only be passed by\n' ' keyword (keyword-only arguments):\n' '\n' ' *key* specifies a function of one argument that is used ' 'to\n' ' extract a comparison key from each list element (for ' 'example,\n' ' "key=str.lower"). The key corresponding to each item in ' 'the list\n' ' is calculated once and then used for the entire sorting ' 'process.\n' ' The default value of "None" means that list items are ' 'sorted\n' ' directly without calculating a separate key value.\n' '\n' ' The "functools.cmp_to_key()" utility is available to ' 'convert a\n' ' 2.x style *cmp* function to a *key* function.\n' '\n' ' *reverse* is a boolean value. If set to "True", then the ' 'list\n' ' elements are sorted as if each comparison were reversed.\n' '\n' ' This method modifies the sequence in place for economy of ' 'space\n' ' when sorting a large sequence. To remind users that it ' 'operates\n' ' by side effect, it does not return the sorted sequence ' '(use\n' ' "sorted()" to explicitly request a new sorted list ' 'instance).\n' '\n' ' The "sort()" method is guaranteed to be stable. A sort ' 'is\n' ' stable if it guarantees not to change the relative order ' 'of\n' ' elements that compare equal — this is helpful for sorting ' 'in\n' ' multiple passes (for example, sort by department, then by ' 'salary\n' ' grade).\n' '\n' ' For sorting examples and a brief sorting tutorial, see ' 'Sorting\n' ' HOW TO.\n' '\n' ' **CPython implementation detail:** While a list is being ' 'sorted,\n' ' the effect of attempting to mutate, or even inspect, the ' 'list is\n' ' undefined. The C implementation of Python makes the list ' 'appear\n' ' empty for the duration, and raises "ValueError" if it can ' 'detect\n' ' that the list has been mutated during a sort.\n' '\n' '\n' 'Tuples\n' '======\n' '\n' 'Tuples are immutable sequences, typically used to store ' 'collections of\n' 'heterogeneous data (such as the 2-tuples produced by the ' '"enumerate()"\n' 'built-in). Tuples are also used for cases where an immutable ' 'sequence\n' 'of homogeneous data is needed (such as allowing storage in a ' '"set" or\n' '"dict" instance).\n' '\n' 'class tuple([iterable])\n' '\n' ' Tuples may be constructed in a number of ways:\n' '\n' ' * Using a pair of parentheses to denote the empty tuple: ' '"()"\n' '\n' ' * Using a trailing comma for a singleton tuple: "a," or ' '"(a,)"\n' '\n' ' * Separating items with commas: "a, b, c" or "(a, b, c)"\n' '\n' ' * Using the "tuple()" built-in: "tuple()" or ' '"tuple(iterable)"\n' '\n' ' The constructor builds a tuple whose items are the same and ' 'in the\n' ' same order as *iterable*’s items. *iterable* may be either ' 'a\n' ' sequence, a container that supports iteration, or an ' 'iterator\n' ' object. If *iterable* is already a tuple, it is returned\n' ' unchanged. For example, "tuple(\'abc\')" returns "(\'a\', ' '\'b\', \'c\')"\n' ' and "tuple( [1, 2, 3] )" returns "(1, 2, 3)". If no argument ' 'is\n' ' given, the constructor creates a new empty tuple, "()".\n' '\n' ' Note that it is actually the comma which makes a tuple, not ' 'the\n' ' parentheses. The parentheses are optional, except in the ' 'empty\n' ' tuple case, or when they are needed to avoid syntactic ' 'ambiguity.\n' ' For example, "f(a, b, c)" is a function call with three ' 'arguments,\n' ' while "f((a, b, c))" is a function call with a 3-tuple as the ' 'sole\n' ' argument.\n' '\n' ' Tuples implement all of the common sequence operations.\n' '\n' 'For heterogeneous collections of data where access by name is ' 'clearer\n' 'than access by index, "collections.namedtuple()" may be a more\n' 'appropriate choice than a simple tuple object.\n' '\n' '\n' 'Ranges\n' '======\n' '\n' 'The "range" type represents an immutable sequence of numbers and ' 'is\n' 'commonly used for looping a specific number of times in "for" ' 'loops.\n' '\n' 'class range(stop)\n' 'class range(start, stop[, step])\n' '\n' ' The arguments to the range constructor must be integers ' '(either\n' ' built-in "int" or any object that implements the "__index__"\n' ' special method). If the *step* argument is omitted, it ' 'defaults to\n' ' "1". If the *start* argument is omitted, it defaults to "0". ' 'If\n' ' *step* is zero, "ValueError" is raised.\n' '\n' ' For a positive *step*, the contents of a range "r" are ' 'determined\n' ' by the formula "r[i] = start + step*i" where "i >= 0" and ' '"r[i] <\n' ' stop".\n' '\n' ' For a negative *step*, the contents of the range are still\n' ' determined by the formula "r[i] = start + step*i", but the\n' ' constraints are "i >= 0" and "r[i] > stop".\n' '\n' ' A range object will be empty if "r[0]" does not meet the ' 'value\n' ' constraint. Ranges do support negative indices, but these ' 'are\n' ' interpreted as indexing from the end of the sequence ' 'determined by\n' ' the positive indices.\n' '\n' ' Ranges containing absolute values larger than "sys.maxsize" ' 'are\n' ' permitted but some features (such as "len()") may raise\n' ' "OverflowError".\n' '\n' ' Range examples:\n' '\n' ' >>> list(range(10))\n' ' [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n' ' >>> list(range(1, 11))\n' ' [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n' ' >>> list(range(0, 30, 5))\n' ' [0, 5, 10, 15, 20, 25]\n' ' >>> list(range(0, 10, 3))\n' ' [0, 3, 6, 9]\n' ' >>> list(range(0, -10, -1))\n' ' [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]\n' ' >>> list(range(0))\n' ' []\n' ' >>> list(range(1, 0))\n' ' []\n' '\n' ' Ranges implement all of the common sequence operations ' 'except\n' ' concatenation and repetition (due to the fact that range ' 'objects\n' ' can only represent sequences that follow a strict pattern ' 'and\n' ' repetition and concatenation will usually violate that ' 'pattern).\n' '\n' ' start\n' '\n' ' The value of the *start* parameter (or "0" if the ' 'parameter was\n' ' not supplied)\n' '\n' ' stop\n' '\n' ' The value of the *stop* parameter\n' '\n' ' step\n' '\n' ' The value of the *step* parameter (or "1" if the parameter ' 'was\n' ' not supplied)\n' '\n' 'The advantage of the "range" type over a regular "list" or ' '"tuple" is\n' 'that a "range" object will always take the same (small) amount ' 'of\n' 'memory, no matter the size of the range it represents (as it ' 'only\n' 'stores the "start", "stop" and "step" values, calculating ' 'individual\n' 'items and subranges as needed).\n' '\n' 'Range objects implement the "collections.abc.Sequence" ABC, and\n' 'provide features such as containment tests, element index ' 'lookup,\n' 'slicing and support for negative indices (see Sequence Types — ' 'list,\n' 'tuple, range):\n' '\n' '>>> r = range(0, 20, 2)\n' '>>> r\n' 'range(0, 20, 2)\n' '>>> 11 in r\n' 'False\n' '>>> 10 in r\n' 'True\n' '>>> r.index(10)\n' '5\n' '>>> r[5]\n' '10\n' '>>> r[:5]\n' 'range(0, 10, 2)\n' '>>> r[-1]\n' '18\n' '\n' 'Testing range objects for equality with "==" and "!=" compares ' 'them as\n' 'sequences. That is, two range objects are considered equal if ' 'they\n' 'represent the same sequence of values. (Note that two range ' 'objects\n' 'that compare equal might have different "start", "stop" and ' '"step"\n' 'attributes, for example "range(0) == range(2, 1, 3)" or ' '"range(0, 3,\n' '2) == range(0, 4, 2)".)\n' '\n' 'Changed in version 3.2: Implement the Sequence ABC. Support ' 'slicing\n' 'and negative indices. Test "int" objects for membership in ' 'constant\n' 'time instead of iterating through all items.\n' '\n' 'Changed in version 3.3: Define ‘==’ and ‘!=’ to compare range ' 'objects\n' 'based on the sequence of values they define (instead of ' 'comparing\n' 'based on object identity).\n' '\n' 'New in version 3.3: The "start", "stop" and "step" attributes.\n' '\n' 'See also:\n' '\n' ' * The linspace recipe shows how to implement a lazy version of ' 'range\n' ' suitable for floating point applications.\n', 'typesseq-mutable': 'Mutable Sequence Types\n' '**********************\n' '\n' 'The operations in the following table are defined on ' 'mutable sequence\n' 'types. The "collections.abc.MutableSequence" ABC is ' 'provided to make\n' 'it easier to correctly implement these operations on ' 'custom sequence\n' 'types.\n' '\n' 'In the table *s* is an instance of a mutable sequence ' 'type, *t* is any\n' 'iterable object and *x* is an arbitrary object that ' 'meets any type and\n' 'value restrictions imposed by *s* (for example, ' '"bytearray" only\n' 'accepts integers that meet the value restriction "0 <= x ' '<= 255").\n' '\n' '+--------------------------------+----------------------------------+-----------------------+\n' '| Operation | ' 'Result | Notes ' '|\n' '|================================|==================================|=======================|\n' '| "s[i] = x" | item *i* of *s* is ' 'replaced by | |\n' '| | ' '*x* | ' '|\n' '+--------------------------------+----------------------------------+-----------------------+\n' '| "s[i:j] = t" | slice of *s* from *i* ' 'to *j* is | |\n' '| | replaced by the ' 'contents of the | |\n' '| | iterable ' '*t* | |\n' '+--------------------------------+----------------------------------+-----------------------+\n' '| "del s[i:j]" | same as "s[i:j] = ' '[]" | |\n' '+--------------------------------+----------------------------------+-----------------------+\n' '| "s[i:j:k] = t" | the elements of ' '"s[i:j:k]" are | (1) |\n' '| | replaced by those of ' '*t* | |\n' '+--------------------------------+----------------------------------+-----------------------+\n' '| "del s[i:j:k]" | removes the elements ' 'of | |\n' '| | "s[i:j:k]" from the ' 'list | |\n' '+--------------------------------+----------------------------------+-----------------------+\n' '| "s.append(x)" | appends *x* to the ' 'end of the | |\n' '| | sequence (same ' 'as | |\n' '| | "s[len(s):len(s)] = ' '[x]") | |\n' '+--------------------------------+----------------------------------+-----------------------+\n' '| "s.clear()" | removes all items ' 'from *s* (same | (5) |\n' '| | as "del ' 's[:]") | |\n' '+--------------------------------+----------------------------------+-----------------------+\n' '| "s.copy()" | creates a shallow ' 'copy of *s* | (5) |\n' '| | (same as ' '"s[:]") | |\n' '+--------------------------------+----------------------------------+-----------------------+\n' '| "s.extend(t)" or "s += t" | extends *s* with the ' 'contents of | |\n' '| | *t* (for the most ' 'part the same | |\n' '| | as "s[len(s):len(s)] ' '= t") | |\n' '+--------------------------------+----------------------------------+-----------------------+\n' '| "s *= n" | updates *s* with its ' 'contents | (6) |\n' '| | repeated *n* ' 'times | |\n' '+--------------------------------+----------------------------------+-----------------------+\n' '| "s.insert(i, x)" | inserts *x* into *s* ' 'at the | |\n' '| | index given by *i* ' '(same as | |\n' '| | "s[i:i] = ' '[x]") | |\n' '+--------------------------------+----------------------------------+-----------------------+\n' '| "s.pop([i])" | retrieves the item at ' '*i* and | (2) |\n' '| | also removes it from ' '*s* | |\n' '+--------------------------------+----------------------------------+-----------------------+\n' '| "s.remove(x)" | remove the first item ' 'from *s* | (3) |\n' '| | where "s[i]" is equal ' 'to *x* | |\n' '+--------------------------------+----------------------------------+-----------------------+\n' '| "s.reverse()" | reverses the items of ' '*s* in | (4) |\n' '| | ' 'place | ' '|\n' '+--------------------------------+----------------------------------+-----------------------+\n' '\n' 'Notes:\n' '\n' '1. *t* must have the same length as the slice it is ' 'replacing.\n' '\n' '2. The optional argument *i* defaults to "-1", so that ' 'by default the\n' ' last item is removed and returned.\n' '\n' '3. "remove()" raises "ValueError" when *x* is not found ' 'in *s*.\n' '\n' '4. The "reverse()" method modifies the sequence in place ' 'for economy\n' ' of space when reversing a large sequence. To remind ' 'users that it\n' ' operates by side effect, it does not return the ' 'reversed sequence.\n' '\n' '5. "clear()" and "copy()" are included for consistency ' 'with the\n' ' interfaces of mutable containers that don’t support ' 'slicing\n' ' operations (such as "dict" and "set"). "copy()" is ' 'not part of the\n' ' "collections.abc.MutableSequence" ABC, but most ' 'concrete mutable\n' ' sequence classes provide it.\n' '\n' ' New in version 3.3: "clear()" and "copy()" methods.\n' '\n' '6. The value *n* is an integer, or an object ' 'implementing\n' ' "__index__()". Zero and negative values of *n* clear ' 'the sequence.\n' ' Items in the sequence are not copied; they are ' 'referenced multiple\n' ' times, as explained for "s * n" under Common Sequence ' 'Operations.\n', 'unary': 'Unary arithmetic and bitwise operations\n' '***************************************\n' '\n' 'All unary arithmetic and bitwise operations have the same ' 'priority:\n' '\n' ' u_expr ::= power | "-" u_expr | "+" u_expr | "~" u_expr\n' '\n' 'The unary "-" (minus) operator yields the negation of its numeric\n' 'argument.\n' '\n' 'The unary "+" (plus) operator yields its numeric argument ' 'unchanged.\n' '\n' 'The unary "~" (invert) operator yields the bitwise inversion of ' 'its\n' 'integer argument. The bitwise inversion of "x" is defined as\n' '"-(x+1)". It only applies to integral numbers.\n' '\n' 'In all three cases, if the argument does not have the proper type, ' 'a\n' '"TypeError" exception is raised.\n', 'while': 'The "while" statement\n' '*********************\n' '\n' 'The "while" statement is used for repeated execution as long as an\n' 'expression is true:\n' '\n' ' while_stmt ::= "while" assignment_expression ":" suite\n' ' ["else" ":" suite]\n' '\n' 'This repeatedly tests the expression and, if it is true, executes ' 'the\n' 'first suite; if the expression is false (which may be the first ' 'time\n' 'it is tested) the suite of the "else" clause, if present, is ' 'executed\n' 'and the loop terminates.\n' '\n' 'A "break" statement executed in the first suite terminates the ' 'loop\n' 'without executing the "else" clause’s suite. A "continue" ' 'statement\n' 'executed in the first suite skips the rest of the suite and goes ' 'back\n' 'to testing the expression.\n', 'with': 'The "with" statement\n' '********************\n' '\n' 'The "with" statement is used to wrap the execution of a block with\n' 'methods defined by a context manager (see section With Statement\n' 'Context Managers). This allows common "try"…"except"…"finally" ' 'usage\n' 'patterns to be encapsulated for convenient reuse.\n' '\n' ' with_stmt ::= "with" with_item ("," with_item)* ":" suite\n' ' with_item ::= expression ["as" target]\n' '\n' 'The execution of the "with" statement with one “item” proceeds as\n' 'follows:\n' '\n' '1. The context expression (the expression given in the "with_item") ' 'is\n' ' evaluated to obtain a context manager.\n' '\n' '2. The context manager’s "__enter__()" is loaded for later use.\n' '\n' '3. The context manager’s "__exit__()" is loaded for later use.\n' '\n' '4. The context manager’s "__enter__()" method is invoked.\n' '\n' '5. If a target was included in the "with" statement, the return ' 'value\n' ' from "__enter__()" is assigned to it.\n' '\n' ' Note:\n' '\n' ' The "with" statement guarantees that if the "__enter__()" ' 'method\n' ' returns without an error, then "__exit__()" will always be\n' ' called. Thus, if an error occurs during the assignment to the\n' ' target list, it will be treated the same as an error occurring\n' ' within the suite would be. See step 6 below.\n' '\n' '6. The suite is executed.\n' '\n' '7. The context manager’s "__exit__()" method is invoked. If an\n' ' exception caused the suite to be exited, its type, value, and\n' ' traceback are passed as arguments to "__exit__()". Otherwise, ' 'three\n' ' "None" arguments are supplied.\n' '\n' ' If the suite was exited due to an exception, and the return ' 'value\n' ' from the "__exit__()" method was false, the exception is ' 'reraised.\n' ' If the return value was true, the exception is suppressed, and\n' ' execution continues with the statement following the "with"\n' ' statement.\n' '\n' ' If the suite was exited for any reason other than an exception, ' 'the\n' ' return value from "__exit__()" is ignored, and execution ' 'proceeds\n' ' at the normal location for the kind of exit that was taken.\n' '\n' 'The following code:\n' '\n' ' with EXPRESSION as TARGET:\n' ' SUITE\n' '\n' 'is semantically equivalent to:\n' '\n' ' manager = (EXPRESSION)\n' ' enter = type(manager).__enter__\n' ' exit = type(manager).__exit__\n' ' value = enter(manager)\n' ' hit_except = False\n' '\n' ' try:\n' ' TARGET = value\n' ' SUITE\n' ' except:\n' ' hit_except = True\n' ' if not exit(manager, *sys.exc_info()):\n' ' raise\n' ' finally:\n' ' if not hit_except:\n' ' exit(manager, None, None, None)\n' '\n' 'With more than one item, the context managers are processed as if\n' 'multiple "with" statements were nested:\n' '\n' ' with A() as a, B() as b:\n' ' SUITE\n' '\n' 'is semantically equivalent to:\n' '\n' ' with A() as a:\n' ' with B() as b:\n' ' SUITE\n' '\n' 'Changed in version 3.1: Support for multiple context expressions.\n' '\n' 'See also:\n' '\n' ' **PEP 343** - The “with” statement\n' ' The specification, background, and examples for the Python ' '"with"\n' ' statement.\n', 'yield': 'The "yield" statement\n' '*********************\n' '\n' ' yield_stmt ::= yield_expression\n' '\n' 'A "yield" statement is semantically equivalent to a yield ' 'expression.\n' 'The yield statement can be used to omit the parentheses that would\n' 'otherwise be required in the equivalent yield expression ' 'statement.\n' 'For example, the yield statements\n' '\n' ' yield <expr>\n' ' yield from <expr>\n' '\n' 'are equivalent to the yield expression statements\n' '\n' ' (yield <expr>)\n' ' (yield from <expr>)\n' '\n' 'Yield expressions and statements are only used when defining a\n' '*generator* function, and are only used in the body of the ' 'generator\n' 'function. Using yield in a function definition is sufficient to ' 'cause\n' 'that definition to create a generator function instead of a normal\n' 'function.\n' '\n' 'For full details of "yield" semantics, refer to the Yield ' 'expressions\n' 'section.\n'}
48.896303
118
0.436748
d663482835e339ca596e0d3b4f84a4e536851ea5
604
py
Python
aorist/setup.py
Vibrant-Planet/aorist
067e119ef4d0d40802ce74a8e47d882e557ce195
[ "MIT" ]
16
2021-08-14T10:20:16.000Z
2022-03-31T04:19:26.000Z
aorist/setup.py
scie-nz/aorist
ac1e31251af7d851c4491a310b417de880b79d09
[ "MIT" ]
5
2021-08-15T23:19:10.000Z
2021-09-26T20:50:41.000Z
aorist/setup.py
Vibrant-Planet/aorist
067e119ef4d0d40802ce74a8e47d882e557ce195
[ "MIT" ]
1
2022-01-06T01:26:24.000Z
2022-01-06T01:26:24.000Z
import sys import os from setuptools import setup from setuptools_rust import Binding, RustExtension # We set a specific cargo build target in windows if os.name == "nt": os.environ["CARGO_BUILD_TARGET"] = "x86_64-pc-windows-gnu" setup( name="aorist", version="0.0.1", rust_extensions=[RustExtension("aorist.aorist", binding=Binding.PyO3)], packages=["aorist"], # Rust extensions are not zip safe zip_safe=False, long_description=""" Aorist: ETL code generation for flexible environments and infrastructure """, long_description_content_type="text/x-rst" )
26.26087
76
0.718543
8e03fc8c87969afca5a90a106b5aad347203cbc8
1,527
py
Python
src/dq.py
Tannex/TSP
4b6b4187dda18da068572a2dd852eadef0d0f185
[ "MIT" ]
null
null
null
src/dq.py
Tannex/TSP
4b6b4187dda18da068572a2dd852eadef0d0f185
[ "MIT" ]
null
null
null
src/dq.py
Tannex/TSP
4b6b4187dda18da068572a2dd852eadef0d0f185
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 15 18:38:45 2018 @author: marco """ from data import * def dq_tsp(cities): """Find a tour by divide and conquer: if number of cities is 3 or less, any tour is optimal. Otherwise, split the cities in half, solve each half recursively, then join those two tours together.""" if len(cities) <= 3: return Tour(cities) else: Cs1, Cs2 = split_cities(cities) return join_tours(dq_tsp(Cs1), dq_tsp(Cs2)) def split_cities(cities): """Split cities vertically if map is wider; horizontally if map is taller.""" width, height = extent([c.x for c in cities]), extent([c.y for c in cities]) key = 'x' if (width > height) else 'y' cities = sorted(cities, key=lambda c: getattr(c, key)) mid = len(cities) // 2 return frozenset(cities[:mid]), frozenset(cities[mid:]) def extent(numbers): return max(numbers) - min(numbers) def join_tours(tour1, tour2): """Consider all ways of joining the two tours together, and pick the shortest.""" segments1, segments2 = rotations(tour1), rotations(tour2) tours = [s1 + s2 for s1 in segments1 for s in segments2 for s2 in (s, s[::-1])] return shortest_tour(tours) def rotations(sequence): """All possible rotations of a sequence.""" # A rotation is some suffix of the sequence followed by the rest of the sequence. return [sequence[i:] + sequence[:i] for i in range(len(sequence))]
32.489362
85
0.645711
38b79f759d28b3f817ed5eba64aaaf9a8046373c
2,471
py
Python
src/9.py
t0a5ted/aoc-2021
c94791d2f78ef89636a462f266cf7daead0e54cb
[ "MIT" ]
null
null
null
src/9.py
t0a5ted/aoc-2021
c94791d2f78ef89636a462f266cf7daead0e54cb
[ "MIT" ]
null
null
null
src/9.py
t0a5ted/aoc-2021
c94791d2f78ef89636a462f266cf7daead0e54cb
[ "MIT" ]
null
null
null
""" See: https://adventofcode.com/2021/day/9 """ from typing import * from functools import reduce def parse_input() -> List[List[int]]: data: List[List[int]] = [] with open('input/9.txt', 'r') as file: contents = file.read() for line in contents.split("\n"): data.append([int(char) for char in line]) return data def part1() -> int: # Brute force approach, as always data: List[List[int]] = parse_input() # print(data) risk_level_sum: int = 0 for y, row in enumerate(data): for x, n in enumerate(row): # adj left if x > 0 and n >= data[y][x-1]: continue # adj right if len(row) - 1 > x and n >= data[y][x+1]: continue # adj up if y > 0 and n >= data[y-1][x]: continue # adj down if len(data) - 1 > y and n >= data[y+1][x]: continue # low point, add to sum risk_level_sum += n + 1 return risk_level_sum def part2() -> int: data: List[List[int]] = parse_input() basins_len: List[int] = [] already_in_basin: List[Tuple[int, int]] = [] for y, row in enumerate(data): for x, n in enumerate(row): if (x, y) in already_in_basin: continue basin = get_basin(data, x, y) if basin != []: basins_len.append(len(basin)) already_in_basin += basin basins_len.sort() three_biggest_basin_lens: List[int] = basins_len[-3:] return reduce(lambda x, y: x * y, three_biggest_basin_lens, 1) def get_basin(grid: List[List[int]], x: int, y: int, basin: List[Tuple[int, int]] = None): if basin == None: basin = [] # python hates lists as default params, so this is a workaround if grid[y][x] == 9: return basin basin.append((x, y)) # adj left if x > 0 and (x-1, y) not in basin: basin = get_basin(grid, x-1, y, basin) # adj right if len(grid[0]) - 1 > x and (x+1, y) not in basin: basin = get_basin(grid, x+1, y, basin) # adj up if y > 0 and (x, y-1) not in basin: basin = get_basin(grid, x, y-1, basin) # adj down if len(grid) - 1 > y and (x, y+1) not in basin: basin = get_basin(grid, x, y+1, basin) return basin if __name__ == '__main__': print(part2())
27.764045
90
0.519628
4ffe9662302a69143eb34299d63d01d8cbabecd1
1,502
py
Python
pontoon/terminology/admin.py
desmosinc/pontoon
63733f320b9b6a7462b5b04f3b7bfb3e765a565f
[ "BSD-3-Clause" ]
1
2021-04-15T18:56:19.000Z
2021-04-15T18:56:19.000Z
pontoon/terminology/admin.py
desmosinc/pontoon
63733f320b9b6a7462b5b04f3b7bfb3e765a565f
[ "BSD-3-Clause" ]
7
2019-11-17T21:51:37.000Z
2020-06-26T14:59:49.000Z
pontoon/terminology/admin.py
desmosinc/pontoon
63733f320b9b6a7462b5b04f3b7bfb3e765a565f
[ "BSD-3-Clause" ]
null
null
null
from django.contrib import admin from django import forms from pontoon.terminology.models import Term, TermTranslation from pontoon.base.models import Locale class TermAdmin(admin.ModelAdmin): search_fields = [ "text", "part_of_speech", "definition", "usage", "notes", ] list_display = ( "text", "status", "part_of_speech", "definition", "usage", "notes", "case_sensitive", "exact_match", "do_not_translate", "forbidden", ) list_editable = ( "status", "part_of_speech", "case_sensitive", "exact_match", "do_not_translate", "forbidden", ) raw_id_fields = ("entity",) class LocaleChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return "{} ({})".format(obj.name, obj.code) class TermTranslationAdmin(admin.ModelAdmin): search_fields = [ "text", ] list_display = ("text", "term", "locale", "locale_code") def locale_code(self, term_translation): return term_translation.locale.code def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "locale": return LocaleChoiceField(queryset=Locale.objects.all()) return super().formfield_for_foreignkey(db_field, request, **kwargs) admin.site.register(Term, TermAdmin) admin.site.register(TermTranslation, TermTranslationAdmin)
24.622951
76
0.624501
98f49c7bcab0e797920f863ae7ce6e14930b7dee
4,313
py
Python
keystone_tempest_plugin/services/identity/v3/identity_providers_client.py
ilay09/keystone
e45049dfd46ab7d3e4c6aa48a3046f622f4a3b1e
[ "Apache-2.0" ]
null
null
null
keystone_tempest_plugin/services/identity/v3/identity_providers_client.py
ilay09/keystone
e45049dfd46ab7d3e4c6aa48a3046f622f4a3b1e
[ "Apache-2.0" ]
1
2019-08-18T09:25:49.000Z
2019-08-18T09:25:49.000Z
keystone_tempest_plugin/services/identity/v3/identity_providers_client.py
ilay09/keystone
e45049dfd46ab7d3e4c6aa48a3046f622f4a3b1e
[ "Apache-2.0" ]
null
null
null
# Copyright 2016 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import json import six from tempest.lib.common import rest_client from keystone_tempest_plugin.services.identity import clients class IdentityProvidersClient(clients.Federation): subpath_suffix = 'identity_providers' def create_identity_provider(self, idp_id, **kwargs): """Create an identity provider. :param str idp_id: The ID to be used to create the Identity Provider. :param kwargs: All optional attributes: description (str), enabled (boolean) and remote_ids (list). """ put_body = json.dumps({'identity_provider': kwargs}) return self._put(idp_id, put_body) def list_identity_providers(self): """List the identity providers.""" return self._get() def show_identity_provider(self, idp_id): """Get an identity provider.""" return self._get(idp_id) def delete_identity_provider(self, idp_id): """Delete an identity provider.""" return self._delete(idp_id) def update_identity_provider(self, idp_id, **kwargs): """Update an identity provider. :param str idp_id: The ID from the Identity Provider to be updated. :param kwargs: All optional attributes to update: description (str), enabled (boolean) and remote_ids (list). """ patch_body = json.dumps({'identity_provider': kwargs}) return self._patch(idp_id, patch_body) def add_protocol_and_mapping(self, idp_id, protocol_id, mapping_id): """Add a protocol and mapping to an identity provider.""" put_body = json.dumps({'protocol': {'mapping_id': mapping_id}}) url = '%s/%s/%s' % ( self._build_path(entity_id=idp_id), 'protocols', protocol_id) resp, body = self.put(url, put_body) self.expected_success(201, resp.status) body = json.loads(body if six.PY2 else body.decode('utf-8')) return rest_client.ResponseBody(resp, body) def delete_protocol_and_mapping(self, idp_id, protocol_id): """Delete a protocol and mapping from an identity provider.""" url = '%s/%s/%s' % ( self._build_path(entity_id=idp_id), 'protocols', protocol_id) resp, body = self.delete(url) self.expected_success(204, resp.status) return rest_client.ResponseBody(resp, body) def get_protocol_and_mapping(self, idp_id, protocol_id): """Get a protocol and mapping from an identity provider.""" url = '%s/%s/%s' % ( self._build_path(entity_id=idp_id), 'protocols', protocol_id) resp, body = self.get(url) self.expected_success(200, resp.status) body = json.loads(body if six.PY2 else body.decode('utf-8')) return rest_client.ResponseBody(resp, body) def list_protocols_and_mappings(self, idp_id): """List the protocols and mappings from an identity provider.""" url = '%s/%s' % (self._build_path(entity_id=idp_id), 'protocols') resp, body = self.get(url) self.expected_success(200, resp.status) body = json.loads(body if six.PY2 else body.decode('utf-8')) return rest_client.ResponseBody(resp, body) def update_protocol_mapping(self, idp_id, protocol_id, mapping_id): """Update the identity provider protocol with a new mapping.""" patch_body = json.dumps({'protocol': {'mapping_id': mapping_id}}) url = '%s/%s/%s' % ( self._build_path(entity_id=idp_id), 'protocols', protocol_id) resp, body = self.patch(url, patch_body) self.expected_success(200, resp.status) body = json.loads(body if six.PY2 else body.decode('utf-8')) return rest_client.ResponseBody(resp, body)
41.873786
77
0.667517
b6a79e42df1dd15c58701889ffa59fc6a6b613b9
599
py
Python
start.py
bmuchemi/Pitches
daa80d5b16d0b7aa2879dac29b7aa75abe19e461
[ "MIT" ]
null
null
null
start.py
bmuchemi/Pitches
daa80d5b16d0b7aa2879dac29b7aa75abe19e461
[ "MIT" ]
null
null
null
start.py
bmuchemi/Pitches
daa80d5b16d0b7aa2879dac29b7aa75abe19e461
[ "MIT" ]
null
null
null
from app import create_app, db from app.models import User, Pitches from flask_script import Manager, Server from flask_migrate import Migrate, MigrateCommand app = create_app('dev') manager = Manager(app) manager.add_command('server', Server) migrate = Migrate(app,db) manager.add_command('db', MigrateCommand) @manager.command def test(): import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) @manager.shell def make_shell_context(): return dict(app=app, db=db, User=User) if __name__ == '__main__': manager.run()
23.96
51
0.751252
37fde1c9636e623021470a2132f67e54ae411678
526
py
Python
Study-Basic/001_study_print.py
Cpaul777/Script-Archive
2c2d99d41206d98486d9aebdf1acbb0c06b4513d
[ "MIT" ]
4
2021-01-28T12:01:08.000Z
2021-01-28T14:04:45.000Z
Study-Basic/001_study_print.py
Xzlaynveir-Deirdre/Script-Archive
e937129466ebd15272c23df76d3b8a459e62a51d
[ "MIT" ]
null
null
null
Study-Basic/001_study_print.py
Xzlaynveir-Deirdre/Script-Archive
e937129466ebd15272c23df76d3b8a459e62a51d
[ "MIT" ]
1
2021-12-18T11:17:51.000Z
2021-12-18T11:17:51.000Z
"""Link to the source https://youtu.be/k9TUPpGqYTo""" LINER = '\n-----\n' TEXT = "I am studying python that is taught by Corey in his video" print(TEXT) print(LINER + 'This is called slicing' + LINER) print(TEXT[20]) print(LINER) print(TEXT[20:30]) print(LINER) print(TEXT[9:]) print(LINER + 'This is called Methods' + LINER) print(TEXT.upper()) print(LINER) print(TEXT.lower()) print(LINER) print(TEXT.count("i")) print(LINER) print(TEXT.find('is')) OLD = 'happy but never laugh' NEW = OLD.replace('happy','sad') print(NEW)
22.869565
66
0.692015
6553385170466067bcde4572d25228e177e43455
630
py
Python
var/spack/repos/builtin/packages/r-miniui/package.py
player1537-forks/spack
822b7632222ec5a91dc7b7cda5fc0e08715bd47c
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
11
2015-10-04T02:17:46.000Z
2018-02-07T18:23:00.000Z
var/spack/repos/builtin/packages/r-miniui/package.py
player1537-forks/spack
822b7632222ec5a91dc7b7cda5fc0e08715bd47c
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
22
2017-08-01T22:45:10.000Z
2022-03-10T07:46:31.000Z
var/spack/repos/builtin/packages/r-miniui/package.py
player1537-forks/spack
822b7632222ec5a91dc7b7cda5fc0e08715bd47c
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
4
2016-06-10T17:57:39.000Z
2018-09-11T04:59:38.000Z
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RMiniui(RPackage): """Shiny UI Widgets for Small Screens. Provides UI widget and layout functions for writing Shiny apps that work well on small screens.""" cran = "miniUI" version('0.1.1.1', sha256='452b41133289f630d8026507263744e385908ca025e9a7976925c1539816b0c0') depends_on('r-shiny@0.13:', type=('build', 'run')) depends_on('r-htmltools@0.3:', type=('build', 'run'))
30
97
0.719048
8c5b150c841d1ad2adaa4a0cd7eeed74dbd44243
750
py
Python
book/migrations/0001_initial.py
nightlyds/library-basic-authentication-server
80a5aabe91c0c406459ebd51bfdcb510b8d1e842
[ "MIT" ]
null
null
null
book/migrations/0001_initial.py
nightlyds/library-basic-authentication-server
80a5aabe91c0c406459ebd51bfdcb510b8d1e842
[ "MIT" ]
null
null
null
book/migrations/0001_initial.py
nightlyds/library-basic-authentication-server
80a5aabe91c0c406459ebd51bfdcb510b8d1e842
[ "MIT" ]
1
2021-07-04T14:21:08.000Z
2021-07-04T14:21:08.000Z
# Generated by Django 3.2.4 on 2021-06-29 09:09 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('author', '0001_initial'), ] operations = [ migrations.CreateModel( name='Book', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(blank=True, max_length=128)), ('description', models.TextField(blank=True)), ('count', models.IntegerField(default=10)), ('authors', models.ManyToManyField(related_name='books', to='author.Author')), ], ), ]
28.846154
114
0.573333
0a0eba80ad2d5c80be53c05a649d174d52553ce0
3,814
py
Python
libraries/linters/tn_linter.py
mondele/tx-manager
ddbbeeae5990a327ffc14b42c478d3ea435c0533
[ "MIT" ]
3
2017-03-17T02:25:21.000Z
2017-05-18T22:18:20.000Z
libraries/linters/tn_linter.py
mondele/tx-manager
ddbbeeae5990a327ffc14b42c478d3ea435c0533
[ "MIT" ]
184
2016-10-13T02:56:16.000Z
2021-03-25T21:27:20.000Z
libraries/linters/tn_linter.py
mondele/tx-manager
ddbbeeae5990a327ffc14b42c478d3ea435c0533
[ "MIT" ]
16
2016-09-15T23:34:19.000Z
2019-07-25T07:06:32.000Z
from __future__ import print_function, unicode_literals import os import re from libraries.app.app import App from libraries.door43_tools.bible_books import BOOK_NUMBERS from libraries.general_tools import file_utils from libraries.linters.markdown_linter import MarkdownLinter class TnLinter(MarkdownLinter): # match links of form '](link)' link_marker_re = re.compile(r'\]\(([^\n()]+)\)', re.UNICODE) def __init__(self, single_file=None, *args, **kwargs): super(MarkdownLinter, self).__init__(*args, **kwargs) self.single_file = single_file App.logger.debug("Convert single '{0}'".format(self.single_file)) self.single_dir = None if self.single_file: parts = os.path.splitext(self.single_file) self.single_dir = self.get_dir_for_book(parts[0]) App.logger.debug("Single source dir '{0}'".format(self.single_dir)) def lint(self): """ Checks for issues with translationNotes Use self.log.warning("message") to log any issues. self.source_dir is the directory of source files (.md) :return boolean: """ self.source_dir = os.path.abspath(self.source_dir) source_dir = self.source_dir if not self.single_dir else os.path.join(self.source_dir, self.single_dir) for root, dirs, files in os.walk(source_dir): for f in files: file_path = os.path.join(root, f) parts = os.path.splitext(f) if parts[1] == '.md': contents = file_utils.read_file(file_path) self.find_invalid_links(root, f, contents) for dir in BOOK_NUMBERS: found_files = False if self.single_dir and (dir != self.single_dir): continue App.logger.debug("Processing folder {0}".format(dir)) file_path = os.path.join(self.source_dir, dir) for root, dirs, files in os.walk(file_path): if root == file_path: continue # skip book folder if len(files) > 0: found_files = True break if not found_files: msg = "missing book: '{0}'".format(dir) self.log.warnings.append(msg) App.logger.debug(msg) results = super(TnLinter, self).lint() # Runs checks on Markdown, using the markdown linter if not results: App.logger.debug("Error running MD linter on {0}".format(self.s3_results_key)) return results def find_invalid_links(self, folder, f, contents): for link_match in TnLinter.link_marker_re.finditer(contents): link = link_match.group(1) if link: if link[:4] == 'http': continue if link.find('.md') < 0: continue file_path = os.path.join(folder, link) file_path_abs = os.path.abspath(file_path) exists = os.path.exists(file_path_abs) if not exists: a = self.get_file_link(f, folder) msg = "{0}: contains invalid link: ({1})".format(a, link) self.log.warnings.append(msg) App.logger.debug(msg) def get_file_link(self, f, folder): parts = folder.split(self.source_dir) sub_path = self.source_dir # default if len(parts) == 2: sub_path = parts[1][1:] url = "https://git.door43.org/{0}/{1}/src/master/{2}/{3}".format(self.repo_owner, self.repo_name, sub_path, f) a = '<a href="{0}">{1}/{2}</a>'.format(url, sub_path, f) return a
40.147368
111
0.566072
c8d69b50bcffb488bb9b4899469404cb7e30e909
6,077
py
Python
dxf_stuff/dxf_plugins.py
trevorpeacock/kicad_mmccoo
3f0efb38549f8de1daf2face6a15377084c5cde6
[ "Apache-2.0" ]
1
2021-11-18T11:59:50.000Z
2021-11-18T11:59:50.000Z
dxf_stuff/dxf_plugins.py
trevorpeacock/kicad_mmccoo
3f0efb38549f8de1daf2face6a15377084c5cde6
[ "Apache-2.0" ]
null
null
null
dxf_stuff/dxf_plugins.py
trevorpeacock/kicad_mmccoo
3f0efb38549f8de1daf2face6a15377084c5cde6
[ "Apache-2.0" ]
null
null
null
import pcbnew import wx import os import sys import inspect import pdb from . import dxf_utils from ..simpledialog import DialogUtils import os.path from .dxf_utils import zone_actions from .dxf_utils import segment_actions from .dxf_utils import orient_actions from .dxf_utils import mounting_actions from .dxf_utils import traverse_dxf from .dxf_utils import traverse_graphics from . import mounting class DXFZoneDialog(DialogUtils.BaseDialog): def __init__(self): super(DXFZoneDialog, self).__init__("DXF Dialog") homedir = os.path.expanduser("~") self.file_picker = DialogUtils.FilePicker(self, homedir, wildcard="DXF files (.dxf)|*.dxf", configname="DXFZonedialog") self.AddLabeled(item=self.file_picker, label="DXF file", proportion=0, flag=wx.ALL, border=2) self.basic_layer = DialogUtils.BasicLayerPicker(self, layers=['F.Cu', 'B.Cu']) self.AddLabeled(item=self.basic_layer, label="Target layer", border=2) self.net = DialogUtils.NetPicker(self) self.AddLabeled(item=self.net, label="Target Net", proportion=1, flag=wx.EXPAND|wx.ALL, border=2) # make the dialog a little taller than minimum to give the layer and net # lists a bit more space. self.IncSize(height=5) class DXFZonePlugin(pcbnew.ActionPlugin): def defaults(self): self.name = "Convert a DXF to a zone" self.category = "A descriptive category name" self.description = "This plugin reads a dxf file and converts it to a zone" def Run(self): dlg = DXFZoneDialog() res = dlg.ShowModal() if res == wx.ID_OK: print("ok") if (dlg.net.value == None): warndlg = wx.MessageDialog(self, "no net was selected", "Error", wx.OK | wx.ICON_WARNING) warndlg.ShowModal() warndlg.Destroy() return net = dlg.net.GetValuePtr() traverse_dxf(dlg.file_picker.value, zone_actions(pcbnew.GetBoard(), net, dlg.basic_layer.valueint), merge_polys=True, break_curves=True ) #pcbnew.Refresh() else: print("cancel") DXFZonePlugin().register() class DXFGraphicDialog(DialogUtils.BaseDialog): def __init__(self): super(DXFGraphicDialog, self).__init__("DXF Dialog") homedir = os.path.expanduser("~") self.file_picker = DialogUtils.FilePicker(self, homedir, wildcard="DXF files (.dxf)|*.dxf", configname="DXFGraphicdialog") self.AddLabeled(item=self.file_picker, label="DXF file", proportion=0, flag=wx.ALL, border=2) self.basic_layer = DialogUtils.BasicLayerPicker(self) self.AddLabeled(item=self.basic_layer, label="Target layer", border=2) class DXFGraphicPlugin(pcbnew.ActionPlugin): def defaults(self): self.name = "Convert a DXF to a graphic (Edge.Cuts, User.Cmts,...)" self.category = "A descriptive category name" self.description = "This plugin reads a dxf file and converts it to a zone" def Run(self): dlg = DXFGraphicDialog() res = dlg.ShowModal() print("dxf file {}".format(dlg.file_picker.value)) print("layer {}".format(dlg.basic_layer.value)) if res == wx.ID_OK: print("ok") traverse_dxf(dlg.file_picker.value, segment_actions(pcbnew.GetBoard(), dlg.basic_layer.valueint), merge_polys=False, break_curves=True) else: print("cancel") DXFGraphicPlugin().register() class OrientToGraphicDialog(DialogUtils.BaseDialog): def __init__(self): super(OrientToGraphicDialog, self).__init__("Orient to Graphic") self.basic_layer = DialogUtils.BasicLayerPicker(self, layers=['Cmts.User', 'Eco1.User', 'Eco2.User']) self.AddLabeled(item=self.basic_layer, label="Target layer", border=2) self.mods = DialogUtils.ModulePicker(self, singleton=False) self.AddLabeled(item=self.mods, label="all mods", proportion=1, flag=wx.EXPAND|wx.ALL, border=2) class OrientToGraphicPlugin(pcbnew.ActionPlugin): def defaults(self): self.name = "Orient the selected modules to underlying graphics" self.category = "A descriptive category name" self.description = "This plugin moves/orients selected modules to align with graphic" def Run(self): dlg = OrientToGraphicDialog() res = dlg.ShowModal() print("layer {}".format(dlg.basic_layer.value)) print("mods {}".format(dlg.mods.value)) traverse_graphics(pcbnew.GetBoard(), dlg.basic_layer.value, orient_actions(pcbnew.GetBoard(), dlg.mods.value), merge_polys=True, break_curves=True) OrientToGraphicPlugin().register() class DXFToMountingPlugin(pcbnew.ActionPlugin): def defaults(self): self.name = "DXF circles to modules" self.category = "A descriptive category name" self.description = "This plugin places a module for each circle in a DXF" def Run(self): dlg = mounting.MountingDialog(configname = "mountingmap") res = dlg.ShowModal() if res != wx.ID_OK: return traverse_dxf(dlg.file_picker.value, mounting_actions(pcbnew.GetBoard(), dlg.value, flip=dlg.flip.GetValue())) DXFToMountingPlugin().register()
34.140449
109
0.586474
6e7398e4d68af320da23447b52f58de5107598e5
258
py
Python
src/djrtime/tests/wsgi.py
amitu/rtime
6e23a2f86a2cae4399932879f0d157f8e63a8358
[ "BSD-3-Clause" ]
2
2017-04-01T14:05:58.000Z
2017-04-02T07:57:56.000Z
src/djrtime/tests/wsgi.py
amitu/rtime
6e23a2f86a2cae4399932879f0d157f8e63a8358
[ "BSD-3-Clause" ]
3
2016-11-08T08:00:08.000Z
2016-11-08T08:15:20.000Z
src/djrtime/tests/wsgi.py
amitu/rtime
6e23a2f86a2cae4399932879f0d157f8e63a8358
[ "BSD-3-Clause" ]
null
null
null
import os import django from djrtime.handlers import TimeItHandler os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tests.settings') if django.VERSION >= (1, 10): django.setup(set_prefix=False) else: django.setup() application = TimeItHandler()
17.2
65
0.755814
92f9140d89e34d8f1bc8e3a2abacbb1b8c332179
673
py
Python
userbot/modules/heroku.py
sanakek/OpenUserBot
aae1238a9ee4aff7c617554b4ed2ad73f812c246
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
userbot/modules/heroku.py
sanakek/OpenUserBot
aae1238a9ee4aff7c617554b4ed2ad73f812c246
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
userbot/modules/heroku.py
sanakek/OpenUserBot
aae1238a9ee4aff7c617554b4ed2ad73f812c246
[ "Naumen", "Condor-1.1", "MS-PL" ]
3
2020-02-25T10:49:04.000Z
2020-03-29T02:16:33.000Z
# Copyright (C) 2020 Adek Maulana. # All rights reserved. """ Heroku manager for your userbot """ import heroku3 from userbot import CMD_HELP, LOGS, HEROKU_APP_NAME, HEROKU_API_KEY from userbot.events import register Heroku = heroku3.from_key(HEROKU_API_KEY) @register(outgoing=True, pattern=r"^.heroku(?: |$)(.*)") async def heroku_manager(heroku): await heroku.edit("`Processing...`") conf = heroku.pattern_match.group(1) hours_remaining = Heroku.ratelimit_remaining() await heroku.edit(f"**Heroku** rate limit remaining: {hours_remaining}") return CMD_HELP.update({ "heroku": "`.heroku`" "Usage: Your heroku account manager" })
23.206897
76
0.710253
02aa4e3dba89af70439a3b3d26b84a05666e637e
644
py
Python
python/list_examples.py
matheuskiser/pdx_code_guild
49a5c62fb468253eb4d9a1fb11166df79bb10873
[ "MIT" ]
null
null
null
python/list_examples.py
matheuskiser/pdx_code_guild
49a5c62fb468253eb4d9a1fb11166df79bb10873
[ "MIT" ]
null
null
null
python/list_examples.py
matheuskiser/pdx_code_guild
49a5c62fb468253eb4d9a1fb11166df79bb10873
[ "MIT" ]
null
null
null
# Assign list of careers careers = ['Developer', 'Cook', 'Server', 'Doctor'] # Assign list of user inputs user_input = ['Chef', 'Principal', 'Developer', 'Doctor'] # Finds the index of each item for i in careers: print "Index of " + i + " is: " + str(careers.index(i)) # Checks to see if item is in list print "\n" for i in user_input: print "Is " + i + " in Careers list?" print i in careers # Append a new career to the list careers.append('Bar Tender') # Insert a new career at the beginning of the list careers.insert(0, 'Accountant') # Print out list print "\nHere is the full Careers list:" for i in careers: print i
24.769231
59
0.670807
c033ffce2757918dff987c80009bdcccf07f6b63
963
py
Python
settings/migrations/0002_setting_region.py
stanwood/traidoo-api
83e8599f2eb54352988bac27e2d4acd30734816d
[ "MIT" ]
3
2020-05-05T12:12:09.000Z
2020-05-08T08:48:16.000Z
settings/migrations/0002_setting_region.py
stanwood/traidoo-api
83e8599f2eb54352988bac27e2d4acd30734816d
[ "MIT" ]
160
2020-05-19T13:03:43.000Z
2022-03-12T00:35:28.000Z
settings/migrations/0002_setting_region.py
stanwood/traidoo-api
83e8599f2eb54352988bac27e2d4acd30734816d
[ "MIT" ]
null
null
null
# Generated by Django 2.2.4 on 2020-02-06 09:11 from django.db import migrations, models import django.db.models.deletion def apply_region(apps, schema_editor): db_alias = schema_editor.connection.alias RegionModel = apps.get_model("common", "Region") region, _ = RegionModel.objects.using(db_alias).get_or_create(name="mcswiss") SettingModel = apps.get_model('settings', 'Setting') SettingModel.objects.using(db_alias).update(region=region) class Migration(migrations.Migration): dependencies = [ ('common', '0001_initial'), ('settings', '0001_initial'), ] operations = [ migrations.AddField( model_name='setting', name='region', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='settings', to='common.Region'), ), migrations.RunPython(apply_region, reverse_code=lambda *args: True) ]
30.09375
149
0.682243
93228aa0edc9c8d46056e83a03a203a67fa587fc
700
py
Python
tests/test_issue34_errorlevel.py
dbajar/segno
f7d5669537b12d3ebb914ae6d0a0a1e14f8d25f5
[ "BSD-3-Clause" ]
254
2016-09-25T21:32:00.000Z
2022-03-30T09:56:14.000Z
tests/test_issue34_errorlevel.py
dbajar/segno
f7d5669537b12d3ebb914ae6d0a0a1e14f8d25f5
[ "BSD-3-Clause" ]
102
2016-08-04T12:18:44.000Z
2022-03-23T09:09:51.000Z
tests/test_issue34_errorlevel.py
dbajar/segno
f7d5669537b12d3ebb914ae6d0a0a1e14f8d25f5
[ "BSD-3-Clause" ]
34
2016-09-25T21:34:42.000Z
2022-03-30T08:19:03.000Z
# -*- coding: utf-8 -*- # # Copyright (c) 2016 - 2020 -- Lars Heuer # All rights reserved. # # License: BSD License # """\ Tests against issue 34 <https://github.com/heuer/segno/issues/34> """ from __future__ import absolute_import, unicode_literals import pytest import segno try: from .tutils import read_matrix # Attempted relative import in non-package except (ValueError, SystemError, ImportError): from tutils import read_matrix def test_m3_wikipedia(): qr = segno.make('Wikipedia', version='m3') assert 'M3-L' == qr.designator ref_matrix = read_matrix('issue-33-m3-l-wikipedia') assert ref_matrix == qr.matrix if __name__ == '__main__': pytest.main([__file__])
22.580645
56
0.708571
d7a2632ad36ad45358c281be5066a7eb916359e6
6,852
py
Python
python_msx_sdk/model/smart_account_user_role.py
CiscoDevNet/python-msx-sdk
d7e0a08c656504b4f4551d263e67c671a2a04b3f
[ "MIT" ]
null
null
null
python_msx_sdk/model/smart_account_user_role.py
CiscoDevNet/python-msx-sdk
d7e0a08c656504b4f4551d263e67c671a2a04b3f
[ "MIT" ]
null
null
null
python_msx_sdk/model/smart_account_user_role.py
CiscoDevNet/python-msx-sdk
d7e0a08c656504b4f4551d263e67c671a2a04b3f
[ "MIT" ]
null
null
null
""" MSX SDK MSX SDK client. # noqa: E501 The version of the OpenAPI document: 1.0.9 Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from python_msx_sdk.model_utils import ( # noqa: F401 ApiTypeError, ModelComposed, ModelNormal, ModelSimple, cached_property, change_keys_js_to_python, convert_js_args_to_python_args, date, datetime, file_type, none_type, validate_get_composed_info, ) class SmartAccountUserRole(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict with a capitalized key describing the allowed value and an allowed value. These dicts store the allowed enum values. attribute_map (dict): The key is attribute name and the value is json key in definition. discriminator_value_class_map (dict): A dict to go from the discriminator variable value to the discriminator class name. validations (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict that stores validations for max_length, min_length, max_items, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, inclusive_minimum, and regex. additional_properties_type (tuple): A tuple of classes accepted as additional properties values. """ allowed_values = { } validations = { } additional_properties_type = None _nullable = False @cached_property def openapi_types(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded Returns openapi_types (dict): The key is attribute name and the value is attribute type. """ return { 'role_name': (str,), # noqa: E501 'virtual_account_id': (int,), # noqa: E501 'virtual_account_name': (str,), # noqa: E501 } @cached_property def discriminator(): return None attribute_map = { 'role_name': 'roleName', # noqa: E501 'virtual_account_id': 'virtualAccountId', # noqa: E501 'virtual_account_name': 'virtualAccountName', # noqa: E501 } _composed_schemas = {} required_properties = set([ '_data_store', '_check_type', '_spec_property_naming', '_path_to_item', '_configuration', '_visited_composed_classes', ]) @convert_js_args_to_python_args def __init__(self, *args, **kwargs): # noqa: E501 """SmartAccountUserRole - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) role_name (str): [optional] # noqa: E501 virtual_account_id (int): Virtual Account identifier. [optional] # noqa: E501 virtual_account_name (str): Virtual Account Name. [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', False) _path_to_item = kwargs.pop('_path_to_item', ()) _configuration = kwargs.pop('_configuration', None) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ self.additional_properties_type is None: # discard variable. continue setattr(self, var_name, var_value)
39.606936
110
0.584063
1bda6513c1244df9aa4e23c26bae3a097d90874e
974
py
Python
metaspace/engine/sm/engine/annotation/mzml_parser.py
METASPACE2020/METASPACE
e1acd9a409f84a78eed7ca9713258c09b0e137ca
[ "Apache-2.0" ]
32
2018-08-13T15:49:42.000Z
2022-01-17T18:32:19.000Z
metaspace/engine/sm/engine/annotation/mzml_parser.py
METASPACE2020/METASPACE
e1acd9a409f84a78eed7ca9713258c09b0e137ca
[ "Apache-2.0" ]
624
2018-07-02T15:18:22.000Z
2022-03-30T08:10:35.000Z
metaspace/engine/sm/engine/annotation/mzml_parser.py
METASPACE2020/METASPACE
e1acd9a409f84a78eed7ca9713258c09b0e137ca
[ "Apache-2.0" ]
6
2021-01-10T22:24:30.000Z
2022-03-16T19:14:37.000Z
class MzMLParser: def __init__(self, filename): self.experiment = self.read_ms1_experiment(filename) self.coordinates = [(i, 1, 1) for i in range(1, self.experiment.size() + 1)] @staticmethod def read_ms1_experiment(filepath): # pylint: disable=import-outside-toplevel,no-name-in-module,import-error from pyopenms import FileHandler, MSExperiment source_experiment = MSExperiment() file_handler = FileHandler() # bytes is required by `loadExperiment()` called below typed_fp = filepath if isinstance(filepath, bytes) else filepath.encode() file_handler.loadExperiment(typed_fp, source_experiment) ms1_experiment = MSExperiment() for spectrum in source_experiment: if spectrum.getMSLevel() == 1: ms1_experiment.addSpectrum(spectrum) return ms1_experiment def getspectrum(self, idx): return self.experiment[idx].get_peaks()
38.96
84
0.678645
365f0bb4410ff4058f2d49104c0747f32513d9ab
3,482
py
Python
autotest/t052_test.py
hansonmcoombs/flopy
49398983c36d381992621d5bf698ea7f78fc0014
[ "CC0-1.0", "BSD-3-Clause" ]
null
null
null
autotest/t052_test.py
hansonmcoombs/flopy
49398983c36d381992621d5bf698ea7f78fc0014
[ "CC0-1.0", "BSD-3-Clause" ]
null
null
null
autotest/t052_test.py
hansonmcoombs/flopy
49398983c36d381992621d5bf698ea7f78fc0014
[ "CC0-1.0", "BSD-3-Clause" ]
null
null
null
import os import numpy as np import pymake from ci_framework import FlopyTestSetup, base_test_dir import flopy base_dir = base_test_dir(__file__, rel_path="temp", verbose=True) exe_name = "mf2005" v = flopy.which(exe_name) run = True if v is None: run = False def test_binary_well(): model_ws = f"{base_dir}_test_binary_well" test_setup = FlopyTestSetup(verbose=True, test_dirs=model_ws) nlay = 3 nrow = 3 ncol = 3 mfnam = "t1" ml = flopy.modflow.Modflow( modelname=mfnam, model_ws=model_ws, verbose=True, exe_name=exe_name, ) dis = flopy.modflow.ModflowDis( ml, nlay=nlay, nrow=nrow, ncol=ncol, top=0, botm=[-1.0, -2.0, -3.0] ) ibound = np.ones((nlay, nrow, ncol), dtype=int) ibound[0, 1, 1] = 0 ibound[0, 0, -1] = -1 bas = flopy.modflow.ModflowBas(ml, ibound=ibound) lpf = flopy.modflow.ModflowLpf(ml, ipakcb=102) wd = flopy.modflow.ModflowWel.get_empty(ncells=2, aux_names=["v1", "v2"]) wd["k"][0] = 2 wd["i"][0] = 2 wd["j"][0] = 2 wd["flux"][0] = -1000.0 wd["v1"][0] = 1.0 wd["v2"][0] = 2.0 wd["k"][1] = 2 wd["i"][1] = 1 wd["j"][1] = 1 wd["flux"][1] = -500.0 wd["v1"][1] = 200.0 wd["v2"][1] = 100.0 wel_data = {0: wd} wel = flopy.modflow.ModflowWel( ml, stress_period_data=wel_data, dtype=wd.dtype ) oc = flopy.modflow.ModflowOc(ml) pcg = flopy.modflow.ModflowPcg(ml) ml.write_input() # run the modflow-2005 model if run: success, buff = ml.run_model(silent=False) assert success, "could not run MODFLOW-2005 model" fn0 = os.path.join(model_ws, f"{mfnam}.nam") # load the model m = flopy.modflow.Modflow.load( f"{mfnam}.nam", model_ws=model_ws, verbose=True, exe_name=exe_name, ) wl = m.wel.stress_period_data[0] msg = ( "previous well package stress period data does not match " + "stress period data loaded." ) assert np.array_equal(wel.stress_period_data[0], wl), msg # change model work space pth = os.path.join(model_ws, "flopy") m.change_model_ws(new_pth=pth) # remove the existing well package m.remove_package("WEL") # recreate well package with binary output wel = flopy.modflow.ModflowWel( m, stress_period_data=wel_data, binary=True, dtype=wd.dtype ) # write the model to the new path m.write_input() # run the new modflow-2005 model if run: success, buff = m.run_model(silent=False) assert success, "could not run the new MODFLOW-2005 model" fn1 = os.path.join(pth, f"{mfnam}.nam") # compare the files if run: fsum = os.path.join(model_ws, f"{os.path.splitext(mfnam)[0]}.head.out") success = False try: success = pymake.compare_heads(fn0, fn1, outfile=fsum) except: print("could not perform head comparison") assert success, "head comparison failure" fsum = os.path.join( model_ws, f"{os.path.splitext(mfnam)[0]}.budget.out" ) success = False try: success = pymake.compare_budget( fn0, fn1, max_incpd=0.1, max_cumpd=0.1, outfile=fsum ) except: print("could not perform budget comparison") assert success, "budget comparison failure" if __name__ == "__main__": test_binary_well()
26.378788
79
0.598794
2430e453c4dfe138e2cbf8708b71534d27d336a0
8,013
py
Python
AppServer/google/net/proto2/python/public/service.py
loftwah/appscale
586fc1347ebc743d7a632de698f4dbfb09ae38d6
[ "Apache-2.0" ]
790
2015-01-03T02:13:39.000Z
2020-05-10T19:53:57.000Z
AppServer/google/net/proto2/python/public/service.py
nlake44/appscale
6944af660ca4cb772c9b6c2332ab28e5ef4d849f
[ "Apache-2.0" ]
1,361
2015-01-08T23:09:40.000Z
2020-04-14T00:03:04.000Z
AppServer/google/net/proto2/python/public/service.py
nlake44/appscale
6944af660ca4cb772c9b6c2332ab28e5ef4d849f
[ "Apache-2.0" ]
155
2015-01-08T22:59:31.000Z
2020-04-08T08:01:53.000Z
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """DEPRECATED: Declares the RPC service interfaces. This module declares the abstract interfaces underlying proto2 RPC services. These are intended to be independent of any particular RPC implementation, so that proto2 services can be used on top of a variety of implementations. Starting with version 2.3.0, RPC implementations should not try to build on these, but should instead provide code generator plugins which generate code specific to the particular RPC implementation. This way the generated code can be more appropriate for the implementation in use and can avoid unnecessary layers of indirection. """ class RpcException(Exception): """Exception raised on failed blocking RPC method call.""" pass class Service(object): """Abstract base interface for protocol-buffer-based RPC services. Services themselves are abstract classes (implemented either by servers or as stubs), but they subclass this base interface. The methods of this interface can be used to call the methods of the service without knowing its exact type at compile time (analogous to the Message interface). """ def GetDescriptor(): """Retrieves this service's descriptor.""" raise NotImplementedError def CallMethod(self, method_descriptor, rpc_controller, request, done): """Calls a method of the service specified by method_descriptor. If "done" is None then the call is blocking and the response message will be returned directly. Otherwise the call is asynchronous and "done" will later be called with the response value. In the blocking case, RpcException will be raised on error. Preconditions: * method_descriptor.service == GetDescriptor * request is of the exact same classes as returned by GetRequestClass(method). * After the call has started, the request must not be modified. * "rpc_controller" is of the correct type for the RPC implementation being used by this Service. For stubs, the "correct type" depends on the RpcChannel which the stub is using. Postconditions: * "done" will be called when the method is complete. This may be before CallMethod() returns or it may be at some point in the future. * If the RPC failed, the response value passed to "done" will be None. Further details about the failure can be found by querying the RpcController. """ raise NotImplementedError def GetRequestClass(self, method_descriptor): """Returns the class of the request message for the specified method. CallMethod() requires that the request is of a particular subclass of Message. GetRequestClass() gets the default instance of this required type. Example: method = service.GetDescriptor().FindMethodByName("Foo") request = stub.GetRequestClass(method)() request.ParseFromString(input) service.CallMethod(method, request, callback) """ raise NotImplementedError def GetResponseClass(self, method_descriptor): """Returns the class of the response message for the specified method. This method isn't really needed, as the RpcChannel's CallMethod constructs the response protocol message. It's provided anyway in case it is useful for the caller to know the response type in advance. """ raise NotImplementedError class RpcController(object): """An RpcController mediates a single method call. The primary purpose of the controller is to provide a way to manipulate settings specific to the RPC implementation and to find out about RPC-level errors. The methods provided by the RpcController interface are intended to be a "least common denominator" set of features which we expect all implementations to support. Specific implementations may provide more advanced features (e.g. deadline propagation). """ def Reset(self): """Resets the RpcController to its initial state. After the RpcController has been reset, it may be reused in a new call. Must not be called while an RPC is in progress. """ raise NotImplementedError def Failed(self): """Returns true if the call failed. After a call has finished, returns true if the call failed. The possible reasons for failure depend on the RPC implementation. Failed() must not be called before a call has finished. If Failed() returns true, the contents of the response message are undefined. """ raise NotImplementedError def ErrorText(self): """If Failed is true, returns a human-readable description of the error.""" raise NotImplementedError def StartCancel(self): """Initiate cancellation. Advises the RPC system that the caller desires that the RPC call be canceled. The RPC system may cancel it immediately, may wait awhile and then cancel it, or may not even cancel the call at all. If the call is canceled, the "done" callback will still be called and the RpcController will indicate that the call failed at that time. """ raise NotImplementedError def SetFailed(self, reason): """Sets a failure reason. Causes Failed() to return true on the client side. "reason" will be incorporated into the message returned by ErrorText(). If you find you need to return machine-readable information about failures, you should incorporate it into your response protocol buffer and should NOT call SetFailed(). """ raise NotImplementedError def IsCanceled(self): """Checks if the client cancelled the RPC. If true, indicates that the client canceled the RPC, so the server may as well give up on replying to it. The server should still call the final "done" callback. """ raise NotImplementedError def NotifyOnCancel(self, callback): """Sets a callback to invoke on cancel. Asks that the given callback be called when the RPC is canceled. The callback will always be called exactly once. If the RPC completes without being canceled, the callback will be called after completion. If the RPC has already been canceled when NotifyOnCancel() is called, the callback will be called immediately. NotifyOnCancel() must be called no more than once per request. """ raise NotImplementedError class RpcChannel(object): """Abstract interface for an RPC channel. An RpcChannel represents a communication line to a service which can be used to call that service's methods. The service may be running on another machine. Normally, you should not use an RpcChannel directly, but instead construct a stub {@link Service} wrapping it. Example: Example: RpcChannel channel = rpcImpl.Channel("remotehost.example.com:1234") RpcController controller = rpcImpl.Controller() MyService service = MyService_Stub(channel) service.MyMethod(controller, request, callback) """ def CallMethod(self, method_descriptor, rpc_controller, request, response_class, done): """Calls the method identified by the descriptor. Call the given method of the remote service. The signature of this procedure looks the same as Service.CallMethod(), but the requirements are less strict in one important way: the request object doesn't have to be of any specific class as long as its descriptor is method.input_type. """ raise NotImplementedError
37.097222
79
0.738425
94f5ff25e00f9c63ae1daaeb4de325ae6ecba14e
1,101
py
Python
graspologic/utils/__init__.py
vmdhhh/graspologic
1ffd88ec2ee3f1cfb1061185758e43eda7433b41
[ "MIT" ]
1
2021-09-08T18:04:02.000Z
2021-09-08T18:04:02.000Z
graspologic/utils/__init__.py
vmdhhh/graspologic
1ffd88ec2ee3f1cfb1061185758e43eda7433b41
[ "MIT" ]
null
null
null
graspologic/utils/__init__.py
vmdhhh/graspologic
1ffd88ec2ee3f1cfb1061185758e43eda7433b41
[ "MIT" ]
null
null
null
# Copyright (c) Microsoft Corporation and contributors. # Licensed under the MIT License. from .ptr import pass_to_ranks from .utils import ( augment_diagonal, binarize, cartesian_product, fit_plug_in_variance_estimator, import_edgelist, import_graph, is_almost_symmetric, is_fully_connected, is_loopless, is_symmetric, is_unweighted, largest_connected_component, multigraph_lcc_intersection, multigraph_lcc_union, remap_labels, remap_node_ids, remove_loops, remove_vertices, symmetrize, to_laplacian, ) __all__ = [ "import_graph", "import_edgelist", "is_symmetric", "is_loopless", "is_unweighted", "is_almost_symmetric", "symmetrize", "remove_loops", "to_laplacian", "is_fully_connected", "largest_connected_component", "multigraph_lcc_union", "multigraph_lcc_intersection", "augment_diagonal", "binarize", "cartesian_product", "pass_to_ranks", "fit_plug_in_variance_estimator", "remove_vertices", "remap_labels", "remap_node_ids", ]
21.588235
55
0.701181
c9059c5fb96dcd2328afeeef45d09a818190abae
508
py
Python
authentication/views.py
mushahid54/feedback_survey
a568008f0717b52649010286e55e242f083734be
[ "MIT" ]
null
null
null
authentication/views.py
mushahid54/feedback_survey
a568008f0717b52649010286e55e242f083734be
[ "MIT" ]
null
null
null
authentication/views.py
mushahid54/feedback_survey
a568008f0717b52649010286e55e242f083734be
[ "MIT" ]
null
null
null
from django.shortcuts import render # Create your views here. from oauth2_provider.ext.rest_framework import permissions, OAuth2Authentication from rest_framework import viewsets from authentication.models import User from authentication.serializers import UserCreateSerializer #from chatapp.utils import CustomMetaDataMixin class UserViewSet(viewsets.ModelViewSet): """ Simple create user """ queryset = User.objects.filter(is_active=True) serializer_class = UserCreateSerializer
29.882353
80
0.809055
eb8c879ca533bf304ed6ef956628a19364f2976f
25,321
py
Python
pyctcdecode/tests/test_decoder.py
kensho-technologies/pyctcdecode
c33f94bce283ea9af79d30e2b815e3bf34a137c9
[ "Apache-2.0" ]
203
2021-06-08T22:49:56.000Z
2022-03-31T11:55:21.000Z
pyctcdecode/tests/test_decoder.py
kensho-technologies/pyctcdecode
c33f94bce283ea9af79d30e2b815e3bf34a137c9
[ "Apache-2.0" ]
40
2021-06-11T20:58:07.000Z
2022-03-23T10:58:27.000Z
pyctcdecode/tests/test_decoder.py
kensho-technologies/pyctcdecode
c33f94bce283ea9af79d30e2b815e3bf34a137c9
[ "Apache-2.0" ]
39
2021-06-09T21:03:35.000Z
2022-03-26T13:14:23.000Z
# Copyright 2021-present Kensho Technologies, LLC. import json import math import multiprocessing import os import unittest from hypothesis import given, settings from hypothesis import strategies as st import kenlm # type: ignore import numpy as np from ..alphabet import BPE_TOKEN, UNK_BPE_TOKEN, Alphabet from ..decoder import ( BeamSearchDecoderCTC, _merge_beams, _normalize_whitespace, _prune_history, _sort_and_trim_beams, _sum_log_scores, build_ctcdecoder, ) from ..language_model import LanguageModel, MultiLanguageModel from .helpers import TempfileTestCase def _random_matrix(rows: int, cols: int) -> np.ndarray: return np.random.normal(size=(rows, cols)) def _random_logits(rows: int, cols: int) -> np.ndarray: """Sample random logit matrix of given dimension.""" xs = np.exp(_random_matrix(rows, cols)) ps = (xs.T / np.sum(xs, axis=1)).T logits = np.log(ps) return logits def _random_libri_logits(N: int) -> np.ndarray: return _random_logits(N, len(LIBRI_LABELS) + 1) def _approx_beams(beams, precis=5): """Return beams with scores rounded.""" return [tuple(list(b[:-1]) + [round(b[-1], precis)]) for b in beams] def _approx_lm_beams(beams, precis=5): """Return beams with scores rounded.""" simple_beams = [] for text, _, frames, s1, s2 in beams: simple_beams.append((text, frames, round(s1, precis), round(s2, precis))) return simple_beams def _greedy_decode(logits, alphabet): label_dict = {n: c for n, c in enumerate(alphabet.labels)} prev_c = None out = [] for n in logits.argmax(axis=1): c = label_dict[n] if c != prev_c: out.append(c) return "".join(out) class TestDecoderHelpers(unittest.TestCase): def test_normalize_whitespace(self): # empty input out = _normalize_whitespace("") self.assertEqual(out, "") out = _normalize_whitespace(" This is super. ") self.assertEqual(out, "This is super.") def test_sum_log_scores(self): out = _sum_log_scores(0, 0) expected_out = math.log(math.exp(0) + math.exp(0)) self.assertEqual(out, expected_out) out = _sum_log_scores(1 - math.log(2), 1 - math.log(2)) self.assertEqual(out, 1.0) def test_sort_and_trim_beams(self): beams = _sort_and_trim_beams([(-3,), (-9,), (-5,)], 2) expected_beams = [(-3,), (-5,)] self.assertListEqual(beams, expected_beams) def test_merge_beams(self): beams = [ ("Batman and", "", "Robi", "i", [], (-1, -1), -1), ("Batman and", "Robin", "", "", [], (-1, -1), -1), ("Batman and", "", "Robi", "", [], (-1, -1), -1), ("Batman and", "", "Robi", "", [], (-1, -1), -1), ("Batman &", "", "Robi", "", [], (-1, -1), -1), ] merged_beams = _merge_beams(beams) expected_merged_beams = [ ("Batman and", "", "Robi", "i", [], (-1, -1), -1), ("Batman and", "Robin", "", "", [], (-1, -1), -1), ("Batman and", "", "Robi", "", [], (-1, -1), math.log(2 * math.exp(-1))), ("Batman &", "", "Robi", "", [], (-1, -1), -1), ] self.assertListEqual(_approx_beams(merged_beams), _approx_beams(expected_merged_beams)) def test_prune_history(self): beams = [ ("A Gandalf owns", "", "potatoes", "s", [], (-1, -1), -1, -1), ("B Gandalf owns", "", "potatoes", "", [], (-1, -1), -1, -1), ("C Gandalf owns", "", "potatoes", "s", [], (-1, -1), -1, -1), ("D Gandalf sells", "", "yeast", "", [], (-1, -1), -1, -1), ("E Gandalf owns", "", "yeast", "", [], (-1, -1), -1, -1), ] pruned_beams = _prune_history(beams, 3) expected_pruned_beams = [ ("A Gandalf owns", "", "potatoes", "s", [], (-1, -1), -1), ("B Gandalf owns", "", "potatoes", "", [], (-1, -1), -1), ("D Gandalf sells", "", "yeast", "", [], (-1, -1), -1), ("E Gandalf owns", "", "yeast", "", [], (-1, -1), -1), ] self.assertListEqual(_approx_beams(pruned_beams), _approx_beams(expected_pruned_beams)) CUR_PATH = os.path.dirname(os.path.abspath(__file__)) # libri files with open(os.path.join(CUR_PATH, "sample_data", "libri_logits.json")) as f: LIBRI_LOGITS = np.array(json.load(f)) LIBRI_LABELS = [ " ", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "'", ] # basic 2-gram kenlm model trained with 'bugs bunny' KENLM_MODEL_PATH = os.path.join(CUR_PATH, "sample_data", "bugs_bunny_kenlm.arpa") TEST_KENLM_MODEL = kenlm.Model(KENLM_MODEL_PATH) SAMPLE_LABELS = [" ", "b", "g", "n", "s", "u", "y", ""] SAMPLE_VOCAB = {c: n for n, c in enumerate(SAMPLE_LABELS)} BUGS_PROBS = np.zeros((4, len(SAMPLE_VOCAB))) BUGS_PROBS[0][SAMPLE_VOCAB.get("b")] = 1 BUGS_PROBS[1][SAMPLE_VOCAB.get("u")] = 1 BUGS_PROBS[2][SAMPLE_VOCAB.get("g")] = 1 BUGS_PROBS[3][SAMPLE_VOCAB.get("s")] = 1 BUNNY_PROBS = np.zeros((6, len(SAMPLE_VOCAB))) BUNNY_PROBS[0][SAMPLE_VOCAB.get("b")] = 1 BUNNY_PROBS[1][SAMPLE_VOCAB.get("u")] = 1 BUNNY_PROBS[2][SAMPLE_VOCAB.get("n")] = 1 BUNNY_PROBS[3][SAMPLE_VOCAB.get("")] = 1 BUNNY_PROBS[4][SAMPLE_VOCAB.get("n")] = 1 BUNNY_PROBS[5][SAMPLE_VOCAB.get("y")] = 1 BLANK_PROBS = np.zeros((1, len(SAMPLE_VOCAB))) BLANK_PROBS[0][SAMPLE_VOCAB.get("")] = 1 SPACE_PROBS = np.zeros((1, len(SAMPLE_VOCAB))) SPACE_PROBS[0][SAMPLE_VOCAB.get(" ")] = 1 # make mixed version that can get fixed with LM TEST_PROBS = np.vstack( [ np.vstack([BUGS_PROBS, BLANK_PROBS, BLANK_PROBS]) * 0.49 + BUNNY_PROBS * 0.51, SPACE_PROBS, BUNNY_PROBS, ] ) # convert to log probs without hitting overflow TEST_LOGITS = np.log(np.clip(TEST_PROBS, 1e-15, 1)) TEST_UNIGRAMS = ["bugs", "bunny"] class TestDecoder(unittest.TestCase): def test_decoder(self): alphabet = Alphabet.build_alphabet(SAMPLE_LABELS) # test empty decoder = BeamSearchDecoderCTC(alphabet) text = decoder.decode(TEST_LOGITS) self.assertEqual(text, "bunny bunny") # with LM but alpha = 0 language_model = LanguageModel(TEST_KENLM_MODEL, alpha=0.0) decoder = BeamSearchDecoderCTC(alphabet, language_model) text = decoder.decode(TEST_LOGITS) self.assertEqual(text, "bunny bunny") # alpha = 1 language_model = LanguageModel(TEST_KENLM_MODEL, alpha=1.0) decoder = BeamSearchDecoderCTC(alphabet, language_model) text = decoder.decode(TEST_LOGITS) self.assertEqual(text, "bugs bunny") # add empty unigrams language_model = LanguageModel(TEST_KENLM_MODEL, [], alpha=1.0) decoder = BeamSearchDecoderCTC(alphabet, language_model) text = decoder.decode(TEST_LOGITS) self.assertEqual(text, "bugs bunny") # add restricted unigrams but unk weight 0 unigrams = ["bunny"] language_model = LanguageModel(TEST_KENLM_MODEL, unigrams, alpha=1.0, unk_score_offset=0.0) decoder = BeamSearchDecoderCTC(alphabet, language_model) text = decoder.decode(TEST_LOGITS) self.assertEqual(text, "bugs bunny") # add unk weight unigrams = ["bunny"] language_model = LanguageModel( TEST_KENLM_MODEL, unigrams, alpha=1.0, unk_score_offset=-10.0 ) decoder = BeamSearchDecoderCTC(alphabet, language_model) text = decoder.decode(TEST_LOGITS) self.assertEqual(text, "bunny bunny") # verify class variables and cleanup n_models = len(BeamSearchDecoderCTC.model_container) self.assertGreaterEqual(n_models, 2) # delete a specific model from container decoder.cleanup() self.assertLess(len(BeamSearchDecoderCTC.model_container), n_models) # delete all models BeamSearchDecoderCTC.clear_class_models() self.assertEqual(len(BeamSearchDecoderCTC.model_container), 0) def test_build_ctcdecoder(self): decoder = build_ctcdecoder(SAMPLE_LABELS, KENLM_MODEL_PATH) text = decoder.decode(TEST_LOGITS) self.assertEqual(text, "bugs bunny") def test_decode_batch(self): decoder = build_ctcdecoder(SAMPLE_LABELS, KENLM_MODEL_PATH, TEST_UNIGRAMS) with multiprocessing.Pool() as pool: text_list = decoder.decode_batch(pool, [TEST_LOGITS] * 5) expected_text_list = ["bugs bunny"] * 5 self.assertListEqual(expected_text_list, text_list) def test_decode_beams_batch(self): decoder = build_ctcdecoder(SAMPLE_LABELS, KENLM_MODEL_PATH, TEST_UNIGRAMS) with multiprocessing.Pool() as pool: text_list = decoder.decode_beams_batch(pool, [TEST_LOGITS] * 5) expected_text_list = [ [ ( "bugs bunny", [("bugs", (0, 4)), ("bunny", (7, 13))], -2.853399551509947, 0.14660044849005294, ) ], [ ( "bugs bunny", [("bugs", (0, 4)), ("bunny", (7, 13))], -2.853399551509947, 0.14660044849005294, ) ], [ ( "bugs bunny", [("bugs", (0, 4)), ("bunny", (7, 13))], -2.853399551509947, 0.14660044849005294, ) ], [ ( "bugs bunny", [("bugs", (0, 4)), ("bunny", (7, 13))], -2.853399551509947, 0.14660044849005294, ) ], [ ( "bugs bunny", [("bugs", (0, 4)), ("bunny", (7, 13))], -2.853399551509947, 0.14660044849005294, ) ], ] self.assertListEqual(expected_text_list, text_list) def test_multi_lm(self): alphabet = Alphabet.build_alphabet(SAMPLE_LABELS) lm = LanguageModel(TEST_KENLM_MODEL) decoder = BeamSearchDecoderCTC(alphabet, lm) text = decoder.decode(TEST_LOGITS) self.assertEqual(text, "bugs bunny") # constructing a multi lm with twice the same should average to the same result multi_lm = MultiLanguageModel([lm, lm]) decoder_multi_lm = BeamSearchDecoderCTC(alphabet, multi_lm) text = decoder_multi_lm.decode(TEST_LOGITS) self.assertEqual(text, "bugs bunny") beams_1 = decoder.decode_beams(TEST_LOGITS) beams_2 = decoder_multi_lm.decode_beams(TEST_LOGITS) self.assertListEqual(_approx_lm_beams(beams_1), _approx_lm_beams(beams_2)) def test_pruning(self): decoder = build_ctcdecoder(SAMPLE_LABELS, KENLM_MODEL_PATH) text = decoder.decode(TEST_LOGITS) self.assertEqual(text, "bugs bunny") text = _greedy_decode(TEST_LOGITS, decoder._alphabet) # pylint: disable=W0212 self.assertEqual(text, "bunny bunny") # setting a token threshold higher than one will force only argmax characters text = decoder.decode(TEST_LOGITS, token_min_logp=0.0) self.assertEqual(text, "bunny bunny") def test_history_pruning(self): decoder = build_ctcdecoder(SAMPLE_LABELS) # make test logits where first token is ambiguous and all following tokens are clear add_probs = np.vstack([SPACE_PROBS, BUNNY_PROBS]) logits = np.log(np.clip(np.vstack([TEST_PROBS] + [add_probs] * 5), 1e-15, 1)) beams = decoder.decode_beams(logits, prune_history=False) beams_pruned = decoder.decode_beams(logits, prune_history=True) # make sure top result is the same self.assertEqual(beams[0][0], beams_pruned[0][0]) # history pruning will have a strong effect on diversity here self.assertEqual(len(beams), 16) self.assertEqual(len(beams_pruned), 1) def test_stateful(self): bunny_bunny_probs = np.vstack( [ BUGS_PROBS, SPACE_PROBS, np.vstack([BUGS_PROBS, BLANK_PROBS, BLANK_PROBS]) * 0.51 + BUNNY_PROBS * 0.49, ] ) # without a LM we get bugs bugs as most likely no_lm_decoder = build_ctcdecoder(SAMPLE_LABELS) text = no_lm_decoder.decode(bunny_bunny_probs) self.assertEqual(text, "bugs bugs") # now let's add a LM decoder = build_ctcdecoder(SAMPLE_LABELS, KENLM_MODEL_PATH, TEST_UNIGRAMS) # LM correctly picks up the higher bigram probability for 'bugs bunny' over 'bugs bugs' text = decoder.decode(bunny_bunny_probs) self.assertEqual(text, "bugs bunny") # when splitting the LM can only see unigrams text = decoder.decode(bunny_bunny_probs[:4]) + " " + decoder.decode(bunny_bunny_probs[4:]) self.assertEqual(text, "bugs bugs") # if we keep state from the first unigram then the second can be scored correctly text, lm_state, _, _, _ = decoder.decode_beams(bunny_bunny_probs[:4])[0] text += " " + decoder.decode_beams(bunny_bunny_probs[4:], lm_start_state=lm_state)[0][0] self.assertEqual(text, "bugs bunny") def test_hotwords(self): decoder = build_ctcdecoder(SAMPLE_LABELS, KENLM_MODEL_PATH) text = decoder.decode(TEST_LOGITS) self.assertEqual(text, "bugs bunny") text = decoder.decode(TEST_LOGITS, hotwords=["bunny"], hotword_weight=20) self.assertEqual(text, "bunny bunny") text = decoder.decode(TEST_LOGITS, hotwords=["bugs", "bunny"], hotword_weight=20) self.assertEqual(text, "bugs bunny") text = decoder.decode(TEST_LOGITS, hotwords=["bugs bunny"], hotword_weight=20) self.assertEqual(text, "bugs bunny") # check that this also works without language model no_lm_decoder = build_ctcdecoder(SAMPLE_LABELS) text = no_lm_decoder.decode(TEST_LOGITS) self.assertEqual(text, "bunny bunny") text = no_lm_decoder.decode(TEST_LOGITS, hotwords=["bugs"]) self.assertEqual(text, "bugs bunny") def test_beam_results(self): # build a basic decoder with LM to get all possible combinations decoder = build_ctcdecoder(SAMPLE_LABELS) beams = decoder.decode_beams(TEST_LOGITS) self.assertEqual(len(beams), 16) # the best beam should be bunny bunny top_beam = beams[0] self.assertEqual(top_beam[0], "bunny bunny") # the worst beam should be bugs bunny worst_beam = beams[-1] self.assertEqual(worst_beam[0], "bugs bunny") # if we add the language model, that should push bugs bunny to the top, far enough to # remove all other beams from the output decoder = build_ctcdecoder(SAMPLE_LABELS, KENLM_MODEL_PATH) beams = decoder.decode_beams(TEST_LOGITS) self.assertEqual(len(beams), 1) top_beam = beams[0] self.assertEqual(top_beam[0], "bugs bunny") # if we don't punish <unk> and don't prune beams by score we recover all but sorted # correctly with 'bugs bunny' and the top (bigram LM) and 'bunny bunny' second (unigram LM) alphabet = Alphabet.build_alphabet(SAMPLE_LABELS) language_model = LanguageModel(TEST_KENLM_MODEL, unk_score_offset=0.0) decoder = BeamSearchDecoderCTC(alphabet, language_model) beams = decoder.decode_beams(TEST_LOGITS, beam_prune_logp=-20.0) self.assertEqual(len(beams), 16) self.assertEqual(beams[0][0], "bugs bunny") self.assertEqual(beams[1][0], "bunny bunny") def test_frame_annotation(self): # build a basic decoder with LM to get all possible combinations decoder = build_ctcdecoder(SAMPLE_LABELS) beams = decoder.decode_beams(TEST_LOGITS) top_beam = beams[0] self.assertEqual(top_beam[0], "bunny bunny") # the frame annotations returned should correspond to the position of the the two words # within the logit matrix expected_frames = [("bunny", (0, 6)), ("bunny", (7, 13))] self.assertEqual(len(top_beam[2]), len(expected_frames)) self.assertListEqual(top_beam[2], expected_frames) worst_beam = beams[-1] self.assertEqual(worst_beam[0], "bugs bunny") # the first word is of length 4 now, so check for correct frame annotations (ctc blank # character won't be included in the frame count if it's at the end of a word) expected_frames = [("bugs", (0, 4)), ("bunny", (7, 13))] self.assertEqual(len(worst_beam[2]), len(expected_frames)) self.assertListEqual(worst_beam[2], expected_frames) # check if frame annotation works in ctc stretched word stretched_chars = [" ", "", "b", "u", "n", "", "n", "n", "y", "", " ", " "] test_frame_logits = np.zeros((len(stretched_chars), len(SAMPLE_VOCAB))) for n, c in enumerate(stretched_chars): test_frame_logits[n][SAMPLE_VOCAB.get(c)] = 1 top_beam = decoder.decode_beams(test_frame_logits)[0] self.assertEqual(top_beam[0], "bunny") expected_frames = [("bunny", (2, 9))] self.assertEqual(len(top_beam[2]), len(expected_frames)) self.assertListEqual(top_beam[2], expected_frames) # test for bpe vocabulary bpe_labels = ["▁bugs", "▁bun", "ny", ""] bpe_vocab = {c: n for n, c in enumerate(bpe_labels)} bpe_decoder = build_ctcdecoder(bpe_labels) bpe_ctc_out = ["", "▁bugs", "▁bun", "ny", "ny", ""] test_frame_logits = np.zeros((len(bpe_ctc_out), len(bpe_vocab))) for n, c in enumerate(bpe_ctc_out): test_frame_logits[n][bpe_vocab.get(c)] = 1 top_beam = bpe_decoder.decode_beams(test_frame_logits)[0] self.assertEqual(top_beam[0], "bugs bunny") expected_frames = [("bugs", (1, 2)), ("bunny", (2, 5))] self.assertEqual(len(top_beam[2]), len(expected_frames)) self.assertListEqual(top_beam[2], expected_frames) def test_realistic_alphabet(self): decoder = build_ctcdecoder(LIBRI_LABELS) text = decoder.decode(LIBRI_LOGITS) expected_text = ( "i have a good deal of will you remember and what i have set my mind upon no doubt " "i shall some day achieve" ) self.assertEqual(text, expected_text) beams = decoder.decode_beams(LIBRI_LOGITS) # check that every word received frame annotations self.assertEqual(len(beams[0][0].split()), len(beams[0][2])) # test with fake BPE vocab, spoof space with with ▁▁ libri_labels_bpe = [UNK_BPE_TOKEN, BPE_TOKEN] + ["##" + c for c in LIBRI_LABELS[1:]] zero_row = np.array([[-100.0] * LIBRI_LOGITS.shape[0]]).T libri_logits_bpe = np.hstack([zero_row, LIBRI_LOGITS]) decoder = build_ctcdecoder(libri_labels_bpe) text = decoder.decode(libri_logits_bpe) expected_text = ( "i have a good deal of will you remember and what i have set my mind upon no doubt " "i shall some day achieve" ) self.assertEqual(text, expected_text) # check that every word received frame annotations self.assertEqual(len(beams[0][0].split()), len(beams[0][2])) @settings(deadline=1000) @given(st.builds(_random_libri_logits, st.integers(min_value=0, max_value=20))) def test_fuzz_decode(self, logits: np.ndarray): """Ensure decoder is robust to random logit inputs.""" decoder = build_ctcdecoder(LIBRI_LABELS) decoder.decode(logits) @settings(deadline=1000) @given( st.builds( _random_matrix, st.integers(min_value=0, max_value=20), st.integers(min_value=len(LIBRI_LABELS) + 1, max_value=len(LIBRI_LABELS) + 1), ) ) def test_invalid_logit_inputs(self, logits: np.ndarray): decoder = build_ctcdecoder(LIBRI_LABELS) decoder.decode(logits) @given( alpha=st.one_of(st.none(), st.floats()), beta=st.one_of(st.none(), st.floats()), unk_score_offset=st.one_of(st.none(), st.floats()), lm_score_boundary=st.one_of(st.none(), st.booleans()), ) def test_fuzz_reset_params(self, alpha, beta, unk_score_offset, lm_score_boundary): decoder = build_ctcdecoder(SAMPLE_LABELS, KENLM_MODEL_PATH, alpha=0.0) decoder.reset_params( alpha=alpha, beta=beta, unk_score_offset=unk_score_offset, lm_score_boundary=lm_score_boundary, ) class TestSerialization(TempfileTestCase): def _count_num_language_models(self): return sum( [1 for model in BeamSearchDecoderCTC.model_container.values() if model is not None] ) def test_parse_directory(self): good_filenames = [ ("alphabet.json", "language_model"), ("alphabet.json",), ("README.md", "alphabet.json", "language_model"), # additional file in dir ] bad_filenames = [ ("language_model"), # missing alphabet ("alphabet.wrong-ext", "language_model"), ] for filenames in good_filenames: self.clear_dir() for fn in filenames: with open(os.path.join(self.temp_dir, fn), "w") as fi: fi.write("meaningless data") BeamSearchDecoderCTC.parse_directory_contents(self.temp_dir) # should not error out for filenames in bad_filenames: self.clear_dir() for fn in filenames: with open(os.path.join(self.temp_dir, fn), "w") as fi: fi.write("meaningless data") with self.assertRaises(ValueError): LanguageModel.parse_directory_contents(self.temp_dir) def test_serialization(self): self.clear_dir() decoder = build_ctcdecoder(LIBRI_LABELS) text = decoder.decode(LIBRI_LOGITS) old_num_models = self._count_num_language_models() # saving shouldn't alter state of model_container decoder.save_to_dir(self.temp_dir) self.assertEqual(self._count_num_language_models(), old_num_models) new_decoder = BeamSearchDecoderCTC.load_from_dir(self.temp_dir) new_text = new_decoder.decode(LIBRI_LOGITS) self.assertEqual(text, new_text) # this decoder has no LM so we should not increment the number of models self.assertEqual(old_num_models, self._count_num_language_models()) self.clear_dir() BeamSearchDecoderCTC.clear_class_models() # repeat with a decoder with a language model alphabet = Alphabet.build_alphabet(SAMPLE_LABELS) language_model = LanguageModel(TEST_KENLM_MODEL, alpha=1.0) decoder = BeamSearchDecoderCTC(alphabet, language_model) text = decoder.decode(TEST_LOGITS) self.assertEqual(text, "bugs bunny") old_num_models = self._count_num_language_models() decoder.save_to_dir(self.temp_dir) # here too, saving should not alter number of lang models self.assertEqual(self._count_num_language_models(), old_num_models) new_decoder = BeamSearchDecoderCTC.load_from_dir(self.temp_dir) new_text = new_decoder.decode(TEST_LOGITS) self.assertEqual(text, new_text) # this decoder has a language model so we expect one more key self.assertEqual(old_num_models + 1, self._count_num_language_models()) def test_load_from_hub_offline(self): from huggingface_hub.snapshot_download import REPO_ID_SEPARATOR # create language model and decode text alphabet = Alphabet.build_alphabet(SAMPLE_LABELS) language_model = LanguageModel(TEST_KENLM_MODEL, alpha=1.0) decoder = BeamSearchDecoderCTC(alphabet, language_model) text = decoder.decode(TEST_LOGITS) self.assertEqual(text, "bugs bunny") # We are now pretending to have downloaded a HF repository # called `kesho/dummy_test` into the cache. The format of # cached HF repositories is <flattened-hub-name>.<branch>.<sha256> which # is created under the hood in `.load_from_hf_hub`. To mock a cached # download we have to do it manually here. dummy_hub_name = "kensho/dummy_test" dummy_cached_subdir = ( dummy_hub_name.replace("/", REPO_ID_SEPARATOR) + ".main.123456aoeusnth" ) dummy_cached_dir = os.path.join(self.temp_dir, dummy_cached_subdir) os.makedirs(dummy_cached_dir) # save decoder decoder.save_to_dir(os.path.join(self.temp_dir, dummy_cached_dir)) # load from cache in offline mode new_decoder = BeamSearchDecoderCTC.load_from_hf_hub( dummy_hub_name, cache_dir=self.temp_dir, local_files_only=True ) new_text = new_decoder.decode(TEST_LOGITS) self.assertEqual(text, new_text)
38.955385
99
0.619604
012e617ee0d7b6763d4f140e9f6dd9d1d9cc76e9
506
py
Python
tests/pipeline/test_vignette_corrector.py
moi90/morphocut
fda36b6681331911b7a2592329a7df5e1ce2065c
[ "MIT" ]
1
2020-05-10T09:15:17.000Z
2020-05-10T09:15:17.000Z
tests/pipeline/test_vignette_corrector.py
moi90/morphocut
fda36b6681331911b7a2592329a7df5e1ce2065c
[ "MIT" ]
null
null
null
tests/pipeline/test_vignette_corrector.py
moi90/morphocut
fda36b6681331911b7a2592329a7df5e1ce2065c
[ "MIT" ]
null
null
null
import glob import os.path from morphocut.pipeline.vignette_corrector import VignetteCorrector from skimage.io import imread def test_vignette_corrector_no_channel(image_fns): vignette_corrector = VignetteCorrector("input", "output") inp = ( { "facets": { "input": { "image": imread(img_fn, as_gray=True) } } } for img_fn in image_fns ) for _ in vignette_corrector(inp): pass
20.24
67
0.581028
52e1c8d8517c8889d6e4cb828762b1c7a4ef61ae
607
py
Python
test/widgets/conftest.py
g--o/Lavinder
a31092c452be769b7aeb6a1a80a6e57cc4625829
[ "MIT" ]
1
2019-06-18T07:44:04.000Z
2019-06-18T07:44:04.000Z
test/widgets/conftest.py
g--o/Lavinder
a31092c452be769b7aeb6a1a80a6e57cc4625829
[ "MIT" ]
22
2019-02-23T23:56:05.000Z
2019-09-04T21:35:24.000Z
test/widgets/conftest.py
g--o/Lavinder
a31092c452be769b7aeb6a1a80a6e57cc4625829
[ "MIT" ]
4
2019-02-22T23:26:00.000Z
2022-01-03T17:46:54.000Z
import pytest import os @pytest.fixture(scope='function') def fake_bar(): from liblavinder.bar import Bar height = 24 b = Bar([], height) b.height = height return b TEST_DIR = os.path.dirname(os.path.abspath(__file__)) DATA_DIR = os.path.join(os.path.dirname(TEST_DIR), 'data') @pytest.fixture(scope='module') def svg_img_as_pypath(): "Return the py.path object of a svg image" import py audio_volume_muted = os.path.join( DATA_DIR, 'svg', 'audio-volume-muted.svg', ) audio_volume_muted = py.path.local(audio_volume_muted) return audio_volume_muted
22.481481
58
0.691928
44fdee0045ae5b1058077429e353e35f2d408283
943
py
Python
dutils/templatetags/google_analytics.py
dsclementsen/django-dutils
ff4720eb0c800291cde56050667e48e6782bb0ab
[ "Unlicense" ]
null
null
null
dutils/templatetags/google_analytics.py
dsclementsen/django-dutils
ff4720eb0c800291cde56050667e48e6782bb0ab
[ "Unlicense" ]
null
null
null
dutils/templatetags/google_analytics.py
dsclementsen/django-dutils
ff4720eb0c800291cde56050667e48e6782bb0ab
[ "Unlicense" ]
null
null
null
from django import template from django.template import Template from django.conf import settings from django.utils.safestring import mark_safe register = template.Library() @register.simple_tag def google_analytics(): google_tracking_str = "" if (hasattr(settings, 'GOOGLE_ANALYTICS_TRACKING_ID') and settings.GOOGLE_ANALYTICS_TRACKING_ID): google_tracking_str = """ <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', '%s', 'auto'); ga('send', 'pageview'); </script> """ % (settings.GOOGLE_ANALYTICS_TRACKING_ID) google_tracking_str = mark_safe(google_tracking_str) return google_tracking_str
32.517241
84
0.709438
01452d8b394a7ee3ea2f85fe8b6bbe39d380b190
3,062
py
Python
homeassistant/components/fibaro/sensor.py
shanbs/home-assistant
818776d2b4f11e4f51992dc88bc0a6f9055833b2
[ "Apache-2.0" ]
1
2019-02-18T03:16:32.000Z
2019-02-18T03:16:32.000Z
homeassistant/components/fibaro/sensor.py
shanbs/home-assistant
818776d2b4f11e4f51992dc88bc0a6f9055833b2
[ "Apache-2.0" ]
3
2021-09-08T03:29:36.000Z
2022-03-12T00:59:48.000Z
homeassistant/components/fibaro/sensor.py
shanbs/home-assistant
818776d2b4f11e4f51992dc88bc0a6f9055833b2
[ "Apache-2.0" ]
1
2019-09-28T07:06:08.000Z
2019-09-28T07:06:08.000Z
"""Support for Fibaro sensors.""" import logging from homeassistant.const import ( DEVICE_CLASS_TEMPERATURE, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_ILLUMINANCE, TEMP_CELSIUS, TEMP_FAHRENHEIT) from homeassistant.helpers.entity import Entity from homeassistant.components.sensor import ENTITY_ID_FORMAT from homeassistant.components.fibaro import ( FIBARO_DEVICES, FibaroDevice) SENSOR_TYPES = { 'com.fibaro.temperatureSensor': ['Temperature', None, None, DEVICE_CLASS_TEMPERATURE], 'com.fibaro.smokeSensor': ['Smoke', 'ppm', 'mdi:fire', None], 'CO2': ['CO2', 'ppm', 'mdi:cloud', None], 'com.fibaro.humiditySensor': ['Humidity', '%', None, DEVICE_CLASS_HUMIDITY], 'com.fibaro.lightSensor': ['Light', 'lx', None, DEVICE_CLASS_ILLUMINANCE] } DEPENDENCIES = ['fibaro'] _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Fibaro controller devices.""" if discovery_info is None: return add_entities( [FibaroSensor(device) for device in hass.data[FIBARO_DEVICES]['sensor']], True) class FibaroSensor(FibaroDevice, Entity): """Representation of a Fibaro Sensor.""" def __init__(self, fibaro_device): """Initialize the sensor.""" self.current_value = None self.last_changed_time = None super().__init__(fibaro_device) self.entity_id = ENTITY_ID_FORMAT.format(self.ha_id) if fibaro_device.type in SENSOR_TYPES: self._unit = SENSOR_TYPES[fibaro_device.type][1] self._icon = SENSOR_TYPES[fibaro_device.type][2] self._device_class = SENSOR_TYPES[fibaro_device.type][3] else: self._unit = None self._icon = None self._device_class = None try: if not self._unit: if self.fibaro_device.properties.unit == 'lux': self._unit = 'lx' elif self.fibaro_device.properties.unit == 'C': self._unit = TEMP_CELSIUS elif self.fibaro_device.properties.unit == 'F': self._unit = TEMP_FAHRENHEIT else: self._unit = self.fibaro_device.properties.unit except (KeyError, ValueError): pass @property def state(self): """Return the state of the sensor.""" return self.current_value @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return self._unit @property def icon(self): """Icon to use in the frontend, if any.""" return self._icon @property def device_class(self): """Return the device class of the sensor.""" return self._device_class def update(self): """Update the state.""" try: self.current_value = float(self.fibaro_device.properties.value) except (KeyError, ValueError): pass
32.231579
75
0.625408
04df009ba17cb449d0cacd1fa8527b5edf167aff
2,355
py
Python
mds/authent/oauthlib_utils.py
Polyconseil/django-mds
964655d3f17d51e74e67ae4c7b62b446435b5506
[ "MIT" ]
15
2019-01-02T13:44:29.000Z
2020-09-03T16:39:46.000Z
mds/authent/oauthlib_utils.py
Polyconseil/django-mds
964655d3f17d51e74e67ae4c7b62b446435b5506
[ "MIT" ]
44
2018-11-30T11:04:03.000Z
2020-01-21T17:21:39.000Z
mds/authent/oauthlib_utils.py
Polyconseil/midas
964655d3f17d51e74e67ae4c7b62b446435b5506
[ "MIT" ]
5
2019-04-23T16:22:49.000Z
2021-03-21T07:45:38.000Z
import datetime import oauthlib.oauth2 import oauthlib.oauth2.rfc6749.tokens import oauth2_provider.models import oauth2_provider.oauth2_validators from oauth2_provider.scopes import BaseScopes from oauth2_provider.settings import oauth2_settings from . import generators def signed_token_generator(request): token_duration = datetime.timedelta( seconds=oauth2_settings.ACCESS_TOKEN_EXPIRE_SECONDS ) user = getattr(request, "user", None) token, payload = generators.generate_jwt_with_payload( request.client, token_duration=token_duration, user=user ) # set claims on the request request.claims = payload return token class Server(oauthlib.oauth2.Server): """Just swap the default token generator to signed_tokens.""" def __init__(self, *args, **kwargs): if not kwargs.get("token_generator"): kwargs["token_generator"] = signed_token_generator kwargs[ "refresh_token_generator" ] = oauthlib.oauth2.rfc6749.tokens.random_token_generator super().__init__(*args, **kwargs) class OAuth2Validator(oauth2_provider.oauth2_validators.OAuth2Validator): def _create_access_token(self, expires, request, token, source_refresh_token=None): """Saves the token jti in the database.""" access_token = oauth2_provider.models.get_access_token_model()( user=request.user, scope=token["scope"], expires=expires, token=token["access_token"], application=request.client, source_refresh_token=source_refresh_token, jti=request.claims["jti"], ) access_token.save() return access_token class AppScopes(BaseScopes): def get_all_scopes(self): Application = oauth2_provider.models.get_application_model() return { k: k for k in set( s for scopes in Application.objects.values_list("scopes", flat=True) for s in scopes ) } def get_available_scopes(self, application=None, request=None, *args, **kwargs): return application.scopes def get_default_scopes(self, application=None, request=None, *args, **kwargs): return self.get_available_scopes(application, request, *args, **kwargs)
32.708333
87
0.676858
f408819123863113b94e531577816ea8347f01e9
199
py
Python
airflow/plugins/airflow_config.py
billhuang56/job-miner
472945be442b3ab5080a28bbcdc8e57653cd2af0
[ "MIT" ]
null
null
null
airflow/plugins/airflow_config.py
billhuang56/job-miner
472945be442b3ab5080a28bbcdc8e57653cd2af0
[ "MIT" ]
null
null
null
airflow/plugins/airflow_config.py
billhuang56/job-miner
472945be442b3ab5080a28bbcdc8e57653cd2af0
[ "MIT" ]
null
null
null
import os AWS_ACCESS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_SECRET_ACCESS_KEY") SCRAPPED_BUCKET = 'jd-scrapped' SCRAPPED_LOG = '_dice_scrapped.log'
28.428571
63
0.81407
e1c940672a35b0352ebc61c566957a2be2706063
2,839
py
Python
venv/Lib/site-packages/keystoneauth1/extras/kerberos/_loading.py
prasoon-uta/IBM-coud-storage
82a6876316715efbd0b492d0d467dde0ab26a56b
[ "Apache-2.0" ]
48
2015-05-02T16:19:10.000Z
2021-12-17T19:01:17.000Z
venv/Lib/site-packages/keystoneauth1/extras/kerberos/_loading.py
prasoon-uta/IBM-coud-storage
82a6876316715efbd0b492d0d467dde0ab26a56b
[ "Apache-2.0" ]
1
2019-12-04T13:48:10.000Z
2019-12-04T13:48:10.000Z
venv/Lib/site-packages/keystoneauth1/extras/kerberos/_loading.py
prasoon-uta/IBM-coud-storage
82a6876316715efbd0b492d0d467dde0ab26a56b
[ "Apache-2.0" ]
46
2015-05-23T14:04:35.000Z
2022-02-17T12:33:50.000Z
# 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 keystoneauth1 import exceptions from keystoneauth1.extras import kerberos from keystoneauth1 import loading class Kerberos(loading.BaseV3Loader): @property def plugin_class(self): return kerberos.Kerberos @property def available(self): return kerberos.requests_kerberos is not None def get_options(self): options = super(Kerberos, self).get_options() options.extend([ loading.Opt('mutual-auth', required=False, default='optional', help='Configures Kerberos Mutual Authentication'), ]) return options def load_from_options(self, **kwargs): if kwargs.get('mutual_auth'): value = kwargs.get('mutual_auth') if not (value.lower() in ['required', 'optional', 'disabled']): m = ('You need to provide a valid value for kerberos mutual ' 'authentication. It can be one of the following: ' '(required, optional, disabled)') raise exceptions.OptionError(m) return super(Kerberos, self).load_from_options(**kwargs) class MappedKerberos(loading.BaseFederationLoader): @property def plugin_class(self): return kerberos.MappedKerberos @property def available(self): return kerberos.requests_kerberos is not None def get_options(self): options = super(MappedKerberos, self).get_options() options.extend([ loading.Opt('mutual-auth', required=False, default='optional', help='Configures Kerberos Mutual Authentication'), ]) return options def load_from_options(self, **kwargs): if kwargs.get('mutual_auth'): value = kwargs.get('mutual_auth') if not (value.lower() in ['required', 'optional', 'disabled']): m = ('You need to provide a valid value for kerberos mutual ' 'authentication. It can be one of the following: ' '(required, optional, disabled)') raise exceptions.OptionError(m) return super(MappedKerberos, self).load_from_options(**kwargs)
33.797619
77
0.624163
622060b78828f544335b1034cc60fecb312cd599
10,981
py
Python
CS1_BostonCollege/HW5_CS1/main.py
gonzalosc2/LearningPython
0210d4cbbb5e154f12007b8e8f825fd3d0022be0
[ "MIT" ]
null
null
null
CS1_BostonCollege/HW5_CS1/main.py
gonzalosc2/LearningPython
0210d4cbbb5e154f12007b8e8f825fd3d0022be0
[ "MIT" ]
null
null
null
CS1_BostonCollege/HW5_CS1/main.py
gonzalosc2/LearningPython
0210d4cbbb5e154f12007b8e8f825fd3d0022be0
[ "MIT" ]
null
null
null
# author: Gonzalo Salazar # assigment: Homework #5 # name: employment analysis in the U.S. # description: main .py file with a series of functions # This code generates a set of figures summarizing the employment # in the U.S. This is done taking into account political parties and # sector (government or private). Finally, some figures per president # are shown as well. The user only needs to provide the name of three # files associated with: # (i) government employment data, # (ii) private employment data, and # (iii) presidential data. #recall: to set working directory #cd .. #cd Learning-Python/CS1_BostonCollege/HW5_CS1 ### LIBRARIES ### import pandas ### FUNCTIONS DEFINITION ### def is_file(filename): "Checks if a file exists or not" " INPUT: string(name of a file)" " OUTPUT: boolean" try: with open(filename, 'r'): return True except IOError: return False def empl_data_processing(filename): "Transforms a txt file into a useful list" " INPUT: string(name of a file)" " OUTPUT: list of lists with employment data by year" with open(filename, 'r') as f: f = list(f)[1:] data = [] for item in f: yr_data = item.strip().split(',') each_year_info = [int(yr_data[0])] for value in yr_data[1:]: each_year_info.append(int(value)) data.append(each_year_info) return data def presi_data_processing(filename): "Transforms a txt file into a useful list" " INPUT: string (name of a file)" " OUTPUT: list of lists with presidents data (period and party)" filename = 'presidents.txt' with open(filename, 'r') as f: f = list(f) data = [] for item in f: presi_data = item.strip().split(', ') # Solves the issue with compound names of presidents, such as James Earl Carter, Jr while len(presi_data) > 3: pres_data = [presi_data[0] + ', ' + presi_data[1]] pres_data.extend(presi_data[2:]) presi_data = pres_data # Separates the period by which each president was in charge in two diff values pres_data = [presi_data[0]] pres_data.extend([presi_data[2],int(presi_data[1][:4]),int(presi_data[1][-4:])-1]) data.append(pres_data) return data def collecting_data(answer): "Opens a txt file with data and processes it" " INPUT: option stated by the user: (G)overnment, (P)rivate or (Pr)esident" " OUTPUT: list of lists" while True: # Asks for the filename filename = input('Please enter the name of the file containing the relevant data. \ \nThe file should be on a comma-separated basis. Please provide the name of \ the file with its extension as well, e.g., name_of_the_file.txt: ') if is_file(filename) == False: print('\nSorry, but there is no file named ' + filename + '. Please provide the correct name.') continue else: break if answer.upper() in ('G','GOVERNMENT','P','PRIVATE'): return empl_data_processing(filename) else: return presi_data_processing(filename) def data_source(): "Asks the user for the type of information she is planning to work with," "to then call other functions in order to collect and transform the data" " INPUT: N/A" " OUTPUT: a data frame with specific data provided by the user or " " an error if the option provided is not valid" while True: try: answer = input('Are you going to load information related to (P)rivate or \ (G)overnment employment, or related to (Pr)esidents elected in \ the U.S.? Please answer P, G, or Pr: ') if answer.upper() in ('G','GOV','GOVERNMENT'): global gov gov = collecting_data(answer) break elif answer.upper() in ('P','PRIV','PRIVATE'): global priv priv = collecting_data(answer) break elif answer.upper() in ('PR','PRESIDENT','PRESIDENTS'): global pres pres = collecting_data(answer) break else: raise ValueError('Invalid value.') except ValueError: print('\nThe value provided is invalid, please answer P, G, or Pr.') def data_prompting(): "Keeps asking for data files if these have not been loaded yet" " INPUT: N/A" " OUTPUT: N/A" while len(priv) == 0 or len(gov) == 0 or len(pres) == 0: data_source() def data_merging(db): "Merges a list with presidential information" " INPUT: list (database)" " OUTPUT: updated list (modification of the original database)" for my_list in db: for president in pres: if my_list[0] in range(president[2],president[3]+1): my_list.extend(president[:2]) def bysort_empl(db): "Selects the column by which we want to sort, in this case by year" " INPUT: list (database)" " OUTPUT: value in specific column" return db[0] def bysort_pres(db): "Selects the column by which we want to sort, in this case by the first year" "a president was in charge" " INPUT: list (database)" " OUTPUT: value in specific column" return db[-2] def data_sorting(db): "Sorts a list depending on criteria" " INPUT: list (database)" " OUTPUT: sorted list" if db in (gov,priv): db.sort(key = bysort_empl) elif db in pres: db.sort(key = bysort_pres) def empl_per_month(party,source): "Calculates the employment per month of a particular party given its source" " INPUT: string [party] and list [source: government or private)]" " OUTPUT: float" total_exp_list = [] for my_list in source: if my_list[14].upper() in party: total_exp_list.append(sum(my_list[1:13])/len(my_list[1:13])) return sum(total_exp_list)/len(total_exp_list) def empl_first_last_diff(source): "Calculates the difference in employment between the first and last month" "of a president in charge" " INPUT: list [source: government or private)]" " OUTPUT: list (with information about each president and the diff in employment)" empl_by_pres = [] for my_list in source: for pres_period in pres: # First month for each president if pres_period[2] == my_list[0]: president_info = [my_list[-2],my_list[1]] # Last month for each president elif pres_period[3] == my_list[0]: #lm_empl.append([my_list[-2],my_list[-3]]) president_info.append(my_list[-3]) if len(president_info) == 3: empl_by_pres.append(president_info) # Adds the absolute difference and percentage difference for each president for my_list_pres in empl_by_pres: diff = my_list_pres[2]-my_list_pres[1] perc = diff / my_list_pres[1] my_list_pres.extend(['{:,}'.format(diff), '{:6.2%}'.format(perc)]) return empl_by_pres def data_formating(db): "Adds commas to units in thousands" " INPUT: list" " OUTPUT: modified list (with commas)" for i in (1,2): for item in db: item[i]='{:,}'.format(item[i]) def data_wrangling(): "Encompasses the data processing step" " INPUT: N/A" " OUTPUT: lists with information about employment per month by party and" " difference between first and last month employment per president" for db in (priv,gov): # Merging employment data with presidential information data_merging(db) # Sorting by year each database data_sorting(db) # Average monthly employment for each political party by source # for source in (gov,priv): # for party in ('DEMOCRAT','REPUBLICAN'): # source_empl_per_month_by_party.append(empl_per_month(party,source)) # For government summary for party in ('DEMOCRAT','REPUBLICAN'): gov_empl_per_month_by_party.append('{:,}'.format(int(empl_per_month(party,gov)))) # For private summary for party in ('DEMOCRAT','REPUBLICAN'): priv_empl_per_month_by_party.append('{:,}'.format(int(empl_per_month(party,priv)))) # Change in employment from the first and last month for each president # For government summary gov_empl_per_president.extend(empl_first_last_diff(gov)) data_formating(gov_empl_per_president) # For private summary priv_empl_per_president.extend(empl_first_last_diff(priv)) data_formating(priv_empl_per_president) def data_display(): "Displays data related to employment in the U.S. by different classifications" " INPUT: N/A" " OUTPUT: prints of different data frames" side_party = ['Democrat','Republican'] header_usd = ['(in millions)'] side_num = list(range(1,len(gov_empl_per_president)+1)) headers_pres = ['President','First Month','Last Month','Diff','% Diff'] print('-----------------------------------------------') print('Governent employment average per month') print(pandas.DataFrame(gov_empl_per_month_by_party,side_party,header_usd)) print('\n') print('-----------------------------------------------') print('Private employment average per month') print(pandas.DataFrame(priv_empl_per_month_by_party,side_party,header_usd)) print('\n') print('-----------------------------------------------') print('Government employment by president (in millions)') print(pandas.DataFrame(gov_empl_per_president,side_num,headers_pres)) print('\n') print('-----------------------------------------------') print('Private employment by president (in millions)') print(pandas.DataFrame(priv_empl_per_president,side_num,headers_pres)) print('\n') ### INITIALIZING THE CODE ### def main(): "Runs the whole code" " INPUT: N/A" " OUTPUT: a bunch of figures about employment in the U.S." ### GLOBAL LISTS ### global gov global priv global pres gov = [] priv = [] pres = [] global gov_empl_per_month_by_party global priv_empl_per_month_by_party global gov_empl_per_president global priv_empl_per_president gov_empl_per_month_by_party = [] priv_empl_per_month_by_party = [] gov_empl_per_president = [] priv_empl_per_president = [] # Asking for data files data_prompting() # Filtering, rearranging and cleansing databases data_wrangling() # Displaying insights obtained from databases data_display() ### RUNNING THE CODE! ### main()
33.787692
107
0.616884
3ba5cb2f730c3ddd33d31df0752ffa07aec75230
2,142
py
Python
src/gfl/gfl/generator.py
mingt2019/GFL
b8e027d2e8cdcc27c85a00744f8790d6db3cc4a3
[ "MIT" ]
123
2020-06-05T13:30:38.000Z
2022-03-30T08:39:43.000Z
src/gfl/gfl/generator.py
GalaxyLearning/PFL
b8e027d2e8cdcc27c85a00744f8790d6db3cc4a3
[ "MIT" ]
13
2020-06-19T13:09:47.000Z
2021-12-22T03:09:24.000Z
src/gfl/gfl/generator.py
GalaxyLearning/GFL
b8e027d2e8cdcc27c85a00744f8790d6db3cc4a3
[ "MIT" ]
35
2020-06-08T15:52:21.000Z
2022-03-25T11:52:42.000Z
__all__ = [ "DatasetGenerator", "JobGenerator" ] import abc import time import uuid from gfl.core.manager.node import GflNode from gfl.core.config import * from gfl.core.data import JobMetadata, DatasetMetadata, Job, Dataset from gfl.utils import TimeUtils class Generator(object): def __init__(self, module): super(Generator, self).__init__() self.module = module @abc.abstractmethod def generate(self): pass @classmethod def _generate_job_id(cls): return uuid.uuid4().hex @classmethod def _generate_dataset_id(cls): return uuid.uuid4().hex class DatasetGenerator(Generator): def __init__(self, module): super(DatasetGenerator, self).__init__(module) self.dataset_id = self._generate_dataset_id() self.metadata = DatasetMetadata(id=self.dataset_id, owner=GflNode.address, create_time=TimeUtils.millis_time()) self.dataset_config = DatasetConfig(module=module) def generate(self): dataset = Dataset(dataset_id=self.dataset_id, metadata=self.metadata, dataset_config=self.dataset_config) dataset.module = self.module return dataset class JobGenerator(Generator): def __init__(self, module): super(JobGenerator, self).__init__(module) self.job_id = self._generate_job_id() self.metadata = JobMetadata(id=self.job_id, owner=GflNode.address, create_time=TimeUtils.millis_time()) self.job_config = JobConfig(module=module) self.train_config = TrainConfig(module=module) self.aggregate_config = AggregateConfig(module=module) def generate(self): job = Job(job_id=self.job_id, metadata=self.metadata, job_config=self.job_config, train_config=self.train_config, aggregate_config=self.aggregate_config) job.module = self.module return job
29.342466
76
0.619514
18a8aa97d34006a13fa73c4bb6a7d70a711c9b6f
4,306
py
Python
nim.py
nim65s/nIM
81de0a1ab2141dad6fd366b3af2fdaea4a99ac8b
[ "BSD-2-Clause" ]
null
null
null
nim.py
nim65s/nIM
81de0a1ab2141dad6fd366b3af2fdaea4a99ac8b
[ "BSD-2-Clause" ]
null
null
null
nim.py
nim65s/nIM
81de0a1ab2141dad6fd366b3af2fdaea4a99ac8b
[ "BSD-2-Clause" ]
1
2018-07-18T14:22:14.000Z
2018-07-18T14:22:14.000Z
#!/usr/bin/env python3 import asyncio import logging import urwid from settings import * from matrix import Matrix from system import System logging.basicConfig(filename='nim.log', level=logging.INFO) class Input(urwid.Edit): def __init__(self, main): self.main = main super().__init__() def keypress(self, size, key): if key == 'enter': if self.edit_text: self.main.cmd(self.edit_text) self.set_edit_text('') else: return super().keypress(size, key) class Main(urwid.Frame): def __init__(self): self.users = {} self.active_account_idx = 0 self.active_room_idx = 0 self.header = urwid.Text('header') self.rooms = urwid.Text('rooms') self.text = urwid.Text('text') self.input = Input(self) self.body = urwid.Columns([(ROOM_LIST_WIDTH, urwid.Filler(self.rooms, valign='top')), urwid.Filler(self.text, valign='top')]) self.accounts = [System(self)] self.accounts.append(Matrix(self)) self.update_header() self.update_rooms() self.update_text(draw=False) super().__init__(self.body, header=self.header, footer=self.input, focus_part='footer') def cmd(self, text): if text.startswith(CMD_PREFIX): text = text[1:] if text.startswith(CMD_PREFIX): self.account.send(text, self.room_id) elif text.startswith('q'): raise urwid.ExitMainLoop elif text.startswith('n'): self.next() elif text.startswith('p'): self.prev() elif text.startswith('s'): self.active_room_idx = self.active_account_idx = 0 self.update_rooms() else: self.system(f'unknown command: {text}') self.update_text() self.update_header() else: self.account.send(text, self.room_id) def system(self, text, sender='system'): self.accounts[0].send(text, 'main', 'system') def update_header(self, header=None): if header is None: header = self.room_data['topic'] self.header.set_text(header + '\n') def update_text(self, history=None, draw=True): text = [] if history is None: history = self.room_data['history'] for dt, sender, body in history: dt = dt.strftime(DT_FORMAT) sender = self.users[sender] text.append(f'{dt} <{sender}> {body}') self.text.set_text('\n'.join(text)) if draw: main_loop.draw_screen() def update_rooms(self): rooms = [] for account in self.accounts: fill = '=' * (ROOM_LIST_WIDTH - 4 - len(str(account))) rooms.append(f'= {account} {fill}') for i, room_id in enumerate(account.rooms): name = account.room_data[room_id]['name'] active = '*' if account == self.account and i == self.active_room_idx else ' ' rooms.append(f' {active} {name}'[:ROOM_LIST_WIDTH - 1]) self.rooms.set_text('\n'.join(rooms)) def next(self): self.active_room_idx += 1 if self.active_room_idx >= len(self.account.rooms): self.active_account_idx = (self.active_account_idx + 1) % len(self.accounts) self.active_room_idx = 0 self.update_rooms() def prev(self): self.active_room_idx -= 1 if self.active_room_idx < 0: self.active_account_idx = (self.active_account_idx - 1) % len(self.accounts) self.active_room_idx = len(self.account.rooms) - 1 self.update_rooms() @property def account(self): return self.accounts[self.active_account_idx] @property def room_id(self): return self.account.rooms[self.active_room_idx] @property def room_data(self): return self.account.room_data[self.room_id] if __name__ == '__main__': event_loop = urwid.AsyncioEventLoop(loop=asyncio.get_event_loop()) screen = urwid.raw_display.Screen() main_loop = urwid.MainLoop(Main(), screen=screen, event_loop=event_loop) main_loop.run()
32.37594
95
0.584301
0e815b9cd105a3a5a403eef902910eccade40195
383
py
Python
geo/bms/bms/asgi.py
Tamlyn78/geo
dd63372acdd1fe8b744c05eca5ad23836e6a1604
[ "MIT" ]
null
null
null
geo/bms/bms/asgi.py
Tamlyn78/geo
dd63372acdd1fe8b744c05eca5ad23836e6a1604
[ "MIT" ]
null
null
null
geo/bms/bms/asgi.py
Tamlyn78/geo
dd63372acdd1fe8b744c05eca5ad23836e6a1604
[ "MIT" ]
null
null
null
""" ASGI config for bms project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bms.settings') application = get_asgi_application()
22.529412
78
0.780679
5b701ff79fe75ed3fa6b71db2f0e6c658075267e
930
py
Python
hummingbot/core/api_throttler/fixed_rate_api_throttler.py
coreydemarse/hummingbot
48dd45b103622b198ca8e833ed9de7d0ad573ed9
[ "Apache-2.0" ]
2
2022-02-10T05:03:14.000Z
2022-03-09T08:29:00.000Z
hummingbot/core/api_throttler/fixed_rate_api_throttler.py
coreydemarse/hummingbot
48dd45b103622b198ca8e833ed9de7d0ad573ed9
[ "Apache-2.0" ]
null
null
null
hummingbot/core/api_throttler/fixed_rate_api_throttler.py
coreydemarse/hummingbot
48dd45b103622b198ca8e833ed9de7d0ad573ed9
[ "Apache-2.0" ]
1
2021-07-30T08:44:01.000Z
2021-07-30T08:44:01.000Z
from typing import Deque from hummingbot.core.api_throttler.api_request_context_base import APIRequestContextBase from hummingbot.core.api_throttler.api_throttler_base import APIThrottlerBase from hummingbot.core.api_throttler.data_types import ( RateLimit, TaskLog, DEFAULT_PATH, ) class FixedRateThrottler(APIThrottlerBase): def execute_task(self): rate_limit: RateLimit = next(iter(self._path_rate_limit_map.values())) task_logs: Deque[TaskLog] = self._path_task_logs_map[DEFAULT_PATH] return FixedRateRequestContext( task_logs=task_logs, rate_limit=rate_limit, retry_interval=self._retry_interval, ) class FixedRateRequestContext(APIRequestContextBase): def within_capacity(self) -> bool: current_capacity: int = self._rate_limit.limit - len(self._task_logs) return current_capacity - self._rate_limit.weight >= 0
31
88
0.747312
2d180de7d03878766613c8f7db20e515621b4954
1,474
py
Python
slothql/django/queryset.py
karol-gruszczyk/sloth-gql
7972adb761b60f14409c2f734473c0a04b8db63c
[ "MIT" ]
2
2018-01-07T08:51:27.000Z
2018-01-23T16:25:56.000Z
slothql/django/queryset.py
karol-gruszczyk/sloth-gql
7972adb761b60f14409c2f734473c0a04b8db63c
[ "MIT" ]
3
2018-01-28T03:41:33.000Z
2018-01-28T03:55:00.000Z
slothql/django/queryset.py
karol-gruszczyk/slothql
7972adb761b60f14409c2f734473c0a04b8db63c
[ "MIT" ]
null
null
null
from typing import Iterable, Type from django.db import models from slothql.selections import selections_to_dict, Selections from .utils.model import get_selectable_relations, get_relations def get_selects(model: Type[models.Model], root_selections: Selections) -> Iterable[str]: forward_relations = get_selectable_relations(model) for name, selections in root_selections.items(): if selections and name in forward_relations: yield from ([f'{name}__{s}' for s in get_selects(forward_relations[name], selections)] or (name,)) def get_prefetches(model: Type[models.Model], root_selections: Selections) -> Iterable[str]: relations = get_relations(model) for name, selections in root_selections.items(): if selections and name in relations: yield from ([f'{name}__{s}' for s in get_prefetches(relations[name], selections)] or (name,)) def remove_selections(selections: Selections, selects: tuple): return selections def get_optimized_queryset(manager: models.Manager, selections: Selections): queryset: models.QuerySet = manager.get_queryset() # selects = tuple(get_selects(manager.model, selections)) # if selects: # queryset = queryset.select_related(*selects) # selections = remove_selections(selections, selects) prefetches = tuple(get_prefetches(manager.model, selections)) if prefetches: queryset = queryset.prefetch_related(*prefetches) return queryset
39.837838
110
0.740163
d93abbc2e9dd1b943f689c26e79544dbf9943595
7,797
py
Python
core/domain/rule_domain.py
Himanshu1495/oppia
8a3a4d6ff633aca12bbd043648a2d45ccdd583e9
[ "Apache-2.0" ]
null
null
null
core/domain/rule_domain.py
Himanshu1495/oppia
8a3a4d6ff633aca12bbd043648a2d45ccdd583e9
[ "Apache-2.0" ]
null
null
null
core/domain/rule_domain.py
Himanshu1495/oppia
8a3a4d6ff633aca12bbd043648a2d45ccdd583e9
[ "Apache-2.0" ]
1
2021-09-22T10:37:34.000Z
2021-09-22T10:37:34.000Z
# coding: utf-8 # # Copyright 2014 The Oppia 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. """Classes relating to rules.""" import inspect import os import pkgutil from extensions.objects.models import objects import feconf import jinja_utils # TODO(sll): In the frontend, use the rule descriptions as the single source # of truth for the params. FUZZY_RULE_TYPE = 'FuzzyMatches' def get_obj_type_for_param_name(rule_class, param_name): """Gets the obj type for a given param name.""" param_list = get_param_list(rule_class.description) for item in param_list: if item[0] == param_name: return item[1] raise Exception( 'Rule %s has no param called %s' % (rule_class.__name__, param_name)) def get_default_object_values(): """Returns a dict mapping object types to their default values, taking into account only object types which represent rule input parameters. Note: we return an explicit dict here in order to avoid unnecessary computation, since this dict never changes between a release and is served each time the editor page loads. We have backend tests that compare the value returned here to an explicitly-computed value -- see rule_domain_test.test_get_default_object_values(). """ return { 'CodeString': '', 'CoordTwoDim': [0.0, 0.0], 'Graph': { 'edges': [], 'isDirected': False, 'isLabeled': False, 'isWeighted': False, 'vertices': [] }, 'GraphProperty': 'strongly_connected', 'Int': 0, 'ListOfCoordTwoDim': [], 'ListOfGraph': [], 'LogicErrorCategory': 'mistake', 'MusicPhrase': [], 'NonnegativeInt': 0, 'NormalizedString': u'', 'Real': 0.0, 'SetOfHtmlString': [], 'SetOfNormalizedString': [], 'SetOfUnicodeString': [], 'UnicodeString': u'' } def get_rules_for_obj_type(obj_type): """Gets all rules for a given object type. Args: obj_type: str. The name of the object type. """ rule_dir = os.path.join(os.getcwd(), feconf.RULES_DIR) rule_class_name = '%sRule' % obj_type results = [] for loader, name, _ in pkgutil.iter_modules(path=[rule_dir]): if name.endswith('_test'): continue module = loader.find_module(name).load_module(name) for name, clazz in inspect.getmembers(module, inspect.isclass): ancestors = clazz.__bases__ ancestor_class_names = [c.__name__ for c in ancestors] if rule_class_name in ancestor_class_names: results.append(clazz) return results def get_description_strings_for_obj_type(obj_type): """Returns a dict whose keys are rule names and whose values are the corresponding description strings. """ rules = get_rules_for_obj_type(obj_type) return { rule.__name__: rule.description for rule in rules } def get_param_list(description): """Get a parameter list from the rule description.""" param_list = [] while description.find('{{') != -1: opening_index = description.find('{{') description = description[opening_index + 2:] bar_index = description.find('|') param_name = description[: bar_index] description = description[bar_index + 1:] closing_index = description.find('}}') normalizer_string = description[: closing_index] description = description[closing_index + 2:] param_list.append( (param_name, getattr(objects, normalizer_string)) ) return param_list CERTAIN_TRUE_VALUE = 1.0 CERTAIN_FALSE_VALUE = 0.0 class Rule(object): """Abstract base class for a value object that represents a rule. All rules assume that the subject and rule initialization parameters are JSONifiable objects (such as primitives, lists, dicts, and compositions of these, but NOT sets, tuples, etc.). This is enforced by normalizing the subject and rule initialization parameters to JSONifiable objects before any evaluations are performed. """ subject_type = None # Description of the rule, e.g. "is equal to {{x|Int}}". Should be # overridden by subclasses. description = '' _params = None _fs = None @property def params(self): if self._params is None: # Derive the rule params from its description. self._params = get_param_list(self.description) return self._params def __init__(self, *args): if len(args) != len(self.params): raise ValueError( 'Expected parameters %s, received %s' % (self.params, args)) for ind, param_tuple in enumerate(self.params): setattr(self, param_tuple[0], param_tuple[1].normalize(args[ind])) self._validate_params() def _validate_params(self): """Validates the rule object immediately after initialization.""" pass def _evaluate(self, subject): """Returns a normalized value between 0 and 1 indicating the truth value of the evaluation, where 1.0 is certainly true and 0.0 is certainly false. This is to be implemented in overridden classes, or implemented in the frontend. """ raise NotImplementedError def _fuzzify_truth_value(self, bool_value): """Returns a fuzzy truth value for a crisp true or false value. A crisp value of true is represented by the fuzzy value of 1.0 and a crisp value of false is represented by 0.0. """ return CERTAIN_TRUE_VALUE if bool(bool_value) else CERTAIN_FALSE_VALUE def _invert_fuzzy_truth_value(self, fuzzy_value): """Performs a NOT operation on a fuzzy value.""" return CERTAIN_TRUE_VALUE - fuzzy_value def set_fs(self, fs): """Set an abstract file system to use with this rule.""" self._fs = fs return self @property def fs(self): return self._fs def eval(self, subject): """Public evaluation method. Args: subject: the thing to be evaluated. Returns: float: the result of the evaluation (between 0.0 and 1.0). """ return self._evaluate(self.subject_type.normalize(subject)) def evaluate_rule(rule_spec, answer_type, context_params, answer, fs): """Evaluates a rule spec. Returns a float between 0.0 and 1.0.""" all_rule_classes = get_rules_for_obj_type(answer_type) rule = next(r for r in all_rule_classes if r.__name__ == rule_spec.rule_type) param_list = [] param_defns = get_param_list(rule.description) for (param_name, obj_cls) in param_defns: parsed_param = rule_spec.inputs[param_name] if isinstance(parsed_param, basestring) and '{{' in parsed_param: parsed_param = jinja_utils.parse_string( parsed_param, context_params, autoescape=False) normalized_param = obj_cls.normalize(parsed_param) param_list.append(normalized_param) constructed_rule = rule(*param_list) constructed_rule.set_fs(fs) return constructed_rule.eval(answer)
32.4875
80
0.659997
c4ca0c0bb9de934815d9f0378df5150e1beb4c53
411
py
Python
tracker/migrations/0029_auto_20190916_1346.py
shapeshift-legacy/watchtower
c9cd5150f8549145f7de9b1ea820d548959350fe
[ "MIT" ]
null
null
null
tracker/migrations/0029_auto_20190916_1346.py
shapeshift-legacy/watchtower
c9cd5150f8549145f7de9b1ea820d548959350fe
[ "MIT" ]
null
null
null
tracker/migrations/0029_auto_20190916_1346.py
shapeshift-legacy/watchtower
c9cd5150f8549145f7de9b1ea820d548959350fe
[ "MIT" ]
null
null
null
# Generated by Django 2.0.7 on 2019-09-16 19:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tracker', '0028_xpub_updated_at'), ] operations = [ migrations.AlterField( model_name='balancechange', name='amount', field=models.DecimalField(decimal_places=0, max_digits=78), ), ]
21.631579
71
0.615572
4250cb72de9a9807f602bd24143425fc23146c0b
614
py
Python
takeprofit/main.py
metaperl/apiary-support
bd09c22a8dbd94d310e638ef70e0fa09a239b5c0
[ "MIT" ]
1
2015-12-23T03:34:41.000Z
2015-12-23T03:34:41.000Z
takeprofit/main.py
metaperl/apiary-support
bd09c22a8dbd94d310e638ef70e0fa09a239b5c0
[ "MIT" ]
null
null
null
takeprofit/main.py
metaperl/apiary-support
bd09c22a8dbd94d310e638ef70e0fa09a239b5c0
[ "MIT" ]
null
null
null
#!/usr/bin/env python from __future__ import print_function # core import logging import decimal # pypi import argh # local logging.basicConfig( format='%(lineno)s %(message)s', level=logging.WARN ) one_percent = 1.0 / 100.0 two_percent = 2.0 / 100.0 decimal.getcontext().prec = 8 def main(entry, percent=6): entry = decimal.Decimal(entry) x_percent = decimal.Decimal(percent / 100.0) tp = entry * x_percent + entry print("On an entry of {0:f}, TP={1:.8f} for a {2} percent gain".format( entry, tp, percent)) if __name__ == '__main__': argh.dispatch_command(main)
16.157895
75
0.666124
5b9f78801f136fffa8c2f8e992911be380664e71
42,109
py
Python
app/default_prefs.py
fsx950223/ci_edit
c0158bae9a776ad31fcadb213ab14726ef5c00c4
[ "Apache-2.0" ]
1
2020-11-24T16:59:40.000Z
2020-11-24T16:59:40.000Z
app/default_prefs.py
fsx950223/ci_edit
c0158bae9a776ad31fcadb213ab14726ef5c00c4
[ "Apache-2.0" ]
null
null
null
app/default_prefs.py
fsx950223/ci_edit
c0158bae9a776ad31fcadb213ab14726ef5c00c4
[ "Apache-2.0" ]
null
null
null
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from __future__ import division from __future__ import print_function import re import os import sys import app.log import app.regex _todo = r"TODO\([\S@.]+\)" __common_keywords = [ "break", "continue", "else", "for", "if", "return", "while" ] __c_keywords = __common_keywords + [ "case", "const", "default", "do", "enum", "goto", "sizeof", "static", "struct", "switch", "typedef" ] __linux_commands = [ "ag", "basename", "bash", "cd", "chmod", "cp", "dircolors", "dirname", "echo", "egrep", "find", "grep", "ixoff", "ixon", "lesspipe", "ln", "ls", "mkdir", "read", "rm", "rmdir", "rxvt", "sed", "sh", "shell", "sleep", "ssh", "tput", "wc" ] if sys.version_info[0] == 2: # The Python2 re limits the number of named groups. Reduce the keywords # recognized. __cpp_keywords = [ "auto", "break", "case", "catch", "class", "const", "constexpr", "continue", "default", "delete", "do", "else", "enum", "export", "false", "for", "friend", "if", "inline", "mutable", "namespace", "new", "noexcept", "nullptr", "override", "private", "protected", "public", "return", "sizeof", "static", "struct", "switch", "template", "this", "throw", "true", "typedef", "typename", "virtual", "while" ] __c_primitive_types = [ "bool", "char", "double", "float", "int", "int8_t", "int16_t", "int32_t", "int64_t", "int_max_t", "int8_t", "int16_t", "int32_t", "int64_t", "intptr_t", "ptrdiff_t", "size_t", "long", "signed", "short", "uint8_t", "uint16_t", "uint32_t", "uint_max_t", "uintptr_t", "unsigned", "void", "wchar_t" ] else: __cpp_keywords = [ "alignas", "alignof", "and", "and_eq", "asm", "audit", "auto", "axiom", "bitand", "bitor", "break", "case", "catch", "class", "compl", "concept", "const", "const_cast", "consteval", "constexpr", "continue", "decltype", "default", "delete", "do", "dynamic_cast", "else", "enum", "explicit", "export", "extern", "false", "final", "for", "friend", "goto", "if", "inline", "mutable", "namespace", "new", "noexcept", "not", "not_eq", "nullptr", "operator", "or", "or_eq", "override", "private", "protected", "public", "register", "reinterpret_cast", "return", "sizeof", "static", "static_assert", "static_cast", "struct", "switch", "template", "this", "thread_local", "throw", "true", "typedef", "typename", "virtual", "volatile", "while", "xor", "xor_eq" ] __c_primitive_types = [ "bool", "char", "double", "float", "int", "int8_t", "int16_t", "int32_t", "int64_t", "int_fast8_t", "int_fast16_t", "int_fast32_t", "int_fast64_t", "int_least8_t", "int_least16_t", "int_least32_t", "int_least64_t", "int_max_t", "int8_t", "int16_t", "int32_t", "int64_t", "intptr_t", "ptrdiff_t", "size_t", "long", "signed", "short", "uint8_t", "uint16_t", "uint32_t", "uint64_t", "uint_fast8_t", "uint_fast16_t", "uint_fast32_t", "uint_fast64_t", "uint_least8_t", "uint_least16_t", "uint_least32_t", "uint_least64_t", "uint_max_t", "uintptr_t", "unsigned", "void", "wchar_t" ] __chrome_extension = r"""\b[a-z]{32}\b""" __sha_1 = r"""\b[a-z0-9]{40}\b""" __special_string_escapes = [ r"\\\\", r"\\b", r"\\f", r"\\n", r"\\r", r"\\t", r"\\v", r"\\0[0-7]{0,3}", #r"%#?-?[0-9]*\.?[0-9]*z?.", __chrome_extension, __sha_1, ] color8 = { "_pre_selection": 1, "bracket": 1, "c": 0, "c_path_bracketed_file": 3, "c_path_quoted_file": 3, "c_preprocessor": 1, "c_preprocessor_include": 1, "c_raw_string1": 3, "c_raw_string2": 3, "c_string1": 3, "c_string2": 3, "context_menu": 1, "cpp_block_comment": 2, "cpp_line_comment": 2, "cpp_string_literal": 2, "current_line": 1, "debug_window": 1, "default": 0, "doc_block_comment": 3, "error": 7, "found_find": 1, "highlight": 3, "html_block_comment": 2, "html_element": 1, "html_element_end": 1, "js_string": 3, "keyword": 1, "line_number": 7, "line_number_current": 6, "line_overflow": 7, "logo": 7, "matching_bracket": 1, "matching_find": 1, "md_link": 2, "message_line": 3, "misspelling": 3, "number": 1, "outside_document": 7, "popup_window": 0, "pound_comment": 3, "py_import": 1, "py_import_file": 2, "py_raw_string1": 2, "py_raw_string2": 2, "py_string1": 2, "py_string2": 2, "quoted_string2": 2, "regex_string": 2, "right_column": 6, "rs_byte_string1": 3, "rs_byte_string2": 3, "rs_raw_string": 3, "selected": 5, "special": 1, "status_line": 7, "status_line_error": 7, "text": 0, "top_info": 7, "trailing_space": 1, "type": 1, } for i in color8.values(): assert 0 <= i < 8, i commentColor16Index = 2 defaultColor16Index = 1 foundColor16Index = 3 keywordsColor16Index = 2 pathColor16Index = 6 selectedColor16Index = 4 # Active find is a selection. specialsColor16Index = 5 stringColor16Index = 6 outsideOfBufferColor16Index = 7 borderColor16Index = 8 borderHighlightColor16Index = 9 color16 = { "_pre_selection": stringColor16Index, "bracket": 6, "c": defaultColor16Index, "c_path_bracketed_file": pathColor16Index, "c_path_quoted_file": pathColor16Index, "c_preprocessor": 1, "c_preprocessor_include": specialsColor16Index, "c_raw_string1": stringColor16Index, "c_raw_string2": stringColor16Index, "c_string1": stringColor16Index, "c_string2": stringColor16Index, "context_menu": 15, "cpp_block_comment": commentColor16Index, "cpp_line_comment": commentColor16Index, "cpp_string_literal": stringColor16Index, "current_line": 15, "debug_window": defaultColor16Index, "default": defaultColor16Index, "doc_block_comment": commentColor16Index, "error": 9, "found_find": foundColor16Index, "highlight": 15, "html_block_comment": commentColor16Index, "html_element": keywordsColor16Index, "html_element_end": keywordsColor16Index, "js_string": stringColor16Index, "keyword": keywordsColor16Index, "line_number": borderColor16Index, "line_number_current": borderHighlightColor16Index, "line_overflow": 15, "logo": borderColor16Index, "matching_bracket": 15, "matching_find": 9, "md_link": stringColor16Index, "message_line": borderColor16Index, "misspelling": 9, "number": 2, "outside_document": outsideOfBufferColor16Index, "popup_window": borderColor16Index, "pound_comment": commentColor16Index, "py_import": keywordsColor16Index, "py_import_file": stringColor16Index, "py_raw_string1": stringColor16Index, "py_raw_string2": stringColor16Index, "py_string1": stringColor16Index, "py_string2": stringColor16Index, "quoted_string2": stringColor16Index, "regex_string": stringColor16Index, "right_column": outsideOfBufferColor16Index, "rs_byte_string1": stringColor16Index, "rs_byte_string2": stringColor16Index, "rs_raw_string": stringColor16Index, "selected": selectedColor16Index, "special": specialsColor16Index, "status_line": borderColor16Index, "status_line_error": borderHighlightColor16Index, "text": defaultColor16Index, "top_info": borderColor16Index, "trailing_space": 15, "type": keywordsColor16Index, } for i in color16.values(): assert 0 <= i < 16, i commentColorIndex = 2 defaultColorIndex = 18 foundColorIndex = 32 keywordsColorIndex = 21 pathColorIndex = 30 selectedColor = 64 # Active find is a selection. specialsColorIndex = 20 stringColorIndex = 5 outsideOfBufferColorIndex = 211 color256 = { "_pre_selection": stringColorIndex, "bracket": 6, "c": defaultColorIndex, "c_path_bracketed_file": pathColorIndex, "c_path_quoted_file": pathColorIndex, "c_preprocessor": 1, "c_preprocessor_include": specialsColorIndex, "c_raw_string1": stringColorIndex, "c_raw_string2": stringColorIndex, "c_string1": stringColorIndex, "c_string2": stringColorIndex, "context_menu": 201, "cpp_block_comment": commentColorIndex, "cpp_line_comment": commentColorIndex, "cpp_string_literal": stringColorIndex, "current_line": 180, "debug_window": defaultColorIndex, "default": defaultColorIndex, "doc_block_comment": commentColorIndex, "error": 9, "found_find": foundColorIndex, "highlight": 96, "html_block_comment": commentColorIndex, "html_element": keywordsColorIndex, "html_element_end": keywordsColorIndex, "js_string": stringColorIndex, "keyword": keywordsColorIndex, "line_number": 168, "line_number_current": 146, "line_overflow": 105, "logo": 168, "matching_bracket": 201, "matching_find": 9, "md_link": stringColorIndex, "message_line": 3, "misspelling": 9, "number": 31, "outside_document": outsideOfBufferColorIndex, "popup_window": 117, "pound_comment": commentColorIndex, "py_import": keywordsColorIndex, "py_import_file": stringColorIndex, "py_raw_string1": stringColorIndex, "py_raw_string2": stringColorIndex, "py_string1": stringColorIndex, "py_string2": stringColorIndex, "quoted_string2": stringColorIndex, "regex_string": stringColorIndex, "right_column": outsideOfBufferColorIndex, "rs_byte_string1": stringColorIndex, "rs_byte_string2": stringColorIndex, "rs_raw_string": stringColorIndex, "selected": selectedColor, "special": specialsColorIndex, "status_line": 168, "status_line_error": 161, "text": defaultColorIndex, "top_info": 168, "trailing_space": 180, "type": keywordsColorIndex, } for i in color256.values(): assert 0 <= i < 256, i # Please keep these color dictionaries in sync. assert color8.keys() == color256.keys() assert color16.keys() == color256.keys() # These prefs are not fully working. prefs = { "color": {}, "devTest": {}, # TODO(dschuyler): provide a UI to enable selected dictionaries. u"dictionaries": { # The base dictionaries are loaded at startup. They are active for all # documents. "base": [ "acronyms", "coding", "contractions", "cpp", "css", "en-abbreviations", "en-gb", "en-misc", "en-us", "html", "name", "user", ], # If the expanded path to the current document contains |key| the list # of dictionaries are applied. "path_match": { u"/chromium/": [u"chromium"], u"/fuchsia/": [u"fuchsia"], }, }, "editor": { # E.g. When key "(" is pressed, "()" is typed. "autoInsertClosingCharacter": False, # When opening a path that starts with "//", the value is used to # replace the first slash in a double slash prefix. "baseDirEnv": u"/", # u"${FUCHSIA_DIR}", # Scroll the window to keep the cursor on screen. "captiveCursor": False, "colorScheme": "default", # Show hidden files in file list. "filesShowDotFiles": True, # Show the size on disk for files in the file list. "filesShowSizes": True, "filesShowModifiedDates": True, "filesSortAscendingByName": True, "filesSortAscendingBySize": None, "filesSortAscendingByModifiedDate": None, "findDotAll": False, "findIgnoreCase": True, "findLocale": False, "findMultiLine": False, "findUnicode": True, "findUseRegex": True, "findVerbose": False, "findWholeWord": False, # An example indentation. If the grammar has its own indent that can # override this value. "indentation": " ", "lineLimitIndicator": 80, # When the mouse wheel is moved, which way should the window scroll. "naturalScrollDirection": True, "onSaveStripTrailingSpaces": True, # Ratio of columns: 0 left, 1.0 right. "optimalCursorCol": 0.98, # Ratio of rows: 0 top, 0.5 middle, 1.0 bottom. "optimalCursorRow": 0.28, "palette": "default", "palette8": "default8", "palette16": "default16", "palette256": "default256", "predictionShowOpenFiles": True, "predictionShowAlternateFiles": True, "predictionShowRecentFiles": True, "predictionSortAscendingByPrediction": True, "predictionSortAscendingByType": None, "predictionSortAscendingByName": None, "predictionSortAscendingByStatus": None, "saveUndo": True, "showLineNumbers": True, "showStatusLine": True, "showTopInfo": True, # Convert/expand tabs to spaces (see tabSize). "tabToSpaces": True, # When expanding tabs to spaces, how many spaces to use. This is not # used for indentation, see "indentation" or grammar "indent". "tabSize": 8, # Use a background thread to process changes and parse grammars. "useBgThread": True, }, "fileType": { "bash": { "ext": [".bash", ".sh"], "grammar": "bash", "tabToSpaces": True, }, "bazel": { "ext": [], "grammar": "bazel", "name": ["BUILD"], "tabToSpaces": True, }, "binary": { "ext": [ ".exe", ".gz", ".gzip", ".jar", ".jpg", ".jpeg", ".o", ".obj", ".png", ".pyc", ".pyo", ".tgz", ".tiff", ".zip" ], "grammar": "binary", "tabToSpaces": False, }, "c": { "ext": [".c"], "grammar": "c", "tabToSpaces": True, }, "cpp": { "ext": [ ".cc", ".cpp", ".cxx", ".c++", ".hpp", ".hxx", ".h++", ".inc", ".h" # Hmm, some source uses .h for cpp headers. ], "grammar": "cpp", "tabToSpaces": True, }, "css": { "ext": [".css", "_css.html"], "grammar": "css", "tabToSpaces": True, }, "dart": { "ext": [ ".dart", ], "grammar": "dart", "tabToSpaces": True, }, "gn": { "ext": [".gn"], "grammar": "gn", "tabToSpaces": True, }, "golang": { "ext": [ ".go", ], "grammar": "golang", "tabToSpaces": True, }, "grd": { "ext": [".grd", ".grdp"], "grammar": "grd", "tabToSpaces": True, }, "html": { "ext": [".htm", ".html"], "grammar": "html", "tabToSpaces": True, }, "java": { "ext": [ ".java", ], "grammar": "java", "tabToSpaces": True, }, "js": { "ext": [".json", ".js"], "grammar": "js", "tabToSpaces": True, }, "make": { "ext": [], "grammar": "make", "name": ["Makefile"], "tabToSpaces": False, }, "md": { "ext": [".md"], "grammar": "md", "tabToSpaces": True, }, "proto": { "ext": [".proto"], "grammar": "proto", "tabToSpaces": True, }, "python": { "ext": [".py"], "grammar": "py", "tabToSpaces": True, }, "rust": { "ext": [".rs"], "grammar": "rs", "tabToSpaces": True, }, "text": { "ext": [".txt"], "grammar": "text", "tabToSpaces": False, }, "words": { "ext": [".words", ""], "grammar": "words", "tabToSpaces": True, }, }, "grammar": { # A grammar is # "grammar_name": { # "begin": None or regex, # "continuation": None or string, # Prefixed used when continuing to another line, # "end": None or regex; a value of None means that the "begin" regex # contains the entire pattern (a leaf grammar), # "end_key": None or regex to determine dynamic end tag. For "here # documents" and c++ string literals. # "error": None or list of string. # "escaped": None or regex, # "indent": None or string, # "next": other grammars that may follow this grammar without nesting # within it. (Contrast with "contains"). # "numbers": None or list of string, # "keywords": None or list of string. Matches whole words only (wraps # values in \b). # "single_line": Boolean, Whether entire grammar must be on a single # line, # "special": None or list of string. # "tabToSpaces": Boolean, Convert/expand tabs to spaces (see tabSize). # "type": text or binary. default: text. # "contains": other grammars that may be contained within this # grammar. # } # The entries for "error", "keywords", and "special" are very similar. # Other than "keywords" being wrapped in \b markers, the difference # between them is just how they are drawn (color and style). "_pre": { "contains": ["_pre_selection"], "spelling": False, }, "_pre_selection": { "begin": r"-->", "end": r"<--", "spelling": False, }, # Bash shell. "bash": { "indent": " ", "keywords": [ "break", "case", "continue", "do", "done", "echo", "else", "esac", "exit", "fi", "if", "for", "return", "switch", "then", "while" ], # Not really types. "types": __linux_commands, "contains": ["c_string1", "c_string2", "pound_comment"], }, # Bazel build script. See https://www.bazel.build/ "bazel": { "indent": " ", "keywords": [ "testonly" ], "types": "", "contains": ["py_string1", "py_string2", "pound_comment"], }, "binary": { "spelling": False, "type": "binary", }, # C language. "c": { "indent": " ", "keywords": __c_keywords, "types": __c_primitive_types, "contains": [ "cpp_block_comment", "cpp_line_comment", "c_preprocessor", "c_string1", "c_string2" ], }, # C++ language. "cpp": { "indent": " ", "keywords": __cpp_keywords, "namespaces": [ "::", "std::", ], "types": __c_primitive_types + [ "char8_t", "char16_t", "char32_t", ], "contains": [ "cpp_block_comment", "cpp_line_comment", "c_preprocessor", "cpp_string_literal", "c_string1", "c_string2" ], }, "cpp_block_comment": { "begin": r"/\*", "continuation": " * ", "end": r"\*/", "indent": " ", "keywords": [], "special": [ r"\bNOTE:", _todo, __chrome_extension, __sha_1, ], }, "cpp_line_comment": { "begin": "//", "continuation": "// ", "end": r"(?<!\\)\n", "indent": " ", "keywords": [], "special": [ r"\bNOTE:", _todo, __chrome_extension, __sha_1, ], }, "c_preprocessor": { "begin": r"^#", "end": r"(?<!\\)\n", "indent": " ", "special": [ r"\bdefine\b", r"\bdefined\b", r"\belif\b", r"\belif\b", r"\belse\b", r"\bendif\b", r"\bif\b", r"\bifdef\b", r"\bifndef\b", r"\binclude\b", r"\bpragma\b", r"\bundef\b", ], "next": [ "c_preprocessor_include", ], }, "c_preprocessor_include": { "begin": r"\binclude", "end": r"(?<!\\)\n", "contains": ["c_path_quoted_file", "c_path_bracketed_file"], }, "c_raw_string1": { "begin": "[uU]?[rR]'", "end": "'", "escaped": r"\\'", "indent": " ", "single_line": True, "special": __special_string_escapes + [r"\\'"], }, "c_raw_string2": { "begin": "[uU]?[rR]\"", "end": "\"", "escaped": "\\\\\"", "indent": " ", "single_line": True, "special": __special_string_escapes + ["\\\\\""], }, "cpp_string_literal": { "begin": "R\"", # TODO(dschuyler): backslash and whitespace are invalid in the # |end_key|. "end_key": """R\"([^(]*)\\(""", "end": "\\)\\0\"", "single_line": False, }, "c_string1": { "begin": "'(?!'')", "end": "'", "escaped": r"\\'", "indent": " ", "special": __special_string_escapes + [r"\\'"], "single_line": True, }, "c_string2": { "begin": "\"(?!\"\")", "end": "\"", "escaped": "\\\\\"", "indent": " ", "special": __special_string_escapes + ["\\\\\""], "single_line": True, }, "c_path_bracketed_file": { # Paths in includes don't allow escapes. "begin": """<[^>\\n]*>""", "end": None, # Leaf grammar. "link_type": "c<", # C system include file. }, "c_path_quoted_file": { # Paths in includes don't allow escapes. "begin": '''"[^"\\n]*"''', "end": None, # Leaf grammar. "link_type": "c\"", # C non-system include file. }, # Cascading Style Sheet. "css": { "begin": "<style", "end": "</style>", "indent": " ", "keywords": [ "host", "slotted", ], "special": [r"#[\w-]+"], "contains": ["cpp_block_comment", "css_block"], }, "css_block": { "begin": r"\\{", "end": r"\\}", "indent": " ", "keywords": [ "background-color", "color", "display", "font-family", "font-size", "height", "max-height", "min-height", "width", "max-width", "min-width" ], "special": [ r"@apply\b", ], "contains": ["cpp_block_comment", "css_value"], }, "css_value": { "begin": ":", "end": ";", "errors": [ r"#(?:[^;]{1,2}|[^;]{5}|[^;]{7}|[^;]{9,})\b", ], "indent": " ", "keywords": [ "absolute", "attr", "block", "border-box", "calc", "center", "default", "ease", "hidden", "inherit", "left", "none", "px", "rgb", "rgba", "right", "rotate[XYZ]?", "scale[XYZ]?", "solid", "transform", "translate[XYZ]?", "transparent", "var" ], "special": [ r"@apply\b", r"\d+deg\b", r"\d+em\b", r"\d+px\b", r"\d+rem\b", r"#(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{6}|[0-9a-fA-F]{3,4})" ], "contains": [ "cpp_block_comment", ], }, # Dart language. "dart": { "indent": " ", "keywords": [ "abstract", "as", "assert", "async", "async", "await", "break", "case", "catch", "class", "const", "continue", "covariant", "default", "deferred", "do", "dynamic", "else", "enum", "export", "extends", "external", "factory", "false", "final", "finally", "for", "get", "if", "implements", "import", "in", "interface", "is", "library", "mixin", "new", "null", "operator", "part", "rethrow", "return", "set", "static", "super", "switch", "sync", "this", "throw", "true", "try", "typedef", "var", "void", "while", "with", "yield" ], "special": [ "@override", ], "contains": [ # This list is carefully ordered. Don"t sort it. "py_string1", "py_string2", "py_raw_string1", "py_raw_string2", "c_raw_string1", "c_raw_string2", "c_string1", "c_string2", "cpp_line_comment", ], }, "doc_block_comment": { "begin": r"/\*\*", "continuation": " * ", "end": r"\*/", "indent": " ", "keywords": [], "special": [ r"@param\b", r"@private\b", r"@protected\b", r"@type\b", r"@typedef\b", r"@return\b", r"\bNOTE:", _todo, ], "types": ["Array", "boolean", "string", "Object"], }, "error": { "indent": " ", "spelling": False, }, # Generate Ninja language. "gn": { "indent": " ", "keywords": ["else", "false", "foreach", "if", "import", "true"], "special": [], "types": [], "contains": [ "pound_comment", "c_string1", "c_string2", ], }, # Go Language. "golang": { "indent": " ", "keywords": [ "break", "case", "chan", "const", "continue", "default", "defer", "else", "fallthrough", "for", "func", "go", "goto", "if", "import", "interface", "map", "nil", "package", "range", "return", "select", "struct", "switch", "type", "var" ], "special": [ #r"(?<!\w)__.*?__(?!\w)", ], "contains": [ "cpp_block_comment", "cpp_line_comment", "cpp_string_literal", "c_string1", "c_string2" ], }, "grd": { "keywords": ["flattenhtml", "allowexternalscript"], }, "html": { "begin": "<html>", "end": app.regex.kNonMatchingRegex, "errors": [ "</br>", "</hr>", "</img>", "</input>", ], "indent": " ", "keywords": [ #"body", "button", "div", "head", "html", "href", "img", #"input", "script", "select", "span", "style", ], "special": [ r"&.{1,5}?;", "<if\s+expr=\"[^\"]*[^>]*>", "</if>", ], "contains": [ "quoted_string1", "quoted_string2", "css", "html_block_comment", "js", "html_element", "html_element_end", ], }, "html_block_comment": { "begin": "<!--", "end": "-->", "indent": " ", }, "html_element": { "begin": r"<[\w-]+", # The "-" is used by Polymer. "contains": [ "html_element_attribute", ], "end": ">", "special": [ r"\\w+", ], }, "html_element_attribute": { "begin": "\\??=\"", "end": "\"", }, "html_element_end": { "begin": r"</\\w+", "end": ">", }, "java": { "indent": " ", "keywords": __common_keywords + [ "case", "class", "default", "do", "false", "interface", "switch", "this", "true" ], "contains": ["c_string1", "c_string2", "cpp_block_comment", "cpp_line_comment"], }, # JavaScript language. "js": { "begin": "<script", "end": "</script>", "indent": " ", "keywords": [ "arguments", "break", "case", "class", "const", "continue", "default", "delete", "document", "else", "false", "for", "function", "if", "instanceof", "let", "of", "return", "static", "switch", "super", "this", "true", "undefined", "var", "while", "yield" ], "special": [ "\bsetTimeout\b", "\brequestCallback\b", "\bconsole\b", "\bwindow\b", ], "contains": [ "c_string1", "c_string2", "doc_block_comment", "cpp_block_comment", "cpp_line_comment", "regex_string", "js_string", ], }, "js_string": { "begin": r"`", "end": r"`", "escaped": r"\\`", "indent": " ", "special": __special_string_escapes + [r"\\`", r"(?<!\\)\$\{[^}]*\}"], "single_line": False, }, "keyword": { "indent": " ", "spelling": False, }, # Makefile "make": { "indent": "\t", "keywords": [ "ifeq", "endif", "ifneq", "break", "case", "continue", "do", "done", "echo", "else", "esac", "exit", "fi", "if", "for", "return", "switch", "then", "while" ], # Not really types. "types": __linux_commands, "contains": ["c_string1", "c_string2", "pound_comment"], }, # Markdown language. "md": { "indent": " ", "keywords": [], #"special": [r"\[[^]]+\]\([^)]+\)"], "contains": [ "md_link", #"quoted_string1", "quoted_string2" ], }, "md_link": { "begin": "\[", "end": "\]", "escaped": r"\\\]", "indent": " ", }, "none": { "spelling": False, }, # Proto buffer language. "proto": { "indent": " ", "keywords": __common_keywords + ["message", "option", "package", "returns", "rpc", "syntax"], "namespaces": [], "special": [ #r"(?<!\w)__.*?__(?!\w)", ], "types": [ "bool", "bytes", "double", "enum", "float", "int8", "int16", "int32", "int64", "optional", "repeated", "required", "string", "uint8", "uint16", "uint32", "uint64" ], "contains": [ # This list is carefully ordered. Don"t sort it. "c_string1", "c_string2", "cpp_line_comment", ], }, # Python language. "py": { "indent": " ", "keywords": __common_keywords + [ "and", "as", "assert", "class", "def", "del", "dict", "elif", "except", "False", "finally", "from", "global", "import", "in", "is", "len", "list", "None", "not", "or", "pass", "raise", "range", "self", "True", "try", "tuple", "until", "with", "yield" ], "namespaces": [ "os\.", "os\.path\.", "sys\.", "traceback\.", "re\.", ], "special": [ #r"(?<!\w)__.*?__(?!\w)", ], "types": [ "Exception", ], "contains": [ # This list is carefully ordered. Don"t sort it. "py_string1", "py_string2", "py_raw_string1", "py_raw_string2", "c_raw_string1", "c_raw_string2", "c_string1", "c_string2", "pound_comment", "py_from", "py_import", ], }, "pound_comment": { "begin": "#", "continuation": "# ", "end": r"\n", "indent": " ", "keywords": [], "special": [ r"\bNOTE:", _todo, ], }, "py_from": { "begin": "from", "end": r"\n", "contains": ["py_import_file"], "next": ["py_import_after_from", "pound_comment"], "spelling": False, }, "py_import_after_from": { "begin": "import", "end": None, }, "py_import": { "begin": "import", "end": r"\n", "keywords": [ "as", ], "contains": ["py_import_file"], "next": ["pound_comment"], "spelling": False, }, "py_import_file": { "begin": "[\.\w]+", "end": None, # Leaf grammar. "link_type": r"pi", # Python import "spelling": False, }, "py_raw_string1": { "begin": "[uU]?[rR]'''", "end": "'''", "escaped": r"\\'", "indent": " ", #"special": ["\"\"?\"?$"], }, "py_raw_string2": { "begin": "[uU]?[rR]\"\"\"", "end": "\"\"\"", "escaped": "\\\\\"", "indent": " ", #"special": ["\\\\\""], }, "py_string1": { "begin": "[uU]?'''", "end": "'''", "escaped": r"\\'", #"indent": " ", "special": __special_string_escapes + [r"\\'"], }, "py_string2": { "begin": "[uU]?\"\"\"", "end": "\"\"\"", "escaped": "\\\\\"", #"indent": " ", "special": __special_string_escapes + ["\\\\\""], }, "quoted_string1": { # This is not a programming string, there are no escape chars. "begin": "'", "end": "'", }, "quoted_string2": { # This is not a programming string, there are no escape chars. "begin": "\"", "end": "\"", }, "regex_string": { "begin": r"(?<=[\n=:;([{,])(?:\s*)/(?![/*])", "end": "/", "escaped": r"\\.", "indent": " ", "special": __special_string_escapes + [r"\\/"], "single_line": True, }, # Rust language. "rs": { "indent": " ", "keywords": [ "abstract", "alignof", "as", "async", "await", "become", "box", "break", "const", "continue", "crate", "do", "dyn", "else", "enum", "extern", "false", "final", "fn", "for", "if", "impl", "in", "let", "loop", "macro", "match", "mod", "move", "mut", "offsetof", "override", "priv", "pub", "pure", "ref", "return", "Self", "self", "sizeof", "static", "struct", "super", "trait", "true", "type", "typeof", "try", "unsafe", "unsized", "use", "virtual", "where", "while", "yield" ], "special": [ #r"(?<!\w)__.*?__(?!\w)", "<\s*'", "&\s*'", ], "types": [ "bool", "char", "i8", "i16", "i32", "i64", "isize", "u8", "u16", "u32", "u64", "usize", "array", "slice", "tuple" ], "contains": [ "cpp_block_comment", "cpp_line_comment", "c_string1", "c_string2", "rs_byte_string1", "rs_byte_string2", "rs_raw_string", ], }, "rs_byte_string1": { "begin": "b'", "end": "'", }, "rs_byte_string2": { "begin": "b\"", "end": "\"", }, "rs_raw_string": { "begin": "b?r#*\"", # TODO(dschuyler): backslash and whitespace are invalid in the # |end_key|. "end_key": """b?r(#*)\"""", "end": "\"\\0", "single_line": False, }, "special": { "indent": " ", "spelling": False, }, "tabs": { "indent": "", "spelling": False, }, "text": { "special": [ __sha_1, ], "contains": ["quoted_string1", "quoted_string2"], }, "type": { "indent": " ", "spelling": False, }, # Dictionary file for ci_edit. "words": { "contains": [ "pound_comment", ], }, }, "palette": { # Note: index 0 of each palette is not set, it remains as the system # entry. "test": { # Same foreground color in all 256 slots. "foregroundIndexes": [18] * 256, # Separate background color in every slot. "backgroundIndexes": [i for i in range(0, 256)], }, "dark": { # This series repeats 8 times (32 * 8 = 256). "foregroundIndexes": [ 14, 202, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 12, 13, 14, 15, 202, 14, 14, 202, 202, 202, 22, 23, 24, 25, 26, 27, 28, 29, 30, 57 ] * 8, # Each of the foreground colors repeat 8 times (32 * 8 = 256). "backgroundIndexes": [232] * 32 + [229] * 32 + [6] * 32 + [221] * 32 + [245] * 32 + [244] * 32 + [243] * 32 + [225] * 32, }, "default8": { # With only 8 colors, make a custom pair for each slot. # 0: black, 1: red, 2: green, 3: yellow, 4: blue, 5: pink, 6: cyan, # 7: gray. "foregroundIndexes": [1, 4, 2, 3, 4, 5, 6, 0], "backgroundIndexes": [0, 6, 7, 7, 7, 7, 7, 7], }, "default16": { # With only 16 colors, make a custom pair for each slot. # 0: black, 1: red, 2: green, 3: yellow, 4: blue, 5: pink, 6: cyan, # 7: gray. "foregroundIndexes": [0, 1, 2, 3, 4, 5, 6, 7, 8, 4, 2, 3, 4, 5, 6, 0], "backgroundIndexes": [0, 15, 15, 15, 15, 15, 15, 15, 7, 7, 7, 7, 7, 7, 7, 15], }, "default256": { # This series repeats 8 times (32 * 8 = 256). "foregroundIndexes": [ 18, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 94, 134, 0, 240, 138, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 57 ] * 8, # Each of the foreground colors repeat 8 times (32 * 8 = 256). "backgroundIndexes": [231] * 32 + [229] * 32 + [14] * 32 + [221] * 32 + [255] * 32 + [254] * 32 + [253] * 32 + [225] * 32, }, }, "status": { "showTips": False, }, "userData": { "homePath": os.path.expanduser("~/.ci_edit"), "historyPath": os.path.join(os.path.expanduser("~/.ci_edit"), "history.dat"), }, } # Alias for old palette name. prefs[u"palette"][u"default"] = prefs[u"palette"][u"default256"]
32.022053
82
0.44221
4bf846dddbd49fdef0284b6fadc82561f6d5fe57
745
py
Python
test/nnUNetV1/network_training/nnUNetTrainer_DiceTopK10.py
jianhuasong/medical-image-segmentation2
cd13caeff4b583b30ee85df340e877463fcadd06
[ "Apache-2.0" ]
2,774
2019-05-31T02:32:52.000Z
2022-03-31T02:03:10.000Z
test/nnUNetV1/network_training/nnUNetTrainer_DiceTopK10.py
shenlong95/SegLoss
f3c1188ab32a0920be9f871e99418bc3a4f02291
[ "Apache-2.0" ]
36
2019-08-21T00:50:43.000Z
2022-02-17T12:12:50.000Z
test/nnUNetV1/network_training/nnUNetTrainer_DiceTopK10.py
shenlong95/SegLoss
f3c1188ab32a0920be9f871e99418bc3a4f02291
[ "Apache-2.0" ]
497
2019-08-02T09:23:23.000Z
2022-03-30T12:54:44.000Z
from nnunet.training.loss_functions.dice_loss import DC_and_topk_loss # from nnunet.training.network_training import nnUNetTrainerCE from nnunet.training.network_training.nnUNetTrainer import nnUNetTrainer class nnUNetTrainer_DiceTopK10(nnUNetTrainer): def __init__(self, plans_file, fold, output_folder=None, dataset_directory=None, batch_dice=True, stage=None, unpack_data=True, deterministic=True, fp16=False): super().__init__(plans_file, fold, output_folder, dataset_directory, batch_dice, stage, unpack_data, deterministic, fp16) k = 10 self.loss = DC_and_topk_loss({'batch_dice':self.batch_dice, 'smooth':1e-5, 'do_bg':False}, {'k':k})
53.214286
113
0.710067
7759602e39823db83bbfd61ecf84eff47e7d5995
11,490
py
Python
ottr/base/template.py
Callidon/pyOTTR
4bd7bdbf0674e285cf939e8da4cc4e7e2b7a419c
[ "MIT" ]
3
2019-11-20T09:15:00.000Z
2021-04-16T15:46:28.000Z
ottr/base/template.py
Callidon/pyOTTR
4bd7bdbf0674e285cf939e8da4cc4e7e2b7a419c
[ "MIT" ]
null
null
null
ottr/base/template.py
Callidon/pyOTTR
4bd7bdbf0674e285cf939e8da4cc4e7e2b7a419c
[ "MIT" ]
null
null
null
# template.py # Author: Thomas MINIER - MIT License 2019 from abc import ABC, abstractmethod from typing import Any, Dict, Iterable, List, Optional, Tuple from rdflib import BNode, Literal, URIRef, Variable from rdflib.namespace import RDFS from ottr.base.argument import InstanceArgument from ottr.base.utils import OTTR_IRI, OTTR_NONE from ottr.types import BoundedTerm, ExpansionResults, InputBindings class TemplateParameter(object): """The parameter of an OTTR Template. Args: * name: The parameter's name. * param_type: The parameter's type. * optional: if the parameter is optional or not. * nonblank: if the parameter accepts blank node or not. * default: the parameter's default value if it is set to `ottr:None`. """ def __init__(self, name: Variable, param_type: str, optional: bool, nonblank: bool, default: BoundedTerm = None): super(TemplateParameter, self).__init__() self._name = name self._param_type = param_type self._optional = optional self._nonblank = nonblank self._default = default # parameter with a default value are automatically set to optional if default is not None: self._optional = True @property def name(self) -> Variable: """Get the parameter name, i.e., a SPARQL variable""" return self._name def __str__(self) -> str: res = f"{self._param_type.n3()} {self._name.n3()}" if self._optional: res = "? " + res if self._nonblank: res = "! " + res return res def __repr__(self) -> str: return self.__str__() def validate(self, value: BoundedTerm) -> Tuple[bool, Optional[BoundedTerm], Optional[str]]: """Assert that a RDF Term can be used as argument for this parameter, *i.e.*, its value is compatible with the parameter definition (type, optional, non blank, etc). Argument: The value to validate. Returns: A tuple (`is_valid`, `value`, `error_reason`) where: * `is_valid` is a boolean which indicates the outcome of the validation. * `value` is the RDF value to use for the argument. Set to `None` if the validation was not successfull. * `error_reason` is an error message that indicates why the validation has failed. Set to `None` if the validation was successfull. """ # assert that the argument's type is correct if self._param_type != RDFS.Resource: # validate uris if self._param_type == OTTR_IRI and (type(value) == Literal or type(value) == Variable): return False, None, "expected an IRI but instead got a {}".format(type(value)) elif type(value) == Literal and value.datatype != self._param_type: return False, None, "expected a Literal with datatype {} but instead got {}".format(self._param_type.n3(), value.datatype) # assert that a non-optional parameter cannot be bound to ottr:None if not self._optional and value == OTTR_NONE: return False, None, 'this parameter is not optional, so it cannot be bound to ottr:none.' # assert that a non blank parameter is not bound to a blank node if self._nonblank and type(value) == BNode: return False, None, 'this parameter is non blank, so it cannot be bound to a blank node.' # if the value is None but has a default value, use the default value if value == OTTR_NONE and self._default is not None: return True, self._default, None # otherwise, everything is fine :-) return True, value, None class AbstractTemplate(ABC): """An abstract OTTR Template. Argument: The template's name as an RDF URI. """ def __init__(self, name: URIRef): super(AbstractTemplate, self).__init__() self._name = name self._parameters = dict() @property def name(self) -> URIRef: return self._name @abstractmethod def expand(self, arguments: InputBindings, all_templates: Dict[URIRef, Any], bnode_suffix: Tuple[int, int] = (0, 0), as_nt: bool = False) -> Iterable[ExpansionResults]: """Expands the template and yields RDF triples. Args: * arguments: Template instantation arguments. * all_templates: Map of all templates known at expansion times. * bnode_suffix: Pair of suffixes used for creating unique blank nodes. * as_nt: True if the RDF triples produced should be in n-triples format, False to use the rdflib format. Yields: RDF triples, in rdflib or n-triples format. """ pass def is_base(self) -> bool: """Returns True if the template is a base template, False otherwise""" return False def add_parameter(self, name: Variable, position: int, param_type: URIRef = RDFS.Resource, optional: bool = False, nonblank: bool = False, default: BoundedTerm = None) -> None: """Register a new parameter for this template. Args: * name: The parameter's name. * position: The parameter's position in the template definition. * param_type: The parameter's type (an URI). Defaults to `rdfs:Resource`. * optional: If the parameter is optional or not. Defaults to `False`. * nonblank: If the parameter accepts blank nodes or not. Defaults to `False`. * default: The parameter's default value if it is set to `ottr:None`. Example: >>> from rdflib import Literal, URIRref, Variable >>> from rdflib.namespace import Namespace, XSD >>> template.add_parameter(Variable("?uri"), 0, param_type=URIRef("http://ns.ottr.xyz/0.4/IRI"), nonblank=True) >>> template.add_parameter(Variable("?name"), 1, param_type=XSD.string, nonblank=True) """ if position not in self._parameters: self._parameters[position] = TemplateParameter(name, param_type, optional, nonblank, default=default) def format_arguments(self, arguments: List[Tuple[int, BoundedTerm]]) -> Dict[Variable, BoundedTerm]: """Format a list of expansion arguments so that they can be used for template expansion using the `expand()` method. Args: List of expansion arguments. Returns: Formatted list of expansion arguments, to be used with the expand() method. Example: >>> from rdflib import Literal, URIRef >>> from rdflib.namespace import XSD >>> raw_arguments = [ (0, URIRef("http://example.org#Anna")), (1, Literal("Anna")) ] >>> arguments = template.format_arguments(raw_arguments) >>> for triple in template.expand(arguments): >>> print(triple) """ args = dict() for position, value in arguments: if position in self._parameters: # validate that the argument can be used for this parameter is_valid, v, error_reason = self._parameters[position].validate(value) if is_valid: args[self._parameters[position].name] = v else: # TODO report/raise exception ?? raise Exception("Invalid argument {} used for parameter \"{}\". Reason : {} ".format(value.n3(), self._parameters[position], error_reason)) else: raise Exception("Missing argument in position {} in template {}".format(position, self._name.n3())) return args class MainTemplate(AbstractTemplate): """An OTTR template definition, which contains several instances to expand. Args: * name: The template name. * instances: Instances declared in the template. """ def __init__(self, name: URIRef, instances: List[AbstractTemplate]): super(MainTemplate, self).__init__(name) self._instances = instances def __str__(self) -> str: instances = ',\n'.join(map(lambda i: str(i), self._instances)) params = ', '.join(map(lambda i: str(i), self._parameters)) return f"{self.name}({params}) :: {{\n {instances} }}." def __repr__(self) -> str: return self.__str__() def expand(self, arguments: InputBindings, all_templates: Dict[URIRef, Any], bnode_suffix: Tuple[int, int] = (0, 0), as_nt: bool = False) -> Iterable[ExpansionResults]: """Expands the template and yields RDF triples. Args: * arguments: Template instantation arguments. * all_templates: Map of all templates known at expansion times. * bnode_suffix: Pair of suffixes used for creating unique blank nodes. * as_nt: True if the RDF triples produced should be in n-triples format, False to use the rdflib format. Yields: RDF triples, in rdflib or n-triples format. """ for instance in self._instances: yield from instance.expand(arguments, all_templates, bnode_suffix=bnode_suffix, as_nt=as_nt) class NonBaseInstance(AbstractTemplate): """A non-base OTTR Template instance. Args: * name: The template name. * instance_arguments: Arguments of the template. """ def __init__(self, name: URIRef, instance_arguments: List[InstanceArgument]): super(NonBaseInstance, self).__init__(name) # store bound & unbound instance arguments separately self._bound_arguments = [(x.position, x.value) for x in instance_arguments if x.is_bound] self._unbound_arguments = [(x.position, x.value) for x in instance_arguments if not x.is_bound] def expand(self, arguments: InputBindings, all_templates: Dict[URIRef, Any], bnode_suffix: Tuple[int, int] = (0, 0), as_nt: bool = False) -> Iterable[ExpansionResults]: """Expands the template and yields RDF triples. Args: * arguments: Template instantation arguments. * all_templates: Map of all templates known at expansion times. * bnode_suffix: Pair of suffixes used for creating unique blank nodes. * as_nt: True if the RDF triples produced should be in n-triples format, False to use the rdflib format. Yields: RDF triples, in rdflib or n-triples format. Throws: `Exception` when an undefined OTTR template is encountered. """ # increment the bnode unique prefixes, used to unify blank node acrros instance expansions bnode_suffix = (bnode_suffix[0], bnode_suffix[1] + 1) if self._name in all_templates: # fetch template template = all_templates[self._name] # try to link unbound instance arguments using the given arguments args = list(self._bound_arguments) for position, value in self._unbound_arguments: if value in arguments: args.append((position, arguments[value])) else: # TODO raise something ?? pass # prepare new arguments for recursive template expansion new_arguments = dict() new_arguments.update(arguments) new_arguments.update(template.format_arguments(args)) # recursively expand the template instance yield from template.expand(new_arguments, all_templates, bnode_suffix=bnode_suffix, as_nt=as_nt) else: raise Exception("Cannot expand the unkown OTTR template '{}'".format(self._name.n3()))
45.96
180
0.645431
b48fc9deda586cf351c371a5c3fd44d06a3a600f
1,751
py
Python
src/500coScraper.py
AlexanderProschek/company-email-sender
3e3ba86f4ff830bb20c6f691c28ce0f9d31291bf
[ "MIT" ]
null
null
null
src/500coScraper.py
AlexanderProschek/company-email-sender
3e3ba86f4ff830bb20c6f691c28ce0f9d31291bf
[ "MIT" ]
null
null
null
src/500coScraper.py
AlexanderProschek/company-email-sender
3e3ba86f4ff830bb20c6f691c28ce0f9d31291bf
[ "MIT" ]
null
null
null
#!python3 import requests import re from bs4 import BeautifulSoup from tqdm import tqdm import json # Prefixes in case script cannot find an email on companies website prefixes = ['info', 'team', 'support', 'hello', 'sales', 'contact', 'help', 'marketing', 'social', 'business'] # Base URL to query the emails url = 'https://companies.api.500.vc/api/v1/companies' resp = requests.get(url, timeout=10) respJSON = json.loads(resp.text) # Go through each URL for company in tqdm(respJSON['data']): compURL = re.sub('^ *http(|s)://(www\.|)', '', company['url']) compURL = re.sub('/.*$', '', compURL) tqdm.write(compURL) try: subRes = requests.get('http://' + compURL, timeout=10) subSoup = BeautifulSoup(subRes.text, 'html.parser') emails = [] found = False for mailTo in subSoup.find_all('a'): if 'href' in mailTo.attrs and re.search('^mailto:', mailTo.attrs['href']): # Clean up email email = re.sub('^mailto:', '', mailTo.attrs['href']) email = re.sub('?.*$', '', email) email = email.trim() # Check if email valid-ish and not a duplicate if re.search('[^@]+@[^@]+\.[^@]+', email) and email not in emails: tqdm.write("> " + email) emails.append(email) found = True if not found: for prefix in prefixes: emails.append(prefix + "@" + compURL) whereToSave = "gen500co.csv" if found: whereToSave = "500co.csv" with open(whereToSave, 'a') as file: for email in emails: file.write("%s\n" % email) except: pass
30.719298
110
0.544832