Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def enable_encryption(self, output_key, input_key): self._chacha = chacha20.Chacha20Cipher(output_key, input_key)
[ "Enable encryption with the specified keys." ]
Please provide a description of the function:def connect(self): return self.loop.create_connection(lambda: self, self.host, self.port)
[ "Connect to device." ]
Please provide a description of the function:def close(self): if self._transport: self._transport.close() self._transport = None self._chacha = None
[ "Close connection to device." ]
Please provide a description of the function:def send(self, message): serialized = message.SerializeToString() log_binary(_LOGGER, '>> Send', Data=serialized) if self._chacha: serialized = self._chacha.encrypt(serialized) log_binary(_LOGGER, '>> Send', Encrypted...
[ "Send message to device." ]
Please provide a description of the function:def data_received(self, data): # A message might be split over several reads, so we store a buffer and # try to decode messages from that buffer self._buffer += data log_binary(_LOGGER, '<< Receive', Data=data) while self._bu...
[ "Message was received from device." ]
Please provide a description of the function:async def get_data(self, path, headers=None, timeout=None): url = self.base_url + path _LOGGER.debug('GET URL: %s', url) resp = None try: resp = await self._session.get( url, headers=headers, ...
[ "Perform a GET request." ]
Please provide a description of the function:async def post_data(self, path, data=None, headers=None, timeout=None): url = self.base_url + path _LOGGER.debug('POST URL: %s', url) self._log_data(data, False) resp = None try: resp = await self._session.post( ...
[ "Perform a POST request." ]
Please provide a description of the function:def read_uint(data, start, length): return int.from_bytes(data[start:start+length], byteorder='big')
[ "Extract a uint from a position in a sequence." ]
Please provide a description of the function:def read_bplist(data, start, length): # TODO: pylint doesn't find FMT_BINARY, why? # pylint: disable=no-member return plistlib.loads(data[start:start+length], fmt=plistlib.FMT_BINARY)
[ "Extract a binary plist from a position in a sequence." ]
Please provide a description of the function:def raw_tag(name, value): return name.encode('utf-8') + \ len(value).to_bytes(4, byteorder='big') + \ value
[ "Create a DMAP tag with raw data." ]
Please provide a description of the function:def string_tag(name, value): return name.encode('utf-8') + \ len(value).to_bytes(4, byteorder='big') + \ value.encode('utf-8')
[ "Create a DMAP tag with string data." ]
Please provide a description of the function:def create(message_type, priority=0): message = protobuf.ProtocolMessage() message.type = message_type message.priority = priority return message
[ "Create a ProtocolMessage." ]
Please provide a description of the function:def device_information(name, identifier): # pylint: disable=no-member message = create(protobuf.DEVICE_INFO_MESSAGE) info = message.inner() info.uniqueIdentifier = identifier info.name = name info.localizedModelName = 'iPhone' info.systemBuil...
[ "Create a new DEVICE_INFO_MESSAGE." ]
Please provide a description of the function:def set_connection_state(): message = create(protobuf.ProtocolMessage.SET_CONNECTION_STATE_MESSAGE) message.inner().state = protobuf.SetConnectionStateMessage.Connected return message
[ "Create a new SET_CONNECTION_STATE." ]
Please provide a description of the function:def crypto_pairing(pairing_data): message = create(protobuf.CRYPTO_PAIRING_MESSAGE) crypto = message.inner() crypto.status = 0 crypto.pairingData = tlv8.write_tlv(pairing_data) return message
[ "Create a new CRYPTO_PAIRING_MESSAGE." ]
Please provide a description of the function:def client_updates_config(artwork=True, now_playing=True, volume=True, keyboard=True): message = create(protobuf.CLIENT_UPDATES_CONFIG_MESSAGE) config = message.inner() config.artworkUpdates = artwork config.nowPlayingUpdates = ...
[ "Create a new CLIENT_UPDATES_CONFIG_MESSAGE." ]
Please provide a description of the function:def register_hid_device(screen_width, screen_height, absolute=False, integrated_display=False): message = create(protobuf.REGISTER_HID_DEVICE_MESSAGE) descriptor = message.inner().deviceDescriptor descriptor.absolute = 1 if absolute e...
[ "Create a new REGISTER_HID_DEVICE_MESSAGE." ]
Please provide a description of the function:def send_packed_virtual_touch_event(xpos, ypos, phase, device_id, finger): message = create(protobuf.SEND_PACKED_VIRTUAL_TOUCH_EVENT_MESSAGE) event = message.inner() # The packed version of VirtualTouchEvent contains X, Y, phase, deviceID # and finger s...
[ "Create a new WAKE_DEVICE_MESSAGE." ]
Please provide a description of the function:def send_hid_event(use_page, usage, down): message = create(protobuf.SEND_HID_EVENT_MESSAGE) event = message.inner() # TODO: This should be generated somehow. I guess it's mach AbsoluteTime # which is tricky to generate. The device does not seem to care...
[ "Create a new SEND_HID_EVENT_MESSAGE." ]
Please provide a description of the function:def command(cmd): message = create(protobuf.SEND_COMMAND_MESSAGE) send_command = message.inner() send_command.command = cmd return message
[ "Playback command request." ]
Please provide a description of the function:def repeat(mode): message = command(protobuf.CommandInfo_pb2.ChangeShuffleMode) send_command = message.inner() send_command.options.externalPlayerCommand = True send_command.options.repeatMode = mode return message
[ "Change repeat mode of current player." ]
Please provide a description of the function:def shuffle(enable): message = command(protobuf.CommandInfo_pb2.ChangeShuffleMode) send_command = message.inner() send_command.options.shuffleMode = 3 if enable else 1 return message
[ "Change shuffle mode of current player." ]
Please provide a description of the function:def seek_to_position(position): message = command(protobuf.CommandInfo_pb2.SeekToPlaybackPosition) send_command = message.inner() send_command.options.playbackPosition = position return message
[ "Seek to an absolute position in stream." ]
Please provide a description of the function:async def pair_with_device(loop): my_zeroconf = Zeroconf() details = conf.AppleTV('127.0.0.1', 'Apple TV') details.add_service(conf.DmapService('login_id')) atv = pyatv.connect_to_apple_tv(details, loop) atv.pairing.pin(PIN_CODE) await atv.pairi...
[ "Make it possible to pair with device." ]
Please provide a description of the function:def read_variant(variant): result = 0 cnt = 0 for data in variant: result |= (data & 0x7f) << (7 * cnt) cnt += 1 if not data & 0x80: return result, variant[cnt:] raise Exception('invalid variant')
[ "Read and parse a binary protobuf variant value." ]
Please provide a description of the function:async def print_what_is_playing(loop): details = conf.AppleTV(ADDRESS, NAME) details.add_service(conf.DmapService(HSGID)) print('Connecting to {}'.format(details.address)) atv = pyatv.connect_to_apple_tv(details, loop) try: print((await atv...
[ "Connect to device and print what is playing." ]
Please provide a description of the function:def add_listener(self, listener, message_type, data=None, one_shot=False): lst = self._one_shots if one_shot else self._listeners if message_type not in lst: lst[message_type] = [] lst[message_type].append(Listener(listener, dat...
[ "Add a listener that will receice incoming messages." ]
Please provide a description of the function:async def start(self): if self.connection.connected: return await self.connection.connect() # In case credentials have been given externally (i.e. not by pairing # with a device), then use that client id if self....
[ "Connect to device and listen to incoming messages." ]
Please provide a description of the function:def stop(self): if self._outstanding: _LOGGER.warning('There were %d outstanding requests', len(self._outstanding)) self._initial_message_sent = False self._outstanding = {} self._one_shots = {...
[ "Disconnect from device." ]
Please provide a description of the function:async def send_and_receive(self, message, generate_identifier=True, timeout=5): await self._connect_and_encrypt() # Some messages will respond with the same identifier as used in the # corresponding request. Ot...
[ "Send a message and wait for a response." ]
Please provide a description of the function:def message_received(self, message): # If the message identifer is outstanding, then someone is # waiting for the respone so we save it here identifier = message.identifier or 'type_' + str(message.type) if identifier in self._outstan...
[ "Message was received from device." ]
Please provide a description of the function:async def playstatus(self, use_revision=False, timeout=None): cmd_url = _PSU_CMD.format( self.playstatus_revision if use_revision else 0) resp = await self.daap.get(cmd_url, timeout=timeout) self.playstatus_revision = parser.first...
[ "Request raw data about what is currently playing.\n\n If use_revision=True, this command will \"block\" until playstatus\n changes on the device.\n\n Must be logged in.\n " ]
Please provide a description of the function:async def artwork(self): art = await self.daap.get(_ARTWORK_CMD, daap_data=False) return art if art != b'' else None
[ "Return an image file (png) for what is currently playing.\n\n None is returned if no artwork is available. Must be logged in.\n " ]
Please provide a description of the function:def ctrl_int_cmd(self, cmd): cmd_url = 'ctrl-int/1/{}?[AUTH]&prompt-id=0'.format(cmd) return self.daap.post(cmd_url)
[ "Perform a \"ctrl-int\" command." ]
Please provide a description of the function:def controlprompt_cmd(self, cmd): data = tags.string_tag('cmbe', cmd) + tags.uint8_tag('cmcc', 0) return self.daap.post(_CTRL_PROMPT_CMD, data=data)
[ "Perform a \"controlpromptentry\" command." ]
Please provide a description of the function:def set_property(self, prop, value): cmd_url = 'ctrl-int/1/setproperty?{}={}&[AUTH]'.format( prop, value) return self.daap.post(cmd_url)
[ "Change value of a DAAP property, e.g. volume or media position." ]
Please provide a description of the function:async def up(self): await self._send_commands( self._move('Down', 0, 20, 275), self._move('Move', 1, 20, 270), self._move('Move', 2, 20, 265), self._move('Move', 3, 20, 260), self._move('Move', 4, 2...
[ "Press key up." ]
Please provide a description of the function:async def down(self): await self._send_commands( self._move('Down', 0, 20, 250), self._move('Move', 1, 20, 255), self._move('Move', 2, 20, 260), self._move('Move', 3, 20, 265), self._move('Move', 4,...
[ "Press key down." ]
Please provide a description of the function:async def left(self): await self._send_commands( self._move('Down', 0, 75, 100), self._move('Move', 1, 70, 100), self._move('Move', 3, 65, 100), self._move('Move', 4, 60, 100), self._move('Move', 5,...
[ "Press key left." ]
Please provide a description of the function:async def right(self): await self._send_commands( self._move('Down', 0, 50, 100), self._move('Move', 1, 55, 100), self._move('Move', 3, 60, 100), self._move('Move', 4, 65, 100), self._move('Move', 5...
[ "Press key right." ]
Please provide a description of the function:def set_position(self, pos): time_in_ms = int(pos)*1000 return self.apple_tv.set_property('dacp.playingtime', time_in_ms)
[ "Seek in the current playing media." ]
Please provide a description of the function:def media_type(self): state = parser.first(self.playstatus, 'cmst', 'caps') if not state: return const.MEDIA_TYPE_UNKNOWN mediakind = parser.first(self.playstatus, 'cmst', 'cmmk') if mediakind is not None: ret...
[ "Type of media is currently playing, e.g. video, music." ]
Please provide a description of the function:def play_state(self): state = parser.first(self.playstatus, 'cmst', 'caps') return convert.playstate(state)
[ "Play state, e.g. playing or paused." ]
Please provide a description of the function:def start(self, initial_delay=0): if self.listener is None: raise exceptions.NoAsyncListenerError elif self._future is not None: return None # Always start with 0 to trigger an immediate response for the # fir...
[ "Wait for push updates from device.\n\n Will throw NoAsyncListenerError if no listner has been set.\n " ]
Please provide a description of the function:async def authenticate_with_device(atv): credentials = await atv.airplay.generate_credentials() await atv.airplay.load_credentials(credentials) try: await atv.airplay.start_authentication() pin = input('PIN Code: ') await atv.airplay...
[ "Perform device authentication and print credentials." ]
Please provide a description of the function:def encrypt(self, data, nounce=None): if nounce is None: nounce = self._out_counter.to_bytes(length=8, byteorder='little') self._out_counter += 1 return self._enc_out.seal(b'\x00\x00\x00\x00' + nounce, data, bytes())
[ "Encrypt data with counter or specified nounce." ]
Please provide a description of the function:def decrypt(self, data, nounce=None): if nounce is None: nounce = self._in_counter.to_bytes(length=8, byteorder='little') self._in_counter += 1 decrypted = self._enc_in.open( b'\x00\x00\x00\x00' + nounce, data, by...
[ "Decrypt data with counter or specified nounce." ]
Please provide a description of the function:def auto_connect(handler, timeout=5, not_found=None, event_loop=None): # A coroutine is used so we can connect to the device while being inside # the event loop async def _handle(loop): atvs = await pyatv.scan_for_apple_tvs( loop, timeout...
[ "Short method for connecting to a device.\n\n This is a convenience method that create an event loop, auto discovers\n devices, picks the first device found, connects to it and passes it to a\n user provided handler. An optional error handler can be provided that is\n called when no device was found. Ve...
Please provide a description of the function:async def login(self): # Do not use session.get_data(...) in login as that would end up in # an infinte loop. def _login_request(): return self.http.get_data( self._mkurl('login?[AUTH]&hasFP=1', ...
[ "Login to Apple TV using specified login id." ]
Please provide a description of the function:async def get(self, cmd, daap_data=True, timeout=None, **args): def _get_request(): return self.http.get_data( self._mkurl(cmd, *args), headers=_DMAP_HEADERS, timeout=timeout) await self._a...
[ "Perform a DAAP GET command." ]
Please provide a description of the function:def get_url(self, cmd, **args): return self.http.base_url + self._mkurl(cmd, *args)
[ "Expand the request URL for a request." ]
Please provide a description of the function:async def post(self, cmd, data=None, timeout=None, **args): def _post_request(): headers = copy(_DMAP_HEADERS) headers['Content-Type'] = 'application/x-www-form-urlencoded' return self.http.post_data( self....
[ "Perform DAAP POST command with optional data." ]
Please provide a description of the function:def set_repeat(self, repeat_mode): # TODO: extract to convert module if int(repeat_mode) == const.REPEAT_STATE_OFF: state = 1 elif int(repeat_mode) == const.REPEAT_STATE_ALL: state = 2 elif int(repeat_mode) == ...
[ "Change repeat mode." ]
Please provide a description of the function:def play_state(self): # TODO: extract to a convert module state = self._setstate.playbackState if state == 1: return const.PLAY_STATE_PLAYING if state == 2: return const.PLAY_STATE_PAUSED return const....
[ "Play state, e.g. playing or paused." ]
Please provide a description of the function:def genre(self): if self._metadata: from pyatv.mrp.protobuf import ContentItem_pb2 transaction = ContentItem_pb2.ContentItem() transaction.ParseFromString(self._metadata)
[ "Genre of the currently playing song." ]
Please provide a description of the function:def total_time(self): now_playing = self._setstate.nowPlayingInfo if now_playing.HasField('duration'): return int(now_playing.duration) return None
[ "Total play time in seconds." ]
Please provide a description of the function:def position(self): now_playing = self._setstate.nowPlayingInfo if now_playing.HasField('elapsedTime'): return int(now_playing.elapsedTime) return None
[ "Position in the playing media (seconds)." ]
Please provide a description of the function:def shuffle(self): info = self._get_command_info(CommandInfo_pb2.ChangeShuffleMode) return None if info is None else info.shuffleMode
[ "If shuffle is enabled or not." ]
Please provide a description of the function:def repeat(self): info = self._get_command_info(CommandInfo_pb2.ChangeRepeatMode) return None if info is None else info.repeatMode
[ "Repeat mode." ]
Please provide a description of the function:async def playing(self): # TODO: This is hack-ish if self._setstate is None: await self.protocol.start() # No SET_STATE_MESSAGE received yet, use default if self._setstate is None: return MrpPlaying(protobuf.S...
[ "Return what is currently playing." ]
Please provide a description of the function:def start(self, initial_delay=0): if self.listener is None: raise exceptions.NoAsyncListenerError elif self._enabled: return self._enabled = True
[ "Wait for push updates from device.\n\n Will throw NoAsyncListenerError if no listner has been set.\n " ]
Please provide a description of the function:async def stop(self, **kwargs): if not self._pin_code: raise Exception('no pin given') # TODO: new exception self.service.device_credentials = \ await self.pairing_procedure.finish_pairing(self._pin_code)
[ "Stop pairing process." ]
Please provide a description of the function:def read_tlv(data): def _parse(data, pos, size, result=None): if result is None: result = {} if pos >= size: return result tag = str(data[pos]) length = data[pos+1] value = data[pos+2:pos+2+length] ...
[ "Parse TLV8 bytes into a dict.\n\n If value is larger than 255 bytes, it is split up in multiple chunks. So\n the same tag might occurr several times.\n " ]
Please provide a description of the function:def write_tlv(data): tlv = b'' for key, value in data.items(): tag = bytes([int(key)]) length = len(value) pos = 0 # A tag with length > 255 is added multiple times and concatenated into # one buffer when reading the TLV ...
[ "Convert a dict to TLV8 bytes." ]
Please provide a description of the function:def comment(value, comment_text): if isinstance(value, Doc): return comment_doc(value, comment_text) return comment_value(value, comment_text)
[ "Annotates a value or a Doc with a comment.\n\n When printed by prettyprinter, the comment will be\n rendered next to the value or Doc.\n " ]
Please provide a description of the function:def register_pretty(type=None, predicate=None): if type is None and predicate is None: raise ValueError( "You must provide either the 'type' or 'predicate' argument." ) if type is not None and predicate is not None: raise Va...
[ "Returns a decorator that registers the decorated function\n as the pretty printer for instances of ``type``.\n\n :param type: the type to register the pretty printer for, or a ``str``\n to indicate the module and name, e.g.: ``'collections.Counter'``.\n :param predicate: a predicate functi...
Please provide a description of the function:def commentdoc(text): if not text: raise ValueError( 'Expected non-empty comment str, got {}'.format(repr(text)) ) commentlines = [] for line in text.splitlines(): alternating_words_ws = list(filter(None, WHITESPACE_PATTE...
[ "Returns a Doc representing a comment `text`. `text` is\n treated as words, and any whitespace may be used to break\n the comment to multiple lines." ]
Please provide a description of the function:def pretty_call(ctx, fn, *args, **kwargs): return pretty_call_alt(ctx, fn, args, kwargs)
[ "Returns a Doc that represents a function call to :keyword:`fn` with\n the remaining positional and keyword arguments.\n\n You can only use this function on Python 3.6+. On Python 3.5, the order\n of keyword arguments is not maintained, and you have to use\n :func:`~prettyprinter.pretty_call_alt`.\n\n ...
Please provide a description of the function:def pretty_call_alt(ctx, fn, args=(), kwargs=()): fndoc = general_identifier(fn) if ctx.depth_left <= 0: return concat([fndoc, LPAREN, ELLIPSIS, RPAREN]) if not kwargs and len(args) == 1: sole_arg = args[0] unwrapped_sole_arg, _com...
[ "Returns a Doc that represents a function call to :keyword:`fn` with\n the ``args`` and ``kwargs``.\n\n Given an arbitrary context ``ctx``,::\n\n pretty_call_alt(ctx, sorted, args=([7, 4, 5], ), kwargs=[('reverse', True)])\n\n Will result in output::\n\n sorted([7, 4, 5], reverse=True)\n\n ...
Please provide a description of the function:def build_fncall( ctx, fndoc, argdocs=(), kwargdocs=(), hug_sole_arg=False, trailing_comment=None, ): if callable(fndoc): fndoc = general_identifier(fndoc) has_comment = bool(trailing_comment) argdocs = list(argdocs) kwa...
[ "Builds a doc that looks like a function call,\n from docs that represent the function, arguments\n and keyword arguments.\n\n If ``hug_sole_arg`` is True, and the represented\n functional call is done with a single non-keyword\n argument, the function call parentheses will hug\n the sole argument...
Please provide a description of the function:def assoc(self, key, value): return self._replace(user_ctx={ **self.user_ctx, key: value, })
[ "\n Return a modified PrettyContext with ``key`` set to ``value``\n " ]
Please provide a description of the function:def align(doc): validate_doc(doc) def evaluator(indent, column, page_width, ribbon_width): return Nest(column - indent, doc) return contextual(evaluator)
[ "Aligns each new line in ``doc`` with the first new line.\n " ]
Please provide a description of the function:def smart_fitting_predicate( page_width, ribbon_frac, min_nesting_level, max_width, triplestack ): chars_left = max_width while chars_left >= 0: if not triplestack: return True indent, mode, doc = triplestack.pop...
[ "\n Lookahead until the last doc at the current indentation level.\n Pretty, but not as fast.\n " ]
Please provide a description of the function:def set_default_style(style): global default_style if style == 'dark': style = default_dark_style elif style == 'light': style = default_light_style if not issubclass(style, Style): raise TypeError( "style must be a s...
[ "Sets default global style to be used by ``prettyprinter.cpprint``.\n\n :param style: the style to set, either subclass of\n ``pygments.styles.Style`` or one of ``'dark'``, ``'light'``\n " ]
Please provide a description of the function:def indent(self, indent): curr_docparts = self._docparts self._docparts = [] self.indentation += indent try: yield finally: self.indentation -= indent indented_docparts = self._docparts ...
[ "with statement support for indenting/dedenting." ]
Please provide a description of the function:def intersperse(x, ys): it = iter(ys) try: y = next(it) except StopIteration: return yield y for y in it: yield x yield y
[ "\n Returns an iterable where ``x`` is inserted between\n each element of ``ys``\n\n :type ys: Iterable\n " ]
Please provide a description of the function:def pformat( object, indent=_UNSET_SENTINEL, width=_UNSET_SENTINEL, depth=_UNSET_SENTINEL, *, ribbon_width=_UNSET_SENTINEL, max_seq_len=_UNSET_SENTINEL, compact=_UNSET_SENTINEL, sort_dict_keys=_UNSET_SENTINEL ): sdocs = python_to_...
[ "\n Returns a pretty printed representation of the object as a ``str``.\n Accepts the same parameters as :func:`~prettyprinter.pprint`.\n The output is not colored.\n " ]
Please provide a description of the function:def pprint( object, stream=_UNSET_SENTINEL, indent=_UNSET_SENTINEL, width=_UNSET_SENTINEL, depth=_UNSET_SENTINEL, *, compact=False, ribbon_width=_UNSET_SENTINEL, max_seq_len=_UNSET_SENTINEL, sort_dict_keys=_UNSET_SENTINEL, end='\n'...
[ "Pretty print a Python value ``object`` to ``stream``,\n which defaults to ``sys.stdout``. The output will not be colored.\n\n :param indent: number of spaces to add for each level of nesting.\n :param stream: the output stream, defaults to ``sys.stdout``\n :param width: a soft maximum allowed number of...
Please provide a description of the function:def cpprint( object, stream=_UNSET_SENTINEL, indent=_UNSET_SENTINEL, width=_UNSET_SENTINEL, depth=_UNSET_SENTINEL, *, compact=False, ribbon_width=_UNSET_SENTINEL, max_seq_len=_UNSET_SENTINEL, sort_dict_keys=_UNSET_SENTINEL, style=N...
[ "Pretty print a Python value ``object`` to ``stream``,\n which defaults to sys.stdout. The output will be colored and\n syntax highlighted.\n\n :param indent: number of spaces to add for each level of nesting.\n :param stream: the output stream, defaults to sys.stdout\n :param width: a soft maximum a...
Please provide a description of the function:def install_extras( include=ALL_EXTRAS, *, exclude=EMPTY_SET, raise_on_error=False, warn_on_error=True ): # noqa include = set(include) exclude = set(exclude) unexisting_extras = (include | exclude) - ALL_EXTRAS if unexisting_extra...
[ "Installs extras.\n\n Installing an extra means registering pretty printers for objects from third\n party libraries and/or enabling integrations with other python programs.\n\n - ``'attrs'`` - automatically pretty prints classes created using the ``attrs`` package.\n - ``'dataclasses'`` - automatically...
Please provide a description of the function:def set_default_config( *, style=_UNSET_SENTINEL, max_seq_len=_UNSET_SENTINEL, width=_UNSET_SENTINEL, ribbon_width=_UNSET_SENTINEL, depth=_UNSET_SENTINEL, sort_dict_keys=_UNSET_SENTINEL ): global _default_config if style is not _UNSE...
[ "\n Sets the default configuration values used when calling\n `pprint`, `cpprint`, or `pformat`, if those values weren't\n explicitly provided. Only overrides the values provided in\n the keyword arguments.\n " ]
Please provide a description of the function:def pretty_repr(instance): instance_type = type(instance) if not is_registered( instance_type, check_superclasses=True, check_deferred=True, register_deferred=True ): warnings.warn( "pretty_repr is assigne...
[ "\n A function assignable to the ``__repr__`` dunder method, so that\n the ``prettyprinter`` definition for the type is used to provide\n repr output. Usage:\n\n .. code:: python\n\n from prettyprinter import pretty_repr\n\n class MyClass:\n __repr__ = pretty_repr\n\n " ]
Please provide a description of the function:def package_maven(): if not os.getenv('JAVA_HOME'): # make sure Maven uses the same JDK which we have used to compile # and link the C-code os.environ['JAVA_HOME'] = jdk_home_dir mvn_goal = 'package' log.info("Executing Maven goal '"...
[ " Run maven package lifecycle " ]
Please provide a description of the function:def _write_jpy_config(target_dir=None, install_dir=None): if not target_dir: target_dir = _build_dir() args = [sys.executable, os.path.join(target_dir, 'jpyutil.py'), '--jvm_dll', jvm_dll_file, '--java_home', jdk_...
[ "\n Write out a well-formed jpyconfig.properties file for easier Java\n integration in a given location.\n " ]
Please provide a description of the function:def _get_module_path(name, fail=False, install_path=None): import imp module = imp.find_module(name) if not module and fail: raise RuntimeError("can't find module '" + name + "'") path = module[1] if not path and fail: raise RuntimeE...
[ " Find the path to the jpy jni modules. " ]
Please provide a description of the function:def find_jdk_home_dir(): for name in JDK_HOME_VARS: jdk_home_dir = os.environ.get(name, None) if jdk_home_dir \ and os.path.exists(os.path.join(jdk_home_dir, 'include')) \ and os.path.exists(os.path.join(jdk_home_dir, ...
[ "\n Try to detect the JDK home directory from Maven, if available, or use\n dedicated environment variables.\n :return: pathname if found, else None\n " ]
Please provide a description of the function:def find_jvm_dll_file(java_home_dir=None, fail=False): logger.debug("Searching for JVM shared library file") if java_home_dir: jvm_dll_path = _find_jvm_dll_file(java_home_dir) if jvm_dll_path: return jvm_dll_path jvm_dll_path =...
[ "\n Try to detect the JVM's shared library file.\n :param java_home_dir: The Java JRE or JDK installation directory to be used for searching.\n :return: pathname if found, else None\n " ]
Please provide a description of the function:def init_jvm(java_home=None, jvm_dll=None, jvm_maxmem=None, jvm_classpath=None, jvm_properties=None, jvm_options=None, config_file=None, config=None): if not config: c...
[ "\n Creates a configured Java virtual machine which will be used by jpy.\n\n :param java_home: The Java JRE or JDK home directory used to search JVM shared library, if 'jvm_dll' is omitted.\n :param jvm_dll: The JVM shared library file. My be inferred from 'java_home'.\n :param jvm_maxmem: The JVM maxim...
Please provide a description of the function:def write_config_files(out_dir='.', java_home_dir=None, jvm_dll_file=None, install_dir=None, req_java_api_conf=True, req_py_api_conf=True): import date...
[ "\n Writes the jpy configuration files for Java and/or Python.\n\n :param out_dir: output directory, must exist\n :param java_home_dir: optional home directory of the Java JRE or JDK installation\n :param jvm_dll_file: optional file to JVM shared library file\n :param install_dir: optional path to wh...
Please provide a description of the function:def load(self, path): with open(path) as f: code = f.read() exec(code, {}, self.__dict__)
[ "\n Read Python file from 'path', execute it and return object that stores all variables of the\n Python code as attributes.\n :param path:\n :return:\n " ]
Please provide a description of the function:def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--lint', help='Path to the ADT lint tool. If not specified it assumes lint tool is in your path', default='lint') parser.add_argument('-...
[ "\n Parse command line arguments.\n " ]
Please provide a description of the function:def run_lint_command(): lint, app_dir, lint_result, ignore_layouts = parse_args() if not lint_result: if not distutils.spawn.find_executable(lint): raise Exception( '`%s` executable could not be found and path to lint result n...
[ "\n Run lint command in the shell and save results to lint-result.xml\n " ]
Please provide a description of the function:def parse_lint_result(lint_result_path, manifest_path): unused_string_pattern = re.compile('The resource `R\.string\.([^`]+)` appears to be unused') mainfest_string_refs = get_manifest_string_refs(manifest_path) root = etree.parse(lint_result_path).getroot()...
[ "\n Parse lint-result.xml and create Issue for every problem found except unused strings referenced in AndroidManifest\n " ]
Please provide a description of the function:def remove_resource_file(issue, filepath, ignore_layouts): if os.path.exists(filepath) and (ignore_layouts is False or issue.elements[0][0] != 'layout'): print('removing resource: {0}'.format(filepath)) os.remove(os.path.abspath(filepath))
[ "\n Delete a file from the filesystem\n " ]
Please provide a description of the function:def remove_resource_value(issue, filepath): if os.path.exists(filepath): for element in issue.elements: print('removing {0} from resource {1}'.format(element, filepath)) parser = etree.XMLParser(remove_blank_text=False, remove_comment...
[ "\n Read an xml file and remove an element which is unused, then save the file back to the filesystem\n " ]
Please provide a description of the function:def remove_unused_resources(issues, app_dir, ignore_layouts): for issue in issues: filepath = os.path.join(app_dir, issue.filepath) if issue.remove_file: remove_resource_file(issue, filepath, ignore_layouts) else: remo...
[ "\n Remove the file or the value inside the file depending if the whole file is unused or not.\n " ]
Please provide a description of the function:def _encryption_context_hash(hasher, encryption_context): serialized_encryption_context = serialize_encryption_context(encryption_context) hasher.update(serialized_encryption_context) return hasher.finalize()
[ "Generates the expected hash for the provided encryption context.\n\n :param hasher: Existing hasher to use\n :type hasher: cryptography.hazmat.primitives.hashes.Hash\n :param dict encryption_context: Encryption context to hash\n :returns: Complete hash\n :rtype: bytes\n " ]
Please provide a description of the function:def build_encryption_materials_cache_key(partition, request): if request.algorithm is None: _algorithm_info = b"\x00" else: _algorithm_info = b"\x01" + request.algorithm.id_as_bytes() hasher = _new_cache_key_hasher() _partition_hash = _p...
[ "Generates a cache key for an encrypt request.\n\n :param bytes partition: Partition name for which to generate key\n :param request: Request for which to generate key\n :type request: aws_encryption_sdk.materials_managers.EncryptionMaterialsRequest\n :returns: cache key\n :rtype: bytes\n " ]
Please provide a description of the function:def _encrypted_data_keys_hash(hasher, encrypted_data_keys): hashed_keys = [] for edk in encrypted_data_keys: serialized_edk = serialize_encrypted_data_key(edk) _hasher = hasher.copy() _hasher.update(serialized_edk) hashed_keys.app...
[ "Generates the expected hash for the provided encrypted data keys.\n\n :param hasher: Existing hasher to use\n :type hasher: cryptography.hazmat.primitives.hashes.Hash\n :param iterable encrypted_data_keys: Encrypted data keys to hash\n :returns: Concatenated, sorted, list of all hashes\n :rtype: byt...
Please provide a description of the function:def build_decryption_materials_cache_key(partition, request): hasher = _new_cache_key_hasher() _partition_hash = _partition_name_hash(hasher=hasher.copy(), partition_name=partition) _algorithm_info = request.algorithm.id_as_bytes() _edks_hash = _encrypte...
[ "Generates a cache key for a decrypt request.\n\n :param bytes partition: Partition name for which to generate key\n :param request: Request for which to generate key\n :type request: aws_encryption_sdk.materials_managers.DecryptionMaterialsRequest\n :returns: cache key\n :rtype: bytes\n " ]