{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef lock_key(key_name,\n stash,\n passphrase,\n backend):\n \"\"\"Lock a key to prevent it from being deleted, purged or modified\n\n `KEY_NAME` is the name of the key to lock\n \"\"\"\n stash = _get_stash(backend, stash, passphrase)\n\n try:\n click.echo('Locking key...')\n stash.lock(key_name=key_name)\n click.echo('Key locked successfully')\n except GhostError as ex:\n sys.exit(ex)", "response": "Lock a key in a stash"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef unlock_key(key_name,\n stash,\n passphrase,\n backend):\n \"\"\"Unlock a key to allow it to be modified, deleted or purged\n\n `KEY_NAME` is the name of the key to unlock\n \"\"\"\n stash = _get_stash(backend, stash, passphrase)\n\n try:\n click.echo('Unlocking key...')\n stash.unlock(key_name=key_name)\n click.echo('Key unlocked successfully')\n except GhostError as ex:\n sys.exit(ex)", "response": "Unlock a key in a stash"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nretrieve a key from the stash", "response": "def get_key(key_name,\n value_name,\n jsonify,\n no_decrypt,\n stash,\n passphrase,\n backend):\n \"\"\"Retrieve a key from the stash\n\n \\b\n `KEY_NAME` is the name of the key to retrieve\n `VALUE_NAME` is a single value to retrieve e.g. if the value\n of the key `test` is `a=b,b=c`, `ghost get test a`a will return\n `b`\n \"\"\"\n if value_name and no_decrypt:\n sys.exit('VALUE_NAME cannot be used in conjuction with --no-decrypt')\n\n stash = _get_stash(backend, stash, passphrase, quiet=jsonify or value_name)\n\n try:\n key = stash.get(key_name=key_name, decrypt=not no_decrypt)\n except GhostError as ex:\n sys.exit(ex)\n\n if not key:\n sys.exit('Key `{0}` not found'.format(key_name))\n if value_name:\n key = key['value'].get(value_name)\n if not key:\n sys.exit(\n 'Value name `{0}` could not be found under key `{1}`'.format(\n value_name, key_name))\n\n if jsonify or value_name:\n click.echo(\n json.dumps(key, indent=4, sort_keys=False).strip('\"'),\n nl=True)\n else:\n click.echo('Retrieving key...')\n click.echo('\\n' + _prettify_dict(key))"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef delete_key(key_name, stash, passphrase, backend):\n stash = _get_stash(backend, stash, passphrase)\n\n for key in key_name:\n try:\n click.echo('Deleting key {0}...'.format(key))\n stash.delete(key_name=key)\n except GhostError as ex:\n sys.exit(ex)\n click.echo('Keys deleted successfully')", "response": "Delete a key from the stash"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef list_keys(key_name,\n max_suggestions,\n cutoff,\n jsonify,\n locked,\n key_type,\n stash,\n passphrase,\n backend):\n \"\"\"List all keys in the stash\n\n If `KEY_NAME` is provided, will look for keys containing `KEY_NAME`.\n If `KEY_NAME` starts with `~`, close matches will be provided according\n to `max_suggestions` and `cutoff`.\n \"\"\"\n stash = _get_stash(backend, stash, passphrase, quiet=jsonify)\n\n try:\n keys = stash.list(\n key_name=key_name,\n max_suggestions=max_suggestions,\n cutoff=cutoff,\n locked_only=locked,\n key_type=key_type)\n except GhostError as ex:\n sys.exit(ex)\n if jsonify:\n click.echo(json.dumps(keys, indent=4, sort_keys=True))\n elif not keys:\n click.echo('The stash is empty. Go on, put some keys in there...')\n else:\n click.echo('Listing all keys...')\n click.echo(_prettify_list(keys))", "response": "List all keys in the stash."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef purge_stash(force, stash, passphrase, backend):\n stash = _get_stash(backend, stash, passphrase)\n\n try:\n click.echo('Purging stash...')\n stash.purge(force)\n # Maybe we should verify that the list is empty\n # afterwards?\n click.echo('Purge complete!')\n except GhostError as ex:\n sys.exit(ex)", "response": "Purge the stash from all of its keys\n "}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nexport all keys to a file", "response": "def export_keys(output_path, stash, passphrase, backend):\n \"\"\"Export all keys to a file\n \"\"\"\n stash = _get_stash(backend, stash, passphrase)\n\n try:\n click.echo('Exporting stash to {0}...'.format(output_path))\n stash.export(output_path=output_path)\n click.echo('Export complete!')\n except GhostError as ex:\n sys.exit(ex)"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef load_keys(key_file, origin_passphrase, stash, passphrase, backend):\n stash = _get_stash(backend, stash, passphrase)\n\n click.echo('Importing all keys from {0}...'.format(key_file))\n stash.load(origin_passphrase, key_file=key_file)\n click.echo('Import complete!')", "response": "Load all keys from an exported key file to the stash\n "}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nmigrate all keys from one stash to another.", "response": "def migrate_stash(source_stash_path,\n source_passphrase,\n source_backend,\n destination_stash_path,\n destination_passphrase,\n destination_backend):\n \"\"\"Migrate all keys from a source stash to a destination stash.\n\n `SOURCE_STASH_PATH` and `DESTINATION_STASH_PATH` are the paths\n to the stashs you wish to perform the migration on.\n \"\"\"\n click.echo('Migrating all keys from {0} to {1}...'.format(\n source_stash_path, destination_stash_path))\n\n try:\n migrate(\n src_path=source_stash_path,\n src_passphrase=source_passphrase,\n src_backend=source_backend,\n dst_path=destination_stash_path,\n dst_passphrase=destination_passphrase,\n dst_backend=destination_backend)\n except GhostError as ex:\n sys.exit(ex)\n click.echo('Migration complete!')"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef ssh(key_name, no_tunnel, stash, passphrase, backend):\n # TODO: find_executable or raise\n def execute(command):\n try:\n click.echo('Executing: {0}'.format(' '.join(command)))\n subprocess.check_call(' '.join(command), shell=True)\n except subprocess.CalledProcessError:\n sys.exit(1)\n\n stash = _get_stash(backend, stash, passphrase)\n key = stash.get(key_name)\n\n if key:\n _assert_is_ssh_type_key(key)\n else:\n sys.exit('Key `{0}` not found'.format(key_name))\n\n conn_info = key['value']\n ssh_key_path = conn_info.get('ssh_key_path')\n ssh_key = conn_info.get('ssh_key')\n proxy_key_path = conn_info.get('proxy_key_path')\n proxy_key = conn_info.get('proxy_key')\n\n id_file = _write_tmp(ssh_key) if ssh_key else ssh_key_path\n conn_info['ssh_key_path'] = id_file\n\n if conn_info.get('proxy'):\n proxy_id_file = _write_tmp(proxy_key) if proxy_key else proxy_key_path\n conn_info['proxy_key_path'] = proxy_id_file\n\n ssh_command = _build_ssh_command(conn_info, no_tunnel)\n try:\n execute(ssh_command)\n finally:\n # If they're not equal, that means we've created a temp one which\n # should be deleted, else, it's a path to an existing key file.\n if id_file != ssh_key_path:\n click.echo('Removing temp ssh key file: {0}...'.format(id_file))\n os.remove(id_file)\n if conn_info.get('proxy') and proxy_id_file != proxy_key_path:\n click.echo('Removing temp proxy key file: {0}...'.format(\n proxy_id_file))\n os.remove(proxy_id_file)", "response": "Use an ssh type key to connect to a machine via ssh."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nbuilding the SSH command to connect to the server.", "response": "def _build_ssh_command(conn_info, no_tunnel=False):\n \"\"\"\n # TODO: Document clearly\n IndetityFile=\"~/.ssh/id_rsa\"\n ProxyCommand=\"ssh -i ~/.ssh/id_rsa proxy_IP nc HOST_IP HOST_PORT\"\n \"\"\"\n command = ['ssh', '-i', conn_info['ssh_key_path'], conn_info['conn']]\n\n if conn_info.get('tunnel') and not no_tunnel:\n command.insert(1, conn_info.get('tunnel'))\n # Tunnel\n command.insert(1, '-L')\n # No shell\n command.insert(1, '-N')\n if conn_info.get('proxy'):\n command.extend(_build_proxy_command(conn_info))\n if conn_info.get('extend'):\n command.append(conn_info.get('extend'))\n return command"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef put(self,\n name,\n value=None,\n modify=False,\n metadata=None,\n description='',\n encrypt=True,\n lock=False,\n key_type='secret',\n add=False):\n \"\"\"Put a key inside the stash\n\n if key exists and modify true: delete and create\n if key exists and modify false: fail\n if key doesn't exist and modify true: fail\n if key doesn't exist and modify false: create\n\n `name` is unique and cannot be changed.\n\n `value` must be provided if the key didn't already exist, otherwise,\n the previous value will be retained.\n\n `created_at` will be left unmodified if the key\n already existed. Otherwise, the current time will be used.\n\n `modified_at` will be changed to the current time\n if the field is being modified.\n\n `metadata` will be updated if provided. If it wasn't\n provided the field from the existing key will be used and the\n same goes for the `uid` which will be generated if it didn't\n previously exist.\n\n `lock` will lock the key to prevent it from being modified or deleted\n\n `add` allows to add values to an existing key instead of overwriting.\n\n Returns the id of the key in the database\n \"\"\"\n def assert_key_is_unlocked(existing_key):\n if existing_key and existing_key.get('lock'):\n raise GhostError(\n 'Key `{0}` is locked and therefore cannot be modified. '\n 'Unlock the key and try again'.format(name))\n\n def assert_value_provided_for_new_key(value, existing_key):\n if not value and not existing_key.get('value'):\n raise GhostError('You must provide a value for new keys')\n\n self._assert_valid_stash()\n self._validate_key_schema(value, key_type)\n if value and encrypt and not isinstance(value, dict):\n raise GhostError('Value must be of type dict')\n\n # TODO: This should be refactored. `_handle_existing_key` deletes\n # the key rather implicitly. It shouldn't do that.\n # `existing_key` will be an empty dict if it doesn't exist\n key = self._handle_existing_key(name, modify or add)\n assert_key_is_unlocked(key)\n assert_value_provided_for_new_key(value, key)\n\n new_key = dict(name=name, lock=lock)\n if value:\n # TODO: fix edge case in which encrypt is false and yet we might\n # try to add to an existing key. encrypt=false is only used when\n # `load`ing into a new stash, but someone might use it directly\n # from the API.\n if add:\n value = self._update_existing_key(key, value)\n new_key['value'] = self._encrypt(value) if encrypt else value\n else:\n new_key['value'] = key.get('value')\n\n # TODO: Treat a case in which we try to update an existing key\n # but don't provide a value in which nothing will happen.\n new_key['description'] = description or key.get('description')\n new_key['created_at'] = key.get('created_at') or _get_current_time()\n new_key['modified_at'] = _get_current_time()\n new_key['metadata'] = metadata or key.get('metadata')\n new_key['uid'] = key.get('uid') or str(uuid.uuid4())\n new_key['type'] = key.get('type') or key_type\n\n key_id = self._storage.put(new_key)\n\n audit(\n storage=self._storage.db_path,\n action='MODIFY' if (modify or add) else 'PUT',\n message=json.dumps(dict(\n key_name=new_key['name'],\n value='HIDDEN',\n description=new_key['description'],\n uid=new_key['uid'],\n metadata=json.dumps(new_key['metadata']),\n lock=new_key['lock'],\n type=new_key['type'])))\n\n return key_id", "response": "Put a key in the database."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef get(self, key_name, decrypt=True):\n self._assert_valid_stash()\n\n key = self._storage.get(key_name).copy()\n if not key.get('value'):\n return None\n if decrypt:\n key['value'] = self._decrypt(key['value'])\n\n audit(\n storage=self._storage.db_path,\n action='GET',\n message=json.dumps(dict(key_name=key_name)))\n\n return key", "response": "Return a key with its parameters if it was found."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nreturns a list of all keys.", "response": "def list(self,\n key_name=None,\n max_suggestions=100,\n cutoff=0.5,\n locked_only=False,\n key_type=None):\n \"\"\"Return a list of all keys.\n \"\"\"\n self._assert_valid_stash()\n\n key_list = [k for k in self._storage.list()\n if k['name'] != 'stored_passphrase' and\n (k.get('lock') if locked_only else True)]\n\n if key_type:\n # To maintain backward compatibility with keys without a type.\n # The default key type is secret, in which case we also look for\n # keys with no (None) types.\n types = ('secret', None) if key_type == 'secret' else [key_type]\n key_list = [k for k in key_list if k.get('type') in types]\n\n key_list = [k['name'] for k in key_list]\n if key_name:\n if key_name.startswith('~'):\n key_list = difflib.get_close_matches(\n key_name.lstrip('~'), key_list, max_suggestions, cutoff)\n else:\n key_list = [k for k in key_list if key_name in k]\n\n audit(\n storage=self._storage.db_path,\n action='LIST' + ('[LOCKED]' if locked_only else ''),\n message=json.dumps(dict()))\n\n return key_list"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ndeletes a key from the storage.", "response": "def delete(self, key_name):\n \"\"\"Delete a key if it exists.\n \"\"\"\n self._assert_valid_stash()\n\n if key_name == 'stored_passphrase':\n raise GhostError(\n '`stored_passphrase` is a reserved ghost key name '\n 'which cannot be deleted')\n\n # TODO: Optimize. We get from the storage twice here for no reason\n if not self.get(key_name):\n raise GhostError('Key `{0}` not found'.format(key_name))\n key = self._storage.get(key_name)\n if key.get('lock'):\n raise GhostError(\n 'Key `{0}` is locked and therefore cannot be deleted '\n 'Please unlock the key and try again'.format(key_name))\n\n deleted = self._storage.delete(key_name)\n\n audit(\n storage=self._storage.db_path,\n action='DELETE',\n message=json.dumps(dict(key_name=key_name)))\n\n if not deleted:\n raise GhostError('Failed to delete {0}'.format(key_name))"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\npurges the stash from all keys", "response": "def purge(self, force=False, key_type=None):\n \"\"\"Purge the stash from all keys\n \"\"\"\n self._assert_valid_stash()\n\n if not force:\n raise GhostError(\n \"The `force` flag must be provided to perform a stash purge. \"\n \"I mean, you don't really want to just delete everything \"\n \"without precautionary measures eh?\")\n\n audit(\n storage=self._storage.db_path,\n action='PURGE',\n message=json.dumps(dict()))\n\n for key_name in self.list(key_type=key_type):\n self.delete(key_name)"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef export(self, output_path=None, decrypt=False):\n self._assert_valid_stash()\n\n all_keys = []\n for key in self.list():\n # We `dict` this as a precaution as tinydb returns\n # a tinydb.database.Element instead of a dictionary\n # and well.. I ain't taking no chances\n all_keys.append(dict(self.get(key, decrypt=decrypt)))\n if all_keys:\n if output_path:\n with open(output_path, 'w') as output_file:\n output_file.write(json.dumps(all_keys, indent=4))\n return all_keys\n else:\n raise GhostError('There are no keys to export')", "response": "Export all keys in the stash to a list or a file"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef load(self, origin_passphrase, keys=None, key_file=None):\n # TODO: Handle keys not dict or key_file not json\n self._assert_valid_stash()\n\n # Check if both or none are provided (ahh, the mighty xor)\n if not (bool(keys) ^ bool(key_file)):\n raise GhostError(\n 'You must either provide a path to an exported stash file '\n 'or a list of key dicts to import')\n if key_file:\n with open(key_file) as stash_file:\n keys = json.loads(stash_file.read())\n\n # If the passphrases are the same, there's no reason to decrypt\n # and re-encrypt. We can simply pass the value.\n decrypt = origin_passphrase != self.passphrase\n if decrypt:\n # TODO: The fact that we need to create a stub stash just to\n # decrypt means we should probably have some encryptor class.\n stub = Stash(TinyDBStorage('stub'), origin_passphrase)\n # TODO: Handle existing keys when loading\n for key in keys:\n self.put(\n name=key['name'],\n value=stub._decrypt(key['value']) if decrypt else key['value'],\n metadata=key['metadata'],\n description=key['description'],\n lock=key.get('lock'),\n key_type=key.get('type'),\n encrypt=decrypt)", "response": "Load the keys from a file or a list of keys."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nturns a json serializable value into an encrypted hexa string.", "response": "def _encrypt(self, value):\n \"\"\"Turn a json serializable value into an jsonified, encrypted,\n hexa string.\n \"\"\"\n value = json.dumps(value)\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n encrypted_value = self.cipher.encrypt(value.encode('utf8'))\n hexified_value = binascii.hexlify(encrypted_value).decode('ascii')\n return hexified_value"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nreturn a dictionary consisting of the key itself", "response": "def get(self, key_name):\n \"\"\"Return a dictionary consisting of the key itself\n\n e.g.\n {u'created_at': u'2016-10-10 08:31:53',\n u'description': None,\n u'metadata': None,\n u'modified_at': u'2016-10-10 08:31:53',\n u'name': u'aws',\n u'uid': u'459f12c0-f341-413e-9d7e-7410f912fb74',\n u'value': u'the_value'}\n\n \"\"\"\n result = self.db.search(Query().name == key_name)\n if not result:\n return {}\n return result[0]"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef delete(self, key_name):\n self.db.remove(Query().name == key_name)\n return self.get(key_name) == {}", "response": "Delete the key and return true if the key was deleted otherwise false"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _construct_key(self, values):\n key = {}\n for column, value in zip(self.keys.columns, values):\n key.update({column.name: value})\n return key", "response": "Construct a key from a list of columns\n and a tuple of values\n "}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef put(self, key):\n self._consul_request('PUT', self._key_url(key['name']), json=key)\n return key['name']", "response": "Put and return the only unique identifier possible"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef put(self, key):\n self.client.write(self._key_path(key['name']), **key)\n return self._key_path(key['name'])", "response": "Put and return the only unique identifier possible"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\ncreate an Elasticsearch index if necessary", "response": "def init(self):\n \"\"\"Create an Elasticsearch index if necessary\n \"\"\"\n # ignore 400 (IndexAlreadyExistsException) when creating an index\n self.es.indices.create(index=self.params['index'], ignore=400)"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef init(self):\n try:\n self.client.create_bucket(\n Bucket=self.db_path,\n CreateBucketConfiguration=self.bucket_configuration)\n except botocore.exceptions.ClientError as e:\n # If the bucket already exists\n if 'BucketAlreadyOwnedByYou' not in str(\n e.response['Error']['Code']):\n raise e", "response": "Create a new bucket."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ninserting the key into the database.", "response": "def put(self, key):\n \"\"\"Insert the key\n :return: Key name\n \"\"\"\n self.client.put_object(\n Body=json.dumps(key),\n Bucket=self.db_path,\n Key=key['name'])\n return key['name']"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef list(self):\n response = self.client.list_objects_v2(Bucket=self.db_path)\n if u'Contents' in response:\n # Filter out everything but the key names\n keys = [key[u'Key'] for key in response[u'Contents']]\n keys_list = []\n\n for key_name in keys:\n key = self.get(key_name)\n keys_list.append(key)\n\n return keys_list\n return []", "response": "Lists the keys\n :return: Returns a list of all keys (not just key names, but rather\n the keys themselves)."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ngetting the key itself in a dictionary.", "response": "def get(self, key_name):\n \"\"\"Gets the key.\n :return: The key itself in a dictionary\n \"\"\"\n try:\n obj = self.client.get_object(\n Bucket=self.db_path,\n Key=key_name)['Body'].read().decode(\"utf-8\")\n\n return json.loads(obj)\n except botocore.exceptions.ClientError as e:\n if 'NoSuchKey' in str(e.response['Error']['Code']):\n return {}\n raise e"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ndeletes the object with the given key name.", "response": "def delete(self, key_name):\n \"\"\"Delete the key.\n :return: True if it was deleted, False otherwise\n \"\"\"\n self.client.delete_object(\n Bucket=self.db_path,\n Key=key_name)\n\n return self.get(key_name) == {}"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef is_initialized(self):\n try:\n return self.client.head_bucket(\n Bucket=self.db_path)['ResponseMetadata']['HTTPStatusCode'] \\\n == 200\n except botocore.exceptions.ClientError as e:\n # If a client error is thrown, then check that it was a 404 error.\n # If it was a 404 error, then the bucket does not exist.\n if 'NoSuchBucket' in str(e.response['Error']['Code']):\n return False\n raise e", "response": "Check if the resource in the database is initialized."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef terminal(port=default_port(), baud='9600'):\n testargs = ['nodemcu-uploader', port, baud]\n # TODO: modifying argv is no good\n sys.argv = testargs\n # resuse miniterm on main function\n miniterm.main()", "response": "Launch minterm from pyserial"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef __set_baudrate(self, baud):\n log.info('Changing communication to %s baud', baud)\n self.__writeln(UART_SETUP.format(baud=baud))\n # Wait for the string to be sent before switching baud\n time.sleep(0.1)\n try:\n self._port.setBaudrate(baud)\n except AttributeError:\n #pySerial 2.7\n self._port.baudrate = baud", "response": "set baudrate of the serial port"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef set_timeout(self, timeout):\n timeout = int(timeout) # will raise on Error\n self._timeout = timeout == 0 and 999999 or timeout", "response": "Set the timeout for the communication with the device."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef __clear_buffers(self):\n try:\n self._port.reset_input_buffer()\n self._port.reset_output_buffer()\n except AttributeError:\n #pySerial 2.7\n self._port.flushInput()\n self._port.flushOutput()", "response": "Clears the input and output buffers"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef __expect(self, exp='> ', timeout=None):\n timeout_before = self._port.timeout\n timeout = timeout or self._timeout\n #do NOT set timeout on Windows\n if SYSTEM != 'Windows':\n # Checking for new data every 100us is fast enough\n if self._port.timeout != MINIMAL_TIMEOUT:\n self._port.timeout = MINIMAL_TIMEOUT\n\n end = time.time() + timeout\n\n # Finish as soon as either exp matches or we run out of time (work like dump, but faster on success)\n data = ''\n while not data.endswith(exp) and time.time() <= end:\n data += self._port.read()\n\n log.debug('expect returned: `{0}`'.format(data))\n if time.time() > end:\n raise CommunicationTimeout('Timeout waiting for data', data)\n\n if not data.endswith(exp) and len(exp) > 0:\n raise BadResponseException('Bad response.', exp, data)\n\n if SYSTEM != 'Windows':\n self._port.timeout = timeout_before\n\n return data", "response": "expect a response from nodemcu or timeout"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef __write(self, output, binary=False):\n if not binary:\n log.debug('write: %s', output)\n else:\n log.debug('write binary: %s', hexify(output))\n self._port.write(output)\n self._port.flush()", "response": "write data on the nodemcu port."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef __exchange(self, output, timeout=None):\n self.__writeln(output)\n self._port.flush()\n return self.__expect(timeout=timeout or self._timeout)", "response": "Write output to the port and wait for response"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef close(self):\n try:\n if self.baud != self.start_baud:\n self.__set_baudrate(self.start_baud)\n self._port.flush()\n self.__clear_buffers()\n except serial.serialutil.SerialException:\n pass\n log.debug('closing port')\n self._port.close()", "response": "restores the nodemcu baudrate and then closes the port"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef prepare(self):\n log.info('Preparing esp for transfer.')\n\n for func in LUA_FUNCTIONS:\n detected = self.__exchange('print({0})'.format(func))\n if detected.find('function:') == -1:\n break\n else:\n log.info('Preparation already done. Not adding functions again.')\n return True\n functions = RECV_LUA + '\\n' + SEND_LUA\n data = functions.format(baud=self._port.baudrate)\n ##change any \\r\\n to just \\n and split on that\n lines = data.replace('\\r', '').split('\\n')\n\n #remove some unneccesary spaces to conserve some bytes\n for line in lines:\n line = line.strip().replace(', ', ',').replace(' = ', '=')\n\n if len(line) == 0:\n continue\n\n resp = self.__exchange(line)\n #do some basic test of the result\n if ('unexpected' in resp) or ('stdin' in resp) or len(resp) > len(functions)+10:\n log.error('error when preparing \"%s\"', resp)\n return False\n return True", "response": "This method uploads the protocol functions nessecary to do binary transfer and returns True if successful False otherwise."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef download_file(self, filename):\n res = self.__exchange('send(\"{filename}\")'.format(filename=filename))\n if ('unexpected' in res) or ('stdin' in res):\n log.error('Unexpected error downloading file: %s', res)\n raise Exception('Unexpected error downloading file')\n\n #tell device we are ready to receive\n self.__write('C')\n #we should get a NUL terminated filename to start with\n sent_filename = self.__expect(NUL).strip()\n log.info('receiveing ' + sent_filename)\n\n #ACK to start download\n self.__write(ACK, True)\n buf = ''\n\n data = ''\n chunk, buf = self.__read_chunk(buf)\n #read chunks until we get an empty which is the end\n while chunk != '':\n self.__write(ACK, True)\n data = data + chunk\n chunk, buf = self.__read_chunk(buf)\n return data", "response": "Download a file from device to local filesystem"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef read_file(self, filename, destination=''):\n if not destination:\n destination = filename\n log.info('Transferring %s to %s', filename, destination)\n data = self.download_file(filename)\n\n # Just in case, the filename may contain folder, so create it if needed.\n log.info(destination)\n if not os.path.exists(os.path.dirname(destination)):\n try:\n os.makedirs(os.path.dirname(destination))\n except OSError as e: # Guard against race condition\n if e.errno != errno.EEXIST:\n raise\n with open(destination, 'w') as fil:\n fil.write(data)", "response": "read a file from the device into a local file"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nsend a file to the device using the transfer protocol", "response": "def write_file(self, path, destination='', verify='none'):\n \"\"\"sends a file to the device using the transfer protocol\"\"\"\n filename = os.path.basename(path)\n if not destination:\n destination = filename\n\n log.info('Transferring %s as %s', path, destination)\n self.__writeln(\"recv()\")\n\n res = self.__expect('C> ')\n if not res.endswith('C> '):\n log.error('Error waiting for esp \"%s\"', res)\n raise CommunicationTimeout('Error waiting for device to start receiving', res)\n\n log.debug('sending destination filename \"%s\"', destination)\n self.__write(destination + '\\x00', True)\n if not self.__got_ack():\n log.error('did not ack destination filename')\n raise NoAckException('Device did not ACK destination filename')\n\n content = from_file(path)\n\n log.debug('sending %d bytes in %s', len(content), filename)\n pos = 0\n chunk_size = 128\n while pos < len(content):\n rest = len(content) - pos\n if rest > chunk_size:\n rest = chunk_size\n\n data = content[pos:pos+rest]\n if not self.__write_chunk(data):\n resp = self.__expect()\n log.error('Bad chunk response \"%s\" %s', resp, hexify(resp))\n raise BadResponseException('Bad chunk response', ACK, resp)\n\n pos += chunk_size\n\n log.debug('sending zero block')\n #zero size block\n self.__write_chunk('')\n if verify != 'none':\n self.verify_file(path, destination, verify)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef verify_file(self, path, destination, verify='none'):\n content = from_file(path)\n log.info('Verifying using %s...' % verify)\n if verify == 'raw':\n\n data = self.download_file(destination)\n if content != data:\n log.error('Raw verification failed.')\n raise VerificationError('Verification failed.')\n else:\n log.info('Verification successful. Contents are identical.')\n elif verify == 'sha1':\n #Calculate SHA1 on remote file. Extract just hash from result\n data = self.__exchange('shafile(\"'+destination+'\")').splitlines()[1]\n log.info('Remote SHA1: %s', data)\n\n #Calculate hash of local data\n filehashhex = hashlib.sha1(content.encode(ENCODING)).hexdigest()\n log.info('Local SHA1: %s', filehashhex)\n if data != filehashhex:\n log.error('SHA1 verification failed.')\n raise VerificationError('SHA1 Verification failed.')\n else:\n log.info('Verification successful. Checksums match')\n\n elif verify != 'none':\n raise Exception(verify + ' is not a valid verification method.')", "response": "Tries to verify if path has same checksum as destination."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef exec_file(self, path):\n filename = os.path.basename(path)\n log.info('Execute %s', filename)\n\n content = from_file(path).replace('\\r', '').split('\\n')\n\n res = '> '\n for line in content:\n line = line.rstrip('\\n')\n retlines = (res + self.__exchange(line)).splitlines()\n # Log all but the last line\n res = retlines.pop()\n for lin in retlines:\n log.info(lin)\n # last line\n log.info(res)", "response": "execute the lines in the local file path"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nreturn true if ACK is received", "response": "def __got_ack(self):\n \"\"\"Returns true if ACK is received\"\"\"\n log.debug('waiting for ack')\n res = self._port.read(1)\n log.debug('ack read %s', hexify(res))\n return res == ACK"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nwriting lines one by one separated by \\ n to device", "response": "def write_lines(self, data):\n \"\"\"write lines, one by one, separated by \\n to device\"\"\"\n lines = data.replace('\\r', '').split('\\n')\n for line in lines:\n self.__exchange(line)"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef __write_chunk(self, chunk):\n log.debug('writing %d bytes chunk', len(chunk))\n data = BLOCK_START + chr(len(chunk)) + chunk\n if len(chunk) < 128:\n padding = 128 - len(chunk)\n log.debug('pad with %d characters', padding)\n data = data + (' ' * padding)\n log.debug(\"packet size %d\", len(data))\n self.__write(data)\n self._port.flush()\n return self.__got_ack()", "response": "formats and sends a chunk of data to the device according\n to transfer protocol"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nread a chunk of data from the port.", "response": "def __read_chunk(self, buf):\n \"\"\"Read a chunk of data\"\"\"\n log.debug('reading chunk')\n timeout_before = self._port.timeout\n if SYSTEM != 'Windows':\n # Checking for new data every 100us is fast enough\n if self._port.timeout != MINIMAL_TIMEOUT:\n self._port.timeout = MINIMAL_TIMEOUT\n\n end = time.time() + timeout_before\n\n while len(buf) < 130 and time.time() <= end:\n buf = buf + self._port.read()\n\n if buf[0] != BLOCK_START or len(buf) < 130:\n log.debug('buffer binary: %s ', hexify(buf))\n raise Exception('Bad blocksize or start byte')\n\n if SYSTEM != 'Windows':\n self._port.timeout = timeout_before\n\n chunk_size = ord(buf[1])\n data = buf[2:chunk_size+2]\n buf = buf[130:]\n return (data, buf)"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nlists files on the device", "response": "def file_list(self):\n \"\"\"list files on the device\"\"\"\n log.info('Listing files')\n res = self.__exchange(LIST_FILES)\n res = res.split('\\r\\n')\n # skip first and last lines\n res = res[1:-1]\n files = []\n for line in res:\n files.append(line.split('\\t'))\n return files"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef file_do(self, filename):\n log.info('Executing '+filename)\n res = self.__exchange('dofile(\"'+filename+'\")')\n log.info(res)\n return res", "response": "Execute a file on the device using dofile"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nprint a file on the device to the console", "response": "def file_print(self, filename):\n \"\"\"Prints a file on the device to console\"\"\"\n log.info('Printing ' + filename)\n res = self.__exchange(PRINT_FILE.format(filename=filename))\n log.info(res)\n return res"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef node_heap(self):\n log.info('Heap')\n res = self.__exchange('print(node.heap())')\n log.info(res)\n return int(res.split('\\r\\n')[1])", "response": "Show device heap size"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\ncompile a file specified by path on the device", "response": "def file_compile(self, path):\n \"\"\"Compiles a file specified by path on the device\"\"\"\n log.info('Compile '+path)\n cmd = 'node.compile(\"%s\")' % path\n res = self.__exchange(cmd)\n log.info(res)\n return res"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef file_remove(self, path):\n log.info('Remove '+path)\n cmd = 'file.remove(\"%s\")' % path\n res = self.__exchange(cmd)\n log.info(res)\n return res", "response": "Removes a file on the device"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreturns a list of sources and destinations from a source file.", "response": "def destination_from_source(sources, use_glob=True):\n \"\"\"\n Split each of the sources in the array on ':'\n First part will be source, second will be destination.\n Modifies the the original array to contain only sources\n and returns an array of destinations.\n \"\"\"\n destinations = []\n newsources = []\n for i in range(0, len(sources)):\n srcdst = sources[i].split(':')\n if len(srcdst) == 2:\n destinations.append(srcdst[1])\n newsources.append(srcdst[0]) #proper list assignment\n else:\n if use_glob:\n listing = glob.glob(srcdst[0])\n for filename in listing:\n newsources.append(filename)\n #always use forward slash at destination\n destinations.append(filename.replace('\\\\', '/'))\n else:\n newsources.append(srcdst[0])\n destinations.append(srcdst[0])\n\n return [newsources, destinations]"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nlisting files on target", "response": "def operation_list(uploader):\n \"\"\"List file on target\"\"\"\n files = uploader.file_list()\n for f in files:\n log.info(\"{file:30s} {size}\".format(file=f[0], size=f[1]))"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef main_func():\n parser = argparse.ArgumentParser(\n description='NodeMCU Lua file uploader',\n prog='nodemcu-uploader'\n )\n\n parser.add_argument(\n '--verbose',\n help='verbose output',\n action='store_true',\n default=False)\n\n parser.add_argument(\n '--version',\n help='prints the version and exists',\n action='version',\n version='%(prog)s {version} (serial {serialversion})'.format(version=__version__, serialversion=serialversion)\n )\n\n parser.add_argument(\n '--port', '-p',\n help='Serial port device',\n default=Uploader.PORT)\n\n parser.add_argument(\n '--baud', '-b',\n help='Serial port baudrate',\n type=arg_auto_int,\n default=Uploader.BAUD)\n\n parser.add_argument(\n '--start_baud', '-B',\n help='Initial Serial port baudrate',\n type=arg_auto_int,\n default=Uploader.START_BAUD)\n\n parser.add_argument(\n '--timeout', '-t',\n help='Timeout for operations',\n type=arg_auto_int,\n default=Uploader.TIMEOUT)\n\n parser.add_argument(\n '--autobaud_time', '-a',\n help='Duration of the autobaud timer',\n type=float,\n default=Uploader.AUTOBAUD_TIME,\n )\n\n subparsers = parser.add_subparsers(\n dest='operation',\n help='Run nodemcu-uploader {command} -h for additional help')\n\n backup_parser = subparsers.add_parser(\n 'backup',\n help='Backup all the files on the nodemcu board')\n backup_parser.add_argument('path', help='Folder where to store the backup')\n\n\n upload_parser = subparsers.add_parser(\n 'upload',\n help='Path to one or more files to be uploaded. Destination name will be the same as the file name.')\n\n upload_parser.add_argument(\n 'filename',\n nargs='+',\n help='Lua file to upload. Use colon to give alternate destination.'\n )\n\n upload_parser.add_argument(\n '--compile', '-c',\n help='If file should be uploaded as compiled',\n action='store_true',\n default=False\n )\n\n upload_parser.add_argument(\n '--verify', '-v',\n help='To verify the uploaded data.',\n action='store',\n nargs='?',\n choices=['none', 'raw', 'sha1'],\n default='none'\n )\n\n upload_parser.add_argument(\n '--dofile', '-e',\n help='If file should be run after upload.',\n action='store_true',\n default=False\n )\n\n upload_parser.add_argument(\n '--restart', '-r',\n help='If esp should be restarted',\n action='store_true',\n default=False\n )\n\n exec_parser = subparsers.add_parser(\n 'exec',\n help='Path to one or more files to be executed line by line.')\n\n exec_parser.add_argument('filename', nargs='+', help='Lua file to execute.')\n\n download_parser = subparsers.add_parser(\n 'download',\n help='Path to one or more files to be downloaded. Destination name will be the same as the file name.')\n\n download_parser.add_argument('filename',\n nargs='+',\n help='Lua file to download. Use colon to give alternate destination.')\n\n\n file_parser = subparsers.add_parser(\n 'file',\n help='File functions')\n\n file_parser.add_argument(\n 'cmd',\n choices=('list', 'do', 'format', 'remove', 'print'),\n help=\"list=list files, do=dofile given path, format=formate file area, remove=remove given path\")\n\n file_parser.add_argument('filename', nargs='*', help='path for cmd')\n\n node_parse = subparsers.add_parser(\n 'node',\n help='Node functions')\n\n node_parse.add_argument('ncmd', choices=('heap', 'restart'), help=\"heap=print heap memory, restart=restart nodemcu\")\n\n subparsers.add_parser(\n 'terminal',\n help='Run pySerials miniterm'\n )\n\n args = parser.parse_args()\n\n default_level = logging.INFO\n if args.verbose:\n default_level = logging.DEBUG\n\n #formatter = logging.Formatter('%(message)s')\n\n logging.basicConfig(level=default_level, format='%(message)s')\n\n if args.operation == 'terminal':\n #uploader can not claim the port\n terminal(args.port, str(args.start_baud))\n return\n\n # let uploader user the default (short) timeout for establishing connection\n uploader = Uploader(args.port, args.baud, start_baud=args.start_baud, autobaud_time=args.autobaud_time)\n\n # and reset the timeout (if we have the uploader&timeout)\n if args.timeout:\n uploader.set_timeout(args.timeout)\n\n if args.operation == 'upload':\n operation_upload(uploader, args.filename, args.verify, args.compile, args.dofile,\n args.restart)\n\n elif args.operation == 'download':\n operation_download(uploader, args.filename)\n\n elif args.operation == 'exec':\n sources = args.filename\n for path in sources:\n uploader.exec_file(path)\n\n elif args.operation == 'file':\n operation_file(uploader, args.cmd, args.filename)\n\n elif args.operation == 'node':\n if args.ncmd == 'heap':\n uploader.node_heap()\n elif args.ncmd == 'restart':\n uploader.node_restart()\n\n elif args.operation == 'backup':\n uploader.backup(args.path)\n\n #no uploader related commands after this point\n uploader.close()", "response": "Main function for CLI"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\ndisplay a GenePattern Python Library content in a notebook without the need to import IPython at the top level.", "response": "def display(content):\n \"\"\"\n Display a widget, text or other media in a notebook without the need to import IPython at the top level.\n\n Also handles wrapping GenePattern Python Library content in widgets.\n :param content:\n :return:\n \"\"\"\n if isinstance(content, gp.GPServer):\n IPython.display.display(GPAuthWidget(content))\n elif isinstance(content, gp.GPTask):\n IPython.display.display(GPTaskWidget(content))\n elif isinstance(content, gp.GPJob):\n IPython.display.display(GPJobWidget(content))\n else:\n IPython.display.display(content)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef register(self, server, username, password):\n\n # Create the session\n session = gp.GPServer(server, username, password)\n\n # Validate username if not empty\n valid_username = username != \"\" and username is not None\n\n # Validate that the server is not already registered\n index = self._get_index(server)\n new_server = index == -1\n\n # Add the new session to the list\n if valid_username and new_server:\n self.sessions.append(session)\n\n # Replace old session is one exists\n if valid_username and not new_server:\n self.sessions[index] = session\n\n return session", "response": "Register a new GenePattern server session for the provided username and password. Return the newly created session."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef get(self, server):\n\n # Handle indexes\n if isinstance(server, int):\n if server >= len(self.sessions):\n return None\n else:\n return self.sessions[server]\n\n # Handle server URLs\n index = self._get_index(server)\n if index == -1:\n return None\n else:\n return self.sessions[index]", "response": "Returns a registered GPServer object with a matching GenePattern server url or index\n "}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _get_index(self, server_url):\n for i in range(len(self.sessions)):\n session = self.sessions[i]\n if session.url == server_url:\n return i\n return -1", "response": "Returns a registered GPServer object with a matching GenePattern server url"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\naccepting None or \u221e or datetime or numeric for target", "response": "def _accept(self, target):\n\t\t\"Accept None or \u221e or datetime or numeric for target\"\n\t\tif isinstance(target, datetime.timedelta):\n\t\t\ttarget = target.total_seconds()\n\n\t\tif target is None:\n\t\t\t# treat None as infinite target\n\t\t\ttarget = float('Inf')\n\n\t\treturn target"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nconverts a numeric timestamp to a timezone - aware datetime.", "response": "def from_timestamp(ts):\n \"\"\"\n Convert a numeric timestamp to a timezone-aware datetime.\n\n A client may override this function to change the default behavior,\n such as to use local time or timezone-na\u00efve times.\n \"\"\"\n return datetime.datetime.utcfromtimestamp(ts).replace(tzinfo=pytz.utc)"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nconstruct a DelayedCommand to come due at time.", "response": "def at_time(cls, at, target):\n \"\"\"\n Construct a DelayedCommand to come due at `at`, where `at` may be\n a datetime or timestamp.\n \"\"\"\n at = cls._from_timestamp(at)\n cmd = cls.from_datetime(at)\n cmd.delay = at - now()\n cmd.target = target\n return cmd"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nrely on pytz. localize to ensure new result honors DST.", "response": "def _localize(dt):\n \"\"\"\n Rely on pytz.localize to ensure new result honors DST.\n \"\"\"\n try:\n tz = dt.tzinfo\n return tz.localize(dt.replace(tzinfo=None))\n except AttributeError:\n return dt"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nschedule a command to run at a specific time each day.", "response": "def daily_at(cls, at, target):\n \"\"\"\n Schedule a command to run at a specific time each day.\n \"\"\"\n daily = datetime.timedelta(days=1)\n # convert when to the next datetime matching this time\n when = datetime.datetime.combine(datetime.date.today(), at)\n if when < now():\n when += daily\n return cls.at_time(cls._localize(when), daily, target)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef strptime(s, fmt, tzinfo=None):\n\tres = time.strptime(s, fmt)\n\treturn datetime.datetime(tzinfo=tzinfo, *res[:6])", "response": "A function to replace strptime in the time module."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef datetime_mod(dt, period, start=None):\n\tif start is None:\n\t\t# use midnight of the same day\n\t\tstart = datetime.datetime.combine(dt.date(), datetime.time())\n\t# calculate the difference between the specified time and the start date.\n\tdelta = dt - start\n\n\t# now aggregate the delta and the period into microseconds\n\t# Use microseconds because that's the highest precision of these time\n\t# pieces. Also, using microseconds ensures perfect precision (no floating\n\t# point errors).\n\tdef get_time_delta_microseconds(td):\n\t\treturn (td.days * seconds_per_day + td.seconds) * 1000000 + td.microseconds\n\tdelta, period = map(get_time_delta_microseconds, (delta, period))\n\toffset = datetime.timedelta(microseconds=delta % period)\n\t# the result is the original specified time minus the offset\n\tresult = dt - offset\n\treturn result", "response": "This function calculates the time which is the specified date or time truncated to the time delta_per_day + period."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef datetime_round(dt, period, start=None):\n\tresult = datetime_mod(dt, period, start)\n\tif abs(dt - result) >= period // 2:\n\t\tresult += period\n\treturn result", "response": "This function will return the datetime that is within the specified period."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nreturn the nearest year to now inferred from a Julian date.", "response": "def get_nearest_year_for_day(day):\n\t\"\"\"\n\tReturns the nearest year to now inferred from a Julian date.\n\t\"\"\"\n\tnow = time.gmtime()\n\tresult = now.tm_year\n\t# if the day is far greater than today, it must be from last year\n\tif day - now.tm_yday > 365 // 2:\n\t\tresult -= 1\n\t# if the day is far less than today, it must be for next year.\n\tif now.tm_yday - day > 365 // 2:\n\t\tresult += 1\n\treturn result"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef get_period_seconds(period):\n\tif isinstance(period, six.string_types):\n\t\ttry:\n\t\t\tname = 'seconds_per_' + period.lower()\n\t\t\tresult = globals()[name]\n\t\texcept KeyError:\n\t\t\tmsg = \"period not in (second, minute, hour, day, month, year)\"\n\t\t\traise ValueError(msg)\n\telif isinstance(period, numbers.Number):\n\t\tresult = period\n\telif isinstance(period, datetime.timedelta):\n\t\tresult = period.days * get_period_seconds('day') + period.seconds\n\telse:\n\t\traise TypeError('period must be a string or integer')\n\treturn result", "response": "get_period_seconds - Get the number of seconds in the specified period"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nreturn the format string that can be used for a given time period.", "response": "def get_date_format_string(period):\n\t\"\"\"\n\tFor a given period (e.g. 'month', 'day', or some numeric interval\n\tsuch as 3600 (in secs)), return the format string that can be\n\tused with strftime to format that time to specify the times\n\tacross that interval, but no more detailed.\n\tFor example,\n\n\t>>> get_date_format_string('month')\n\t'%Y-%m'\n\t>>> get_date_format_string(3600)\n\t'%Y-%m-%d %H'\n\t>>> get_date_format_string('hour')\n\t'%Y-%m-%d %H'\n\t>>> get_date_format_string(None)\n\tTraceback (most recent call last):\n\t\t...\n\tTypeError: period must be a string or integer\n\t>>> get_date_format_string('garbage')\n\tTraceback (most recent call last):\n\t\t...\n\tValueError: period not in (second, minute, hour, day, month, year)\n\t\"\"\"\n\t# handle the special case of 'month' which doesn't have\n\t# a static interval in seconds\n\tif isinstance(period, six.string_types) and period.lower() == 'month':\n\t\treturn '%Y-%m'\n\tfile_period_secs = get_period_seconds(period)\n\tformat_pieces = ('%Y', '-%m-%d', ' %H', '-%M', '-%S')\n\tseconds_per_second = 1\n\tintervals = (\n\t\tseconds_per_year,\n\t\tseconds_per_day,\n\t\tseconds_per_hour,\n\t\tseconds_per_minute,\n\t\tseconds_per_second,\n\t)\n\tmods = list(map(lambda interval: file_period_secs % interval, intervals))\n\tformat_pieces = format_pieces[: mods.index(0) + 1]\n\treturn ''.join(format_pieces)"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ndividing a timedelta by a float value", "response": "def divide_timedelta_float(td, divisor):\n\t\"\"\"\n\tDivide a timedelta by a float value\n\n\t>>> one_day = datetime.timedelta(days=1)\n\t>>> half_day = datetime.timedelta(days=.5)\n\t>>> divide_timedelta_float(one_day, 2.0) == half_day\n\tTrue\n\t>>> divide_timedelta_float(one_day, 2) == half_day\n\tTrue\n\t\"\"\"\n\t# td is comprised of days, seconds, microseconds\n\tdsm = [getattr(td, attr) for attr in ('days', 'seconds', 'microseconds')]\n\tdsm = map(lambda elem: elem / divisor, dsm)\n\treturn datetime.timedelta(*dsm)"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nparses a string representing a span of time and return a datetime. timedelta object.", "response": "def parse_timedelta(str):\n\t\"\"\"\n\tTake a string representing a span of time and parse it to a time delta.\n\tAccepts any string of comma-separated numbers each with a unit indicator.\n\n\t>>> parse_timedelta('1 day')\n\tdatetime.timedelta(days=1)\n\n\t>>> parse_timedelta('1 day, 30 seconds')\n\tdatetime.timedelta(days=1, seconds=30)\n\n\t>>> parse_timedelta('47.32 days, 20 minutes, 15.4 milliseconds')\n\tdatetime.timedelta(days=47, seconds=28848, microseconds=15400)\n\n\tSupports weeks, months, years\n\n\t>>> parse_timedelta('1 week')\n\tdatetime.timedelta(days=7)\n\n\t>>> parse_timedelta('1 year, 1 month')\n\tdatetime.timedelta(days=395, seconds=58685)\n\n\tNote that months and years strict intervals, not aligned\n\tto a calendar:\n\n\t>>> now = datetime.datetime.now()\n\t>>> later = now + parse_timedelta('1 year')\n\t>>> diff = later.replace(year=now.year) - now\n\t>>> diff.seconds\n\t20940\n\t\"\"\"\n\tdeltas = (_parse_timedelta_part(part.strip()) for part in str.split(','))\n\treturn sum(deltas, datetime.timedelta())"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef divide_timedelta(td1, td2):\n\ttry:\n\t\treturn td1 / td2\n\texcept TypeError:\n\t\t# Python 3.2 gets division\n\t\t# http://bugs.python.org/issue2706\n\t\treturn td1.total_seconds() / td2.total_seconds()", "response": "Divide two timedelta objects into a single value."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef date_range(start=None, stop=None, step=None):\n\tif step is None:\n\t\tstep = datetime.timedelta(days=1)\n\tif start is None:\n\t\tstart = datetime.datetime.now()\n\twhile start < stop:\n\t\tyield start\n\t\tstart += step", "response": "A built - in function range that returns a generator that yields dates from start to stop."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef construct_datetime(cls, *args, **kwargs):\n\t\tif len(args) == 1:\n\t\t\targ = args[0]\n\t\t\tmethod = cls.__get_dt_constructor(\n\t\t\t\ttype(arg).__module__,\n\t\t\t\ttype(arg).__name__,\n\t\t\t)\n\t\t\tresult = method(arg)\n\t\t\ttry:\n\t\t\t\tresult = result.replace(tzinfo=kwargs.pop('tzinfo'))\n\t\t\texcept KeyError:\n\t\t\t\tpass\n\t\t\tif kwargs:\n\t\t\t\tfirst_key = kwargs.keys()[0]\n\t\t\t\ttmpl = (\n\t\t\t\t\t\"{first_key} is an invalid keyword \"\n\t\t\t\t\t\"argument for this function.\"\n\t\t\t\t)\n\t\t\t\traise TypeError(tmpl.format(**locals()))\n\t\telse:\n\t\t\tresult = datetime.datetime(*args, **kwargs)\n\t\treturn result", "response": "Construct a datetime. datetime from a number of different time\n\ttypes found in python and pythonwin"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef __common_triplet(input_string, consonants, vowels):\n output = consonants\n\n while len(output) < 3:\n try:\n output += vowels.pop(0)\n except IndexError:\n # If there are less wovels than needed to fill the triplet,\n # (e.g. for a surname as \"Fo'\" or \"Hu\" or the corean \"Y\")\n # fill it with 'X';\n output += 'X'\n\n return output[:3]", "response": "This function returns the common triplet of the input_string."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nreturning the list of consonants and vowels from the input_string.", "response": "def __consonants_and_vowels(input_string):\n \"\"\"__consonants_and_vowels(input_string) -> (string, list)\n\n Get the consonants as a string and the vowels as a list.\n \"\"\"\n input_string = input_string.upper().replace(' ', '')\n\n consonants = [ char for char in input_string if char in __CONSONANTS ]\n vowels = [ char for char in input_string if char in __VOWELS ]\n\n return \"\".join(consonants), vowels"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nreturn the common triplet of the given string.", "response": "def __surname_triplet(input_string):\n \"\"\"__surname_triplet(input_string) -> string\"\"\"\n consonants, vowels = __consonants_and_vowels(input_string)\n\n return __common_triplet(input_string, consonants, vowels)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef __name_triplet(input_string):\n if input_string == '':\n # highly unlikely: no first name, like for instance some Indian persons\n # with only one name on the passport\n # pylint: disable=W0511\n return 'XXX' \n\n consonants, vowels = __consonants_and_vowels(input_string)\n \n if len(consonants) > 3:\n return \"%s%s%s\" % (consonants[0], consonants[2], consonants[3])\n\n return __common_triplet(input_string, consonants, vowels)", "response": "This function returns the name of the current passport based on the input string."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef control_code(input_string):\n assert len(input_string) == 15\n\n # building conversion tables for even and odd characters positions\n even_controlcode = {}\n\n for idx, char in enumerate(string.digits):\n even_controlcode[char] = idx\n\n for idx, char in enumerate(string.ascii_uppercase):\n even_controlcode[char] = idx\n\n values = [ 1, 0, 5, 7, 9, 13, 15, 17, 19, 21, 2, 4, 18, 20, 11, 3, 6, 8,\n 12, 14, 16, 10, 22, 25, 24, 23 ]\n\n odd_controlcode = {}\n\n for idx, char in enumerate(string.digits):\n odd_controlcode[char] = values[idx]\n\n for idx, char in enumerate(string.ascii_uppercase):\n odd_controlcode[char] = values[idx]\n\n # computing the code\n code = 0\n for idx, char in enumerate(input_string):\n if idx % 2 == 0:\n code += odd_controlcode[char]\n else:\n code += even_controlcode[char]\n \n return string.ascii_uppercase[code % 26]", "response": "Computes the control code for the given input_string."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef build(surname, name, birthday, sex, municipality):\n\n # RCCMNL\n output = __surname_triplet(surname) + __name_triplet(name)\n\n # RCCMNL83\n output += str(birthday.year)[2:]\n\n # RCCMNL83S\n output += MONTHSCODE[birthday.month - 1]\n\n # RCCMNL83S18\n output += \"%02d\" % (sex.upper() == 'M' and birthday.day or 40 + birthday.day)\n\n # RCCMNL83S18D969 \n output += municipality\n\n # RCCMNL83S18D969H\n output += control_code(output)\n\n assert isvalid(output)\n\n return output", "response": "Builds the fiscal code for the given person data."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef get_birthday(code):\n assert isvalid(code)\n\n day = int(code[9:11])\n day = day < 32 and day or day - 40\n\n month = MONTHSCODE.index(code[8]) + 1\n year = int(code[6:8])\n\n return \"%02d-%02d-%02d\" % (day, month, year)", "response": "Returns the birthday of the person whose fiscal code is code."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\npass in an Overpass query in Overpass QL.", "response": "def get(self, query, responseformat=\"geojson\", verbosity=\"body\", build=True):\n \"\"\"Pass in an Overpass query in Overpass QL.\"\"\"\n # Construct full Overpass query\n if build:\n full_query = self._construct_ql_query(\n query, responseformat=responseformat, verbosity=verbosity\n )\n else:\n full_query = query\n\n if self.debug:\n logging.getLogger().info(query)\n\n # Get the response from Overpass\n r = self._get_from_overpass(full_query)\n content_type = r.headers.get(\"content-type\")\n\n if self.debug:\n print(content_type)\n if content_type == \"text/csv\":\n result = []\n reader = csv.reader(StringIO(r.text), delimiter=\"\\t\")\n for row in reader:\n result.append(row)\n return result\n elif content_type in (\"text/xml\", \"application/xml\", \"application/osm3s+xml\"):\n return r.text\n elif content_type == \"application/json\":\n response = json.loads(r.text)\n\n if not build:\n return response\n\n # Check for valid answer from Overpass.\n # A valid answer contains an 'elements' key at the root level.\n if \"elements\" not in response:\n raise UnknownOverpassError(\"Received an invalid answer from Overpass.\")\n\n # If there is a 'remark' key, it spells trouble.\n overpass_remark = response.get(\"remark\", None)\n if overpass_remark and overpass_remark.startswith(\"runtime error\"):\n raise ServerRuntimeError(overpass_remark)\n\n if responseformat is not \"geojson\":\n return response\n\n # construct geojson\n return self._as_geojson(response[\"elements\"])"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef parse(self, text):\n\n results = list()\n \n for oneline in text.split('\\n'):\n self._tagger.stdin.write(oneline+'\\n')\n while True:\n r = self._tagger.stdout.readline()[:-1]\n if not r:\n break\n results.append(tuple(r.split('\\t')))\n return results", "response": "Parse the text of a set of items."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef create_port(context, port):\n LOG.info(\"create_port for tenant %s\" % context.tenant_id)\n port_attrs = port[\"port\"]\n\n admin_only = [\"mac_address\", \"device_owner\", \"bridge\", \"admin_state_up\",\n \"use_forbidden_mac_range\", \"network_plugin\",\n \"instance_node_id\"]\n utils.filter_body(context, port_attrs, admin_only=admin_only)\n\n port_attrs = port[\"port\"]\n mac_address = utils.pop_param(port_attrs, \"mac_address\", None)\n use_forbidden_mac_range = utils.pop_param(port_attrs,\n \"use_forbidden_mac_range\", False)\n segment_id = utils.pop_param(port_attrs, \"segment_id\")\n fixed_ips = utils.pop_param(port_attrs, \"fixed_ips\")\n\n if \"device_id\" not in port_attrs:\n port_attrs['device_id'] = \"\"\n device_id = port_attrs['device_id']\n\n # NOTE(morgabra) This should be instance.node from nova, only needed\n # for ironic_driver.\n if \"instance_node_id\" not in port_attrs:\n port_attrs['instance_node_id'] = \"\"\n instance_node_id = port_attrs['instance_node_id']\n\n net_id = port_attrs[\"network_id\"]\n\n port_id = uuidutils.generate_uuid()\n\n net = db_api.network_find(context=context, limit=None, sorts=['id'],\n marker=None, page_reverse=False, fields=None,\n id=net_id, scope=db_api.ONE)\n\n if not net:\n raise n_exc.NetworkNotFound(net_id=net_id)\n _raise_if_unauthorized(context, net)\n\n # NOTE (Perkins): If a device_id is given, try to prevent multiple ports\n # from being created for a device already attached to the network\n if device_id:\n existing_ports = db_api.port_find(context,\n network_id=net_id,\n device_id=device_id,\n scope=db_api.ONE)\n if existing_ports:\n raise n_exc.BadRequest(\n resource=\"port\", msg=\"This device is already connected to the \"\n \"requested network via another port\")\n\n # Try to fail early on quotas and save ourselves some db overhead\n if fixed_ips:\n quota.QUOTAS.limit_check(context, context.tenant_id,\n fixed_ips_per_port=len(fixed_ips))\n\n if not STRATEGY.is_provider_network(net_id):\n # We don't honor segmented networks when they aren't \"shared\"\n segment_id = None\n port_count = db_api.port_count_all(context, network_id=[net_id],\n tenant_id=[context.tenant_id])\n quota.QUOTAS.limit_check(\n context, context.tenant_id,\n ports_per_network=port_count + 1)\n else:\n if not segment_id:\n raise q_exc.AmbiguousNetworkId(net_id=net_id)\n\n network_plugin = utils.pop_param(port_attrs, \"network_plugin\")\n if not network_plugin:\n network_plugin = net[\"network_plugin\"]\n port_attrs[\"network_plugin\"] = network_plugin\n\n ipam_driver = _get_ipam_driver(net, port=port_attrs)\n net_driver = _get_net_driver(net, port=port_attrs)\n # NOTE(morgabra) It's possible that we select a driver different than\n # the one specified by the network. However, we still might need to use\n # this for some operations, so we also fetch it and pass it along to\n # the backend driver we are actually using.\n base_net_driver = _get_net_driver(net)\n\n # TODO(anyone): security groups are not currently supported on port create.\n # Please see JIRA:NCP-801\n security_groups = utils.pop_param(port_attrs, \"security_groups\")\n if security_groups is not None:\n raise q_exc.SecurityGroupsNotImplemented()\n\n group_ids, security_groups = _make_security_group_list(context,\n security_groups)\n quota.QUOTAS.limit_check(context, context.tenant_id,\n security_groups_per_port=len(group_ids))\n addresses = []\n backend_port = None\n\n with utils.CommandManager().execute() as cmd_mgr:\n @cmd_mgr.do\n def _allocate_ips(fixed_ips, net, port_id, segment_id, mac,\n **kwargs):\n if fixed_ips:\n if (STRATEGY.is_provider_network(net_id) and\n not context.is_admin):\n raise n_exc.NotAuthorized()\n\n ips, subnets = split_and_validate_requested_subnets(context,\n net_id,\n segment_id,\n fixed_ips)\n kwargs[\"ip_addresses\"] = ips\n kwargs[\"subnets\"] = subnets\n\n ipam_driver.allocate_ip_address(\n context, addresses, net[\"id\"], port_id,\n CONF.QUARK.ipam_reuse_after, segment_id=segment_id,\n mac_address=mac, **kwargs)\n\n @cmd_mgr.undo\n def _allocate_ips_undo(addr, **kwargs):\n LOG.info(\"Rolling back IP addresses...\")\n if addresses:\n for address in addresses:\n try:\n with context.session.begin():\n ipam_driver.deallocate_ip_address(context, address,\n **kwargs)\n except Exception:\n LOG.exception(\"Couldn't release IP %s\" % address)\n\n @cmd_mgr.do\n def _allocate_mac(net, port_id, mac_address,\n use_forbidden_mac_range=False,\n **kwargs):\n mac = ipam_driver.allocate_mac_address(\n context, net[\"id\"], port_id, CONF.QUARK.ipam_reuse_after,\n mac_address=mac_address,\n use_forbidden_mac_range=use_forbidden_mac_range, **kwargs)\n return mac\n\n @cmd_mgr.undo\n def _allocate_mac_undo(mac, **kwargs):\n LOG.info(\"Rolling back MAC address...\")\n if mac:\n try:\n with context.session.begin():\n ipam_driver.deallocate_mac_address(context,\n mac[\"address\"])\n except Exception:\n LOG.exception(\"Couldn't release MAC %s\" % mac)\n\n @cmd_mgr.do\n def _allocate_backend_port(mac, addresses, net, port_id, **kwargs):\n backend_port = net_driver.create_port(\n context, net[\"id\"],\n port_id=port_id,\n security_groups=group_ids,\n device_id=device_id,\n instance_node_id=instance_node_id,\n mac_address=mac,\n addresses=addresses,\n base_net_driver=base_net_driver)\n _filter_backend_port(backend_port)\n return backend_port\n\n @cmd_mgr.undo\n def _allocate_back_port_undo(backend_port,\n **kwargs):\n LOG.info(\"Rolling back backend port...\")\n try:\n backend_port_uuid = None\n if backend_port:\n backend_port_uuid = backend_port.get(\"uuid\")\n net_driver.delete_port(context, backend_port_uuid)\n except Exception:\n LOG.exception(\n \"Couldn't rollback backend port %s\" % backend_port)\n\n @cmd_mgr.do\n def _allocate_db_port(port_attrs, backend_port, addresses, mac,\n **kwargs):\n port_attrs[\"network_id\"] = net[\"id\"]\n port_attrs[\"id\"] = port_id\n port_attrs[\"security_groups\"] = security_groups\n\n LOG.info(\"Including extra plugin attrs: %s\" % backend_port)\n port_attrs.update(backend_port)\n with context.session.begin():\n new_port = db_api.port_create(\n context, addresses=addresses, mac_address=mac[\"address\"],\n backend_key=backend_port[\"uuid\"], **port_attrs)\n\n return new_port\n\n @cmd_mgr.undo\n def _allocate_db_port_undo(new_port,\n **kwargs):\n LOG.info(\"Rolling back database port...\")\n if not new_port:\n return\n try:\n with context.session.begin():\n db_api.port_delete(context, new_port)\n except Exception:\n LOG.exception(\n \"Couldn't rollback db port %s\" % backend_port)\n\n # addresses, mac, backend_port, new_port\n mac = _allocate_mac(net, port_id, mac_address,\n use_forbidden_mac_range=use_forbidden_mac_range)\n _allocate_ips(fixed_ips, net, port_id, segment_id, mac)\n backend_port = _allocate_backend_port(mac, addresses, net, port_id)\n new_port = _allocate_db_port(port_attrs, backend_port, addresses, mac)\n\n return v._make_port_dict(new_port)", "response": "Create a port which is a connection point of a device."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nupdates the values of a port.", "response": "def update_port(context, id, port):\n \"\"\"Update values of a port.\n\n : param context: neutron api request context\n : param id: UUID representing the port to update.\n : param port: dictionary with keys indicating fields to update.\n valid keys are those that have a value of True for 'allow_put'\n as listed in the RESOURCE_ATTRIBUTE_MAP object in\n neutron/api/v2/attributes.py.\n \"\"\"\n LOG.info(\"update_port %s for tenant %s\" % (id, context.tenant_id))\n port_db = db_api.port_find(context, id=id, scope=db_api.ONE)\n if not port_db:\n raise n_exc.PortNotFound(port_id=id)\n\n port_dict = port[\"port\"]\n fixed_ips = port_dict.pop(\"fixed_ips\", None)\n\n admin_only = [\"mac_address\", \"device_owner\", \"bridge\", \"admin_state_up\",\n \"device_id\"]\n always_filter = [\"network_id\", \"backend_key\", \"network_plugin\"]\n utils.filter_body(context, port_dict, admin_only=admin_only,\n always_filter=always_filter)\n\n # Pre-check the requested fixed_ips before making too many db trips.\n # Note that this is the only check we need, since this call replaces\n # the entirety of the IP addresses document if fixed_ips are provided.\n if fixed_ips:\n quota.QUOTAS.limit_check(context, context.tenant_id,\n fixed_ips_per_port=len(fixed_ips))\n\n new_security_groups = utils.pop_param(port_dict, \"security_groups\")\n if new_security_groups is not None:\n if (Capabilities.TENANT_NETWORK_SG not in\n CONF.QUARK.environment_capabilities):\n if not STRATEGY.is_provider_network(port_db[\"network_id\"]):\n raise q_exc.TenantNetworkSecurityGroupRulesNotEnabled()\n\n if new_security_groups is not None and not port_db[\"device_id\"]:\n raise q_exc.SecurityGroupsRequireDevice()\n\n group_ids, security_group_mods = _make_security_group_list(\n context, new_security_groups)\n quota.QUOTAS.limit_check(context, context.tenant_id,\n security_groups_per_port=len(group_ids))\n\n if fixed_ips is not None:\n # NOTE(mdietz): we want full control over IPAM since\n # we're allocating by subnet instead of\n # network.\n ipam_driver = ipam.IPAM_REGISTRY.get_strategy(\n ipam.QuarkIpamANY.get_name())\n\n addresses, subnet_ids = [], []\n ip_addresses = {}\n\n for fixed_ip in fixed_ips:\n subnet_id = fixed_ip.get(\"subnet_id\")\n ip_address = fixed_ip.get(\"ip_address\")\n if not (subnet_id or ip_address):\n raise n_exc.BadRequest(\n resource=\"fixed_ips\",\n msg=\"subnet_id or ip_address required\")\n\n if ip_address and not subnet_id:\n raise n_exc.BadRequest(\n resource=\"fixed_ips\",\n msg=\"subnet_id required for ip_address allocation\")\n\n if subnet_id and ip_address:\n ip_netaddr = None\n try:\n ip_netaddr = netaddr.IPAddress(ip_address).ipv6()\n except netaddr.AddrFormatError:\n raise n_exc.InvalidInput(\n error_message=\"Invalid format provided for ip_address\")\n ip_addresses[ip_netaddr] = subnet_id\n else:\n subnet_ids.append(subnet_id)\n\n port_ips = set([netaddr.IPAddress(int(a[\"address\"]))\n for a in port_db[\"ip_addresses\"]])\n new_ips = set([a for a in ip_addresses.keys()])\n\n ips_to_allocate = list(new_ips - port_ips)\n ips_to_deallocate = list(port_ips - new_ips)\n\n for ip in ips_to_allocate:\n if ip in ip_addresses:\n # NOTE: Fix for RM10187 - we were losing the list of IPs if\n # more than one IP was to be allocated. Track an\n # aggregate list instead, and add it to the running total\n # after each allocate\n allocated = []\n ipam_driver.allocate_ip_address(\n context, allocated, port_db[\"network_id\"],\n port_db[\"id\"], reuse_after=None, ip_addresses=[ip],\n subnets=[ip_addresses[ip]])\n addresses.extend(allocated)\n\n for ip in ips_to_deallocate:\n ipam_driver.deallocate_ips_by_port(\n context, port_db, ip_address=ip)\n\n for subnet_id in subnet_ids:\n ipam_driver.allocate_ip_address(\n context, addresses, port_db[\"network_id\"], port_db[\"id\"],\n reuse_after=CONF.QUARK.ipam_reuse_after,\n subnets=[subnet_id])\n\n # Need to return all existing addresses and the new ones\n if addresses:\n port_dict[\"addresses\"] = port_db[\"ip_addresses\"]\n port_dict[\"addresses\"].extend(addresses)\n\n # NOTE(morgabra) Updating network_plugin on port objects is explicitly\n # disallowed in the api, so we use whatever exists in the db.\n net_driver = _get_net_driver(port_db.network, port=port_db)\n base_net_driver = _get_net_driver(port_db.network)\n\n # TODO(anyone): What do we want to have happen here if this fails? Is it\n # ok to continue to keep the IPs but fail to apply security\n # groups? Is there a clean way to have a multi-status? Since\n # we're in a beta-y status, I'm going to let this sit for\n # a future patch where we have time to solve it well.\n kwargs = {}\n if new_security_groups is not None:\n # TODO(anyone): this is kind of silly (when testing), because it will\n # modify the incoming dict. Probably should be a copy or\n # something.\n kwargs[\"security_groups\"] = security_group_mods\n net_driver.update_port(context, port_id=port_db[\"backend_key\"],\n mac_address=port_db[\"mac_address\"],\n device_id=port_db[\"device_id\"],\n base_net_driver=base_net_driver,\n **kwargs)\n\n port_dict[\"security_groups\"] = security_group_mods\n\n with context.session.begin():\n port = db_api.port_update(context, port_db, **port_dict)\n\n # NOTE(mdietz): fix for issue 112, we wanted the IPs to be in\n # allocated_at order, so get a fresh object every time\n if port_db in context.session:\n context.session.expunge(port_db)\n port_db = db_api.port_find(context, id=id, scope=db_api.ONE)\n\n return v._make_port_dict(port_db)"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nretrieves a port. : param context: neutron api request context : param id: UUID representing the port to fetch. : param fields: a list of strings that are valid keys in a port dictionary as listed in the RESOURCE_ATTRIBUTE_MAP object in neutron/api/v2/attributes.py. Only these fields will be returned.", "response": "def get_port(context, id, fields=None):\n \"\"\"Retrieve a port.\n\n : param context: neutron api request context\n : param id: UUID representing the port to fetch.\n : param fields: a list of strings that are valid keys in a\n port dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n object in neutron/api/v2/attributes.py. Only these fields\n will be returned.\n \"\"\"\n LOG.info(\"get_port %s for tenant %s fields %s\" %\n (id, context.tenant_id, fields))\n results = db_api.port_find(context, id=id, fields=fields,\n scope=db_api.ONE)\n\n if not results:\n raise n_exc.PortNotFound(port_id=id)\n\n return v._make_port_dict(results)"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ngets a list of ports for the user in the tenant.", "response": "def get_ports(context, limit=None, sorts=['id'], marker=None,\n page_reverse=False, filters=None, fields=None):\n \"\"\"Retrieve a list of ports.\n\n The contents of the list depends on the identity of the user\n making the request (as indicated by the context) as well as any\n filters.\n : param context: neutron api request context\n : param filters: a dictionary with keys that are valid keys for\n a port as listed in the RESOURCE_ATTRIBUTE_MAP object\n in neutron/api/v2/attributes.py. Values in this dictionary\n are an iterable containing values that will be used for an exact\n match comparison for that value. Each result returned by this\n function will have matched one of the values for each key in\n filters.\n : param fields: a list of strings that are valid keys in a\n port dictionary as listed in the RESOURCE_ATTRIBUTE_MAP\n object in neutron/api/v2/attributes.py. Only these fields\n will be returned.\n \"\"\"\n LOG.info(\"get_ports for tenant %s filters %s fields %s\" %\n (context.tenant_id, filters, fields))\n if filters is None:\n filters = {}\n\n if \"ip_address\" in filters:\n if not context.is_admin:\n raise n_exc.NotAuthorized()\n ips = []\n try:\n ips = [netaddr.IPAddress(ip) for ip in filters.pop(\"ip_address\")]\n except netaddr.AddrFormatError:\n raise n_exc.InvalidInput(\n error_message=\"Invalid format provided for ip_address\")\n query = db_api.port_find_by_ip_address(context, ip_address=ips,\n scope=db_api.ALL, **filters)\n ports = []\n for ip in query:\n ports.extend(ip.ports)\n else:\n ports = db_api.port_find(context, limit, sorts, marker,\n fields=fields, join_security_groups=True,\n **filters)\n return v._make_ports_list(ports, fields)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef get_ports_count(context, filters=None):\n LOG.info(\"get_ports_count for tenant %s filters %s\" %\n (context.tenant_id, filters))\n return db_api.port_count_all(context, join_security_groups=True, **filters)", "response": "Return the number of ports in the current context."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef delete_port(context, id):\n LOG.info(\"delete_port %s for tenant %s\" % (id, context.tenant_id))\n\n port = db_api.port_find(context, id=id, scope=db_api.ONE)\n if not port:\n raise n_exc.PortNotFound(port_id=id)\n\n if 'device_id' in port: # false is weird, but ignore that\n LOG.info(\"delete_port %s for tenant %s has device %s\" %\n (id, context.tenant_id, port['device_id']))\n\n backend_key = port[\"backend_key\"]\n mac_address = netaddr.EUI(port[\"mac_address\"]).value\n ipam_driver = _get_ipam_driver(port[\"network\"], port=port)\n ipam_driver.deallocate_mac_address(context, mac_address)\n ipam_driver.deallocate_ips_by_port(\n context, port, ipam_reuse_after=CONF.QUARK.ipam_reuse_after)\n\n net_driver = _get_net_driver(port[\"network\"], port=port)\n base_net_driver = _get_net_driver(port[\"network\"])\n net_driver.delete_port(context, backend_key, device_id=port[\"device_id\"],\n mac_address=port[\"mac_address\"],\n base_net_driver=base_net_driver)\n\n with context.session.begin():\n db_api.port_delete(context, port)", "response": "Delete a port.\n\n : param context: neutron api request context\n : param id: UUID representing the port to delete."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nassociate the flip with ports and creates the flip driver with the flip driver.", "response": "def _create_flip(context, flip, port_fixed_ips):\n \"\"\"Associates the flip with ports and creates it with the flip driver\n\n :param context: neutron api request context.\n :param flip: quark.db.models.IPAddress object representing a floating IP\n :param port_fixed_ips: dictionary of the structure:\n {\"
')\n long_description = re.sub(r'(\\W)``([^`]+)``(\\W)', r'\\1\\2\\3', long_description)\n\n text = DESCRIPTION_TEMPLATES[markup].format(\n keywords=', '.join(cfg.project.keywords),\n classifiers='\\n'.join(cfg.project.classifiers),\n classifiers_indented=' ' + '\\n '.join(cfg.project.classifiers),\n packages=', '.join(cfg.project.packages),\n long_description_html='
{}
'.format(long_description),\n ##data='\\n'.join([\"%s=%r\" % i for i in cfg.project.iteritems()]),\n **cfg)\n with io.open(description_file, 'w', encoding='utf-8') as handle:\n handle.write(text)"} {"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef capture(cmd, **kw):\n kw = kw.copy()\n kw['hide'] = 'out'\n if not kw.get('echo', False):\n kw['echo'] = False\n ignore_failures = kw.pop('ignore_failures', False)\n try:\n return invoke_run(cmd, **kw).stdout.strip()\n except exceptions.Failure as exc:\n if not ignore_failures:\n notify.error(\"Command `{}` failed with RC={}!\".format(cmd, exc.result.return_code,))\n raise", "response": "Run a command and return its stripped captured output."} {"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef run(cmd, **kw):\n kw = kw.copy()\n kw.setdefault('warn', False) # make extra sure errors don't get silenced\n\n report_error = kw.pop('report_error', True)\n runner = kw.pop('runner', invoke_run)\n\n try:\n return runner(cmd, **kw)\n except exceptions.Failure as exc:\n sys.stdout.flush()\n sys.stderr.flush()\n if report_error:\n notify.error(\"Command `{}` failed with RC={}!\".format(cmd, exc.result.return_code,))\n raise\n finally:\n sys.stdout.flush()\n sys.stderr.flush()", "response": "Run a command and flush its output."} {"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef auto_detect(workdir):\n # Any additions here also need a change to `SCM_PROVIDERS`!\n if os.path.isdir(os.path.join(workdir, '.git')) and os.path.isfile(os.path.join(workdir, '.git', 'HEAD')):\n return 'git'\n\n return 'unknown'", "response": "Detects the SCM used in the given directory."} {"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef provider(workdir, commit=True, **kwargs):\n return SCM_PROVIDER[auto_detect(workdir)](workdir, commit=commit, **kwargs)", "response": "Factory for the correct SCM provider in workdir."} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nexiting with error code and message.", "response": "def fail(message, exitcode=1):\n \"\"\"Exit with error code and message.\"\"\"\n sys.stderr.write('ERROR: {}\\n'.format(message))\n sys.stderr.flush()\n sys.exit(exitcode)"} {"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef get_pypi_auth(configfile='~/.pypirc'):\n pypi_cfg = ConfigParser()\n if pypi_cfg.read(os.path.expanduser(configfile)):\n try:\n user = pypi_cfg.get('pypi', 'username')\n pwd = pypi_cfg.get('pypi', 'password')\n return user, pwd\n except ConfigError:\n notify.warning(\"No PyPI credentials in '{}',\"\n \" will fall back to '~/.netrc'...\".format(configfile))\n return None", "response": "Read auth from pypi config file."} {"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\ncontrols a running Sphinx autobuild process.", "response": "def watchdogctl(ctx, kill=False, verbose=True):\n \"\"\"Control / check a running Sphinx autobuild process.\"\"\"\n tries = 40 if kill else 0\n cmd = 'lsof -i TCP:{} -s TCP:LISTEN -S -Fp 2>/dev/null'.format(ctx.rituals.docs.watchdog.port)\n\n pidno = 0\n pidinfo = capture(cmd, ignore_failures=True)\n while pidinfo:\n pidline = next(filter(None, [re.match(r'^p(\\d+)$', x) for x in pidinfo.splitlines()]))\n if not pidline:\n raise ValueError(\"Standard lsof output expected (got {!r})\".format(pidinfo))\n pidno = int(pidline.group(1), 10)\n if verbose:\n ctx.run(\"ps uw {}\".format(pidno), echo=False)\n verbose = False\n\n tries -= 1\n if tries <= 0:\n break\n else:\n try:\n os.kill(pidno, 0)\n #except ProcessLookupError: # XXX Python3 only\n # break\n except OSError as exc: # Python2 has no ProcessLookupError\n if exc.errno == 3:\n break\n raise\n else:\n notify.info(\"Killing PID {}\".format(pidno))\n ctx.run(\"kill {}\".format(pidno), echo=False)\n time.sleep(.25)\n\n pid = capture(cmd, ignore_failures=True)\n\n return pidno"} {"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef confluence(ctx, no_publish=False, clean=False, opts=''):\n cfg = config.load()\n\n if clean:\n ctx.run(\"invoke clean --docs\")\n\n cmd = ['sphinx-build', '-b', 'confluence']\n cmd.extend(['-E', '-a']) # force a full rebuild\n if opts:\n cmd.append(opts)\n cmd.extend(['.', ctx.rituals.docs.build + '_cf'])\n if no_publish:\n cmd.extend(['-Dconfluence_publish=False'])\n\n # Build docs\n notify.info(\"Starting Sphinx build...\")\n with pushd(ctx.rituals.docs.sources):\n ctx.run(' '.join(cmd), pty=True)", "response": "Build Sphinx docs and publish to Confluence."} {"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nuploads a ZIP of built docs to the current directory.", "response": "def upload(ctx, browse=False, target=None, release='latest'):\n \"\"\"Upload a ZIP of built docs (by default to PyPI, else a WebDAV URL).\"\"\"\n cfg = config.load()\n uploader = DocsUploader(ctx, cfg, target)\n\n html_dir = os.path.join(ctx.rituals.docs.sources, ctx.rituals.docs.build)\n if not os.path.isdir(html_dir):\n notify.failure(\"No HTML docs dir found at '{}'!\".format(html_dir))\n\n url = uploader.upload(html_dir, release)\n notify.info(\"Uploaded docs to '{url}'!\".format(url=url or 'N/A'))\n if url and browse: # Open in browser?\n webbrowser.open_new_tab(url)"} {"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nprovides a zipped stream of the docs tree.", "response": "def _zipped(self, docs_base):\n \"\"\" Provide a zipped stream of the docs tree.\"\"\"\n with pushd(docs_base):\n with tempfile.NamedTemporaryFile(prefix='pythonhosted-', delete=False) as ziphandle:\n pass\n zip_name = shutil.make_archive(ziphandle.name, 'zip')\n\n notify.info(\"Uploading {:.1f} MiB from '{}' to '{}'...\"\n .format(os.path.getsize(zip_name) / 1024.0, zip_name, self.target))\n with io.open(zip_name, 'rb') as zipread:\n try:\n yield zipread\n finally:\n os.remove(ziphandle.name)\n os.remove(ziphandle.name + '.zip')"} {"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef _to_webdav(self, docs_base, release):\n try:\n git_path = subprocess.check_output('git remote get-url origin 2>/dev/null', shell=True)\n except subprocess.CalledProcessError:\n git_path = ''\n else:\n git_path = git_path.decode('ascii').strip()\n git_path = git_path.replace('http://', '').replace('https://', '').replace('ssh://', '')\n git_path = re.search(r'[^:/]+?[:/](.+)', git_path)\n git_path = git_path.group(1).replace('.git', '') if git_path else ''\n url = None\n with self._zipped(docs_base) as handle:\n url_ns = dict(name=self.cfg.project.name, version=release, git_path=git_path)\n reply = requests.put(self.params['url'].format(**url_ns),\n data=handle.read(), headers={'Accept': 'application/json'})\n if reply.status_code in range(200, 300):\n notify.info(\"{status_code} {reason}\".format(**vars(reply)))\n try:\n data = reply.json()\n except ValueError as exc:\n notify.warning(\"Didn't get a JSON response! ({})\".format(exc))\n else:\n if 'downloadUri' in data: # Artifactory\n url = data['downloadUri'] + '!/index.html'\n elif reply.status_code == 301:\n url = reply.headers['location']\n else:\n data = self.cfg.copy()\n data.update(self.params)\n data.update(vars(reply))\n notify.error(\"{status_code} {reason} for PUT to {url}\".format(**data))\n\n if not url:\n notify.warning(\"Couldn't get URL from upload response!\")\n return url", "response": "Upload to WebDAV store."} {"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef upload(self, docs_base, release):\n return getattr(self, '_to_' + self.target)(docs_base, release)", "response": "Upload docs in docs_base to the target of this uploader."} {"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef search_file_upwards(name, base=None):\n base = base or os.getcwd()\n while base != os.path.dirname(base):\n if os.path.exists(os.path.join(base, name)):\n return base\n base = os.path.dirname(base)\n\n return None", "response": "Search for a file named name from cwd or given directory to root."} {"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nadd given directory to PYTHONPATH.", "response": "def add_dir2pypath(path):\n \"\"\"Add given directory to PYTHONPATH, e.g. for pylint.\"\"\"\n py_path = os.environ.get('PYTHONPATH', '')\n if path not in py_path.split(os.pathsep):\n py_path = ''.join([path, os.pathsep if py_path else '', py_path])\n os.environ['PYTHONPATH'] = py_path"} {"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef pushd(path):\n saved = os.getcwd()\n os.chdir(path)\n try:\n yield saved\n finally:\n os.chdir(saved)", "response": "A context that enters a given directory and restores the old state on exit."} {"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nrun a command or just echo it depending on commit.", "response": "def run_elective(self, cmd, *args, **kwargs):\n \"\"\"Run a command, or just echo it, depending on `commit`.\"\"\"\n if self._commit:\n return self.run(cmd, *args, **kwargs)\n else:\n notify.warning(\"WOULD RUN: {}\".format(cmd))\n kwargs = kwargs.copy()\n kwargs['echo'] = False\n return self.run('true', *args, **kwargs)"} {"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef banner(msg):\n if ECHO:\n _flush()\n sys.stderr.write(\"\\033[1;7;32;40m{}\\033[0m\\n\".format(msg))\n sys.stderr.flush()", "response": "Emit a banner just like Invoke s run."} {"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef info(msg):\n _flush()\n sys.stdout.write(msg + '\\n')\n sys.stdout.flush()", "response": "Emit a normal message."} {"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nemit a warning message.", "response": "def warning(msg):\n \"\"\"Emit a warning message.\"\"\"\n _flush()\n sys.stderr.write(\"\\033[1;7;33;40mWARNING: {}\\033[0m\\n\".format(msg))\n sys.stderr.flush()"} {"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef error(msg):\n _flush()\n sys.stderr.write(\"\\033[1;37;41mERROR: {}\\033[0m\\n\".format(msg))\n sys.stderr.flush()", "response": "Emit an error message to stderr."} {"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nget currently used devpi base URL.", "response": "def get_devpi_url(ctx):\n \"\"\"Get currently used 'devpi' base URL.\"\"\"\n cmd = 'devpi use --urls'\n lines = ctx.run(cmd, hide='out', echo=False).stdout.splitlines()\n for line in lines:\n try:\n line, base_url = line.split(':', 1)\n except ValueError:\n notify.warning('Ignoring \"{}\"!'.format(line))\n else:\n if line.split()[-1].strip() == 'simpleindex':\n return base_url.split('\\x1b')[0].strip().rstrip('/')\n\n raise LookupError(\"Cannot find simpleindex URL in '{}' output:\\n {}\".format(\n cmd, '\\n '.join(lines),\n ))"} {"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\ndetermine location of tasks. py.", "response": "def get_project_root():\n \"\"\" Determine location of `tasks.py`.\"\"\"\n try:\n tasks_py = sys.modules['tasks']\n except KeyError:\n return None\n else:\n return os.path.abspath(os.path.dirname(tasks_py.__file__))"} {"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef load():\n cfg = Bunch(DEFAULTS)\n # TODO: override with contents of [rituals] section in setup.cfg\n\n cfg.project_root = get_project_root()\n if not cfg.project_root:\n raise RuntimeError(\"No tasks module is imported, cannot determine project root\")\n\n cfg.rootjoin = lambda *names: os.path.join(cfg.project_root, *names)\n cfg.srcjoin = lambda *names: cfg.rootjoin(cfg.srcdir, *names)\n cfg.testjoin = lambda *names: cfg.rootjoin(cfg.testdir, *names)\n cfg.cwd = os.getcwd()\n os.chdir(cfg.project_root)\n\n # this assumes an importable setup.py\n # TODO: maybe call \"python setup.py egg_info\" for metadata\n if cfg.project_root not in sys.path:\n sys.path.append(cfg.project_root)\n try:\n from setup import project # pylint: disable=no-name-in-module\n except ImportError:\n from setup import setup_args as project # pylint: disable=no-name-in-module\n cfg.project = Bunch(project)\n\n return cfg", "response": "Load and return a Bunch containing all the configuration values for the current project root."} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nconvert a glob part to regex syntax.", "response": "def glob2re(part):\n \"\"\"Convert a path part to regex syntax.\"\"\"\n return \"[^/]*\".join(\n re.escape(bit).replace(r'\\[\\^', '[^').replace(r'\\[', '[').replace(r'\\]', ']')\n for bit in part.split(\"*\")\n )"} {"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef parse_glob(pattern):\n if not pattern:\n return\n\n bits = pattern.split(\"/\")\n dirs, filename = bits[:-1], bits[-1]\n\n for dirname in dirs:\n if dirname == \"**\":\n yield \"(|.+/)\"\n else:\n yield glob2re(dirname) + \"/\"\n\n yield glob2re(filename)", "response": "Generate parts of regex transformed from glob pattern."} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nconvert the given glob spec to a compiled regex.", "response": "def compile_glob(spec):\n \"\"\"Convert the given glob `spec` to a compiled regex.\"\"\"\n parsed = \"\".join(parse_glob(spec))\n regex = \"^{0}$\".format(parsed)\n return re.compile(regex)"} {"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nchecking patterns in order last match that includes or excludes path wins. Return None on undecided.", "response": "def included(self, path, is_dir=False):\n \"\"\"Check patterns in order, last match that includes or excludes `path` wins. Return `None` on undecided.\"\"\"\n inclusive = None\n for pattern in self.patterns:\n if pattern.is_dir == is_dir and pattern.matches(path):\n inclusive = pattern.inclusive\n\n #print('+++' if inclusive else '---', path, pattern)\n return inclusive"} {"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef walk(self, **kwargs):\n lead = ''\n if 'with_root' in kwargs and kwargs.pop('with_root'):\n lead = self.root.rstrip(os.sep) + os.sep\n\n for base, dirs, files in os.walk(self.root, **kwargs):\n prefix = base[len(self.root):].lstrip(os.sep)\n bits = prefix.split(os.sep) if prefix else []\n\n for dirname in dirs[:]:\n path = '/'.join(bits + [dirname])\n inclusive = self.included(path, is_dir=True)\n if inclusive:\n yield lead + path + '/'\n elif inclusive is False:\n dirs.remove(dirname)\n\n for filename in files:\n path = '/'.join(bits + [filename])\n if self.included(path):\n yield lead + path", "response": "Like os. walk but generating paths relative to the root."} {"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef build(ctx, dput='', opts=''):\n # Get package metadata\n with io.open('debian/changelog', encoding='utf-8') as changes:\n metadata = re.match(r'^([^ ]+) \\(([^)]+)\\) ([^;]+); urgency=(.+)$', changes.readline().rstrip())\n if not metadata:\n notify.failure('Badly formatted top entry in changelog')\n name, version, _, _ = metadata.groups()\n\n # Build package\n ctx.run('dpkg-buildpackage {} {}'.format(ctx.rituals.deb.build.opts, opts))\n\n # Move created artifacts into \"dist\"\n if not os.path.exists('dist'):\n os.makedirs('dist')\n artifact_pattern = '{}?{}*'.format(name, re.sub(r'[^-_.a-zA-Z0-9]', '?', version))\n changes_files = []\n for debfile in glob.glob('../' + artifact_pattern):\n shutil.move(debfile, 'dist')\n if debfile.endswith('.changes'):\n changes_files.append(os.path.join('dist', os.path.basename(debfile)))\n ctx.run('ls -l dist/{}'.format(artifact_pattern))\n\n if dput:\n ctx.run('dput {} {}'.format(dput, ' '.join(changes_files)))", "response": "Build a DEB package."} {"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ncleans up the project files.", "response": "def clean(_dummy_ctx, docs=False, backups=False, bytecode=False, dist=False, # pylint: disable=redefined-outer-name\n all=False, venv=False, tox=False, extra=''): # pylint: disable=redefined-builtin\n \"\"\"Perform house-keeping.\"\"\"\n cfg = config.load()\n notify.banner(\"Cleaning up project files\")\n\n # Add patterns based on given parameters\n venv_dirs = ['bin', 'include', 'lib', 'share', 'local', '.venv']\n patterns = ['build/', 'pip-selfcheck.json']\n excludes = ['.git/', '.hg/', '.svn/', 'debian/*/']\n if docs or all:\n patterns.extend(['docs/_build/', 'doc/_build/'])\n if dist or all:\n patterns.append('dist/')\n if backups or all:\n patterns.extend(['**/*~'])\n if bytecode or all:\n patterns.extend([\n '**/*.py[co]', '**/__pycache__/', '*.egg-info/',\n cfg.srcjoin('*.egg-info/')[len(cfg.project_root)+1:],\n ])\n if venv:\n patterns.extend([i + '/' for i in venv_dirs])\n if tox:\n patterns.append('.tox/')\n else:\n excludes.append('.tox/')\n if extra:\n patterns.extend(shlex.split(extra))\n\n # Build fileset\n patterns = [antglob.includes(i) for i in patterns] + [antglob.excludes(i) for i in excludes]\n if not venv:\n # Do not scan venv dirs when not cleaning them\n patterns.extend([antglob.excludes(i + '/') for i in venv_dirs])\n fileset = antglob.FileSet(cfg.project_root, patterns)\n\n # Iterate over matches and remove them\n for name in fileset:\n notify.info('rm {0}'.format(name))\n if name.endswith('/'):\n shutil.rmtree(os.path.join(cfg.project_root, name))\n else:\n os.unlink(os.path.join(cfg.project_root, name))"} {"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef freeze(ctx, local=False):\n cmd = 'pip --disable-pip-version-check freeze{}'.format(' --local' if local else '')\n frozen = ctx.run(cmd, hide='out').stdout.replace('\\x1b', '#')\n with io.open('frozen-requirements.txt', 'w', encoding='ascii') as out:\n out.write(\"# Requirements frozen by 'pip freeze' on {}\\n\".format(isodate()))\n out.write(frozen)\n notify.info(\"Frozen {} requirements.\".format(len(frozen.splitlines()),))", "response": "Freeze currently installed requirements."} {"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef isodate(datestamp=None, microseconds=False):\n datestamp = datestamp or datetime.datetime.now()\n if not microseconds:\n usecs = datetime.timedelta(microseconds=datestamp.microsecond)\n datestamp = datestamp - usecs\n return datestamp.isoformat(b' ' if PY2 else u' ')", "response": "Return current or given time formatted according to ISO - 8601."} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nwindowing allow application paths to be registered in the registry.", "response": "def _get_registered_executable(exe_name):\n \"\"\"Windows allow application paths to be registered in the registry.\"\"\"\n registered = None\n if sys.platform.startswith('win'):\n if os.path.splitext(exe_name)[1].lower() != '.exe':\n exe_name += '.exe'\n import _winreg # pylint: disable=import-error\n try:\n key = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\App Paths\\\\\" + exe_name\n value = _winreg.QueryValue(_winreg.HKEY_LOCAL_MACHINE, key)\n registered = (value, \"from HKLM\\\\\"+key)\n except _winreg.error:\n pass\n if registered and not os.path.exists(registered[0]):\n registered = None\n return registered"} {"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nculling inappropriate matches. Possible reasons: - a duplicate of a previous match - not a disk file - not executable (non-Windows) If 'potential' is approved it is returned and added to 'matches'. Otherwise, None is returned.", "response": "def _cull(potential, matches, verbose=0):\n \"\"\"Cull inappropriate matches. Possible reasons:\n - a duplicate of a previous match\n - not a disk file\n - not executable (non-Windows)\n If 'potential' is approved it is returned and added to 'matches'.\n Otherwise, None is returned.\n \"\"\"\n for match in matches: # don't yield duplicates\n if _samefile(potential[0], match[0]):\n if verbose:\n sys.stderr.write(\"duplicate: %s (%s)\\n\" % potential)\n return None\n\n if not stat.S_ISREG(os.stat(potential[0]).st_mode):\n if verbose:\n sys.stderr.write(\"not a regular file: %s (%s)\\n\" % potential)\n elif not os.access(potential[0], os.X_OK):\n if verbose:\n sys.stderr.write(\"no executable access: %s (%s)\\n\" % potential)\n else:\n matches.append(potential)\n return potential\n\n return None"} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nreturn a generator of full paths to the given command.", "response": "def whichgen(command, path=None, verbose=0, exts=None): # pylint: disable=too-many-branches, too-many-statements\n \"\"\"Return a generator of full paths to the given command.\n\n \"command\" is a the name of the executable to search for.\n \"path\" is an optional alternate path list to search. The default it\n to use the PATH environment variable.\n \"verbose\", if true, will cause a 2-tuple to be returned for each\n match. The second element is a textual description of where the\n match was found.\n \"exts\" optionally allows one to specify a list of extensions to use\n instead of the standard list for this system. This can\n effectively be used as an optimization to, for example, avoid\n stat's of \"foo.vbs\" when searching for \"foo\" and you know it is\n not a VisualBasic script but \".vbs\" is on PATHEXT. This option\n is only supported on Windows.\n\n This method returns a generator which yields either full paths to\n the given command or, if verbose, tuples of the form (' + os.path.basename(plot_file_name) + '