repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
aws/aws-dynamodb-encryption-python
src/dynamodb_encryption_sdk/internal/utils.py
decrypt_get_item
def decrypt_get_item(decrypt_method, crypto_config_method, read_method, **kwargs): # type: (Callable, Callable, Callable, **Any) -> Dict # TODO: narrow this down """Transparently decrypt an item after getting it from the table. :param callable decrypt_method: Method to use to decrypt item :param callable crypto_config_method: Method that accepts ``kwargs`` and provides a :class:`CryptoConfig` :param callable read_method: Method that reads from the table :param **kwargs: Keyword arguments to pass to ``read_method`` :return: DynamoDB response :rtype: dict """ validate_get_arguments(kwargs) crypto_config, ddb_kwargs = crypto_config_method(**kwargs) response = read_method(**ddb_kwargs) if "Item" in response: response["Item"] = decrypt_method( item=response["Item"], crypto_config=crypto_config.with_item(_item_transformer(decrypt_method)(response["Item"])), ) return response
python
def decrypt_get_item(decrypt_method, crypto_config_method, read_method, **kwargs): # type: (Callable, Callable, Callable, **Any) -> Dict # TODO: narrow this down """Transparently decrypt an item after getting it from the table. :param callable decrypt_method: Method to use to decrypt item :param callable crypto_config_method: Method that accepts ``kwargs`` and provides a :class:`CryptoConfig` :param callable read_method: Method that reads from the table :param **kwargs: Keyword arguments to pass to ``read_method`` :return: DynamoDB response :rtype: dict """ validate_get_arguments(kwargs) crypto_config, ddb_kwargs = crypto_config_method(**kwargs) response = read_method(**ddb_kwargs) if "Item" in response: response["Item"] = decrypt_method( item=response["Item"], crypto_config=crypto_config.with_item(_item_transformer(decrypt_method)(response["Item"])), ) return response
[ "def", "decrypt_get_item", "(", "decrypt_method", ",", "crypto_config_method", ",", "read_method", ",", "*", "*", "kwargs", ")", ":", "# type: (Callable, Callable, Callable, **Any) -> Dict", "# TODO: narrow this down", "validate_get_arguments", "(", "kwargs", ")", "crypto_con...
Transparently decrypt an item after getting it from the table. :param callable decrypt_method: Method to use to decrypt item :param callable crypto_config_method: Method that accepts ``kwargs`` and provides a :class:`CryptoConfig` :param callable read_method: Method that reads from the table :param **kwargs: Keyword arguments to pass to ``read_method`` :return: DynamoDB response :rtype: dict
[ "Transparently", "decrypt", "an", "item", "after", "getting", "it", "from", "the", "table", "." ]
8de3bbe13df39c59b21bf431010f7acfcf629a2f
https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/utils.py#L197-L217
train
31,100
aws/aws-dynamodb-encryption-python
src/dynamodb_encryption_sdk/internal/utils.py
decrypt_batch_get_item
def decrypt_batch_get_item(decrypt_method, crypto_config_method, read_method, **kwargs): # type: (Callable, Callable, Callable, **Any) -> Dict # TODO: narrow this down """Transparently decrypt multiple items after getting them in a batch request. :param callable decrypt_method: Method to use to decrypt items :param callable crypto_config_method: Method that accepts ``kwargs`` and provides a :class:`CryptoConfig` :param callable read_method: Method that reads from the table :param **kwargs: Keyword arguments to pass to ``read_method`` :return: DynamoDB response :rtype: dict """ request_crypto_config = kwargs.pop("crypto_config", None) for _table_name, table_kwargs in kwargs["RequestItems"].items(): validate_get_arguments(table_kwargs) response = read_method(**kwargs) for table_name, items in response["Responses"].items(): if request_crypto_config is not None: crypto_config = request_crypto_config else: crypto_config = crypto_config_method(table_name=table_name) for pos, value in enumerate(items): items[pos] = decrypt_method( item=value, crypto_config=crypto_config.with_item(_item_transformer(decrypt_method)(items[pos])) ) return response
python
def decrypt_batch_get_item(decrypt_method, crypto_config_method, read_method, **kwargs): # type: (Callable, Callable, Callable, **Any) -> Dict # TODO: narrow this down """Transparently decrypt multiple items after getting them in a batch request. :param callable decrypt_method: Method to use to decrypt items :param callable crypto_config_method: Method that accepts ``kwargs`` and provides a :class:`CryptoConfig` :param callable read_method: Method that reads from the table :param **kwargs: Keyword arguments to pass to ``read_method`` :return: DynamoDB response :rtype: dict """ request_crypto_config = kwargs.pop("crypto_config", None) for _table_name, table_kwargs in kwargs["RequestItems"].items(): validate_get_arguments(table_kwargs) response = read_method(**kwargs) for table_name, items in response["Responses"].items(): if request_crypto_config is not None: crypto_config = request_crypto_config else: crypto_config = crypto_config_method(table_name=table_name) for pos, value in enumerate(items): items[pos] = decrypt_method( item=value, crypto_config=crypto_config.with_item(_item_transformer(decrypt_method)(items[pos])) ) return response
[ "def", "decrypt_batch_get_item", "(", "decrypt_method", ",", "crypto_config_method", ",", "read_method", ",", "*", "*", "kwargs", ")", ":", "# type: (Callable, Callable, Callable, **Any) -> Dict", "# TODO: narrow this down", "request_crypto_config", "=", "kwargs", ".", "pop",...
Transparently decrypt multiple items after getting them in a batch request. :param callable decrypt_method: Method to use to decrypt items :param callable crypto_config_method: Method that accepts ``kwargs`` and provides a :class:`CryptoConfig` :param callable read_method: Method that reads from the table :param **kwargs: Keyword arguments to pass to ``read_method`` :return: DynamoDB response :rtype: dict
[ "Transparently", "decrypt", "multiple", "items", "after", "getting", "them", "in", "a", "batch", "request", "." ]
8de3bbe13df39c59b21bf431010f7acfcf629a2f
https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/utils.py#L220-L248
train
31,101
aws/aws-dynamodb-encryption-python
src/dynamodb_encryption_sdk/internal/utils.py
encrypt_put_item
def encrypt_put_item(encrypt_method, crypto_config_method, write_method, **kwargs): # type: (Callable, Callable, Callable, **Any) -> Dict # TODO: narrow this down """Transparently encrypt an item before putting it to the table. :param callable encrypt_method: Method to use to encrypt items :param callable crypto_config_method: Method that accepts ``kwargs`` and provides a :class:`CryptoConfig` :param callable write_method: Method that writes to the table :param **kwargs: Keyword arguments to pass to ``write_method`` :return: DynamoDB response :rtype: dict """ crypto_config, ddb_kwargs = crypto_config_method(**kwargs) ddb_kwargs["Item"] = encrypt_method( item=ddb_kwargs["Item"], crypto_config=crypto_config.with_item(_item_transformer(encrypt_method)(ddb_kwargs["Item"])), ) return write_method(**ddb_kwargs)
python
def encrypt_put_item(encrypt_method, crypto_config_method, write_method, **kwargs): # type: (Callable, Callable, Callable, **Any) -> Dict # TODO: narrow this down """Transparently encrypt an item before putting it to the table. :param callable encrypt_method: Method to use to encrypt items :param callable crypto_config_method: Method that accepts ``kwargs`` and provides a :class:`CryptoConfig` :param callable write_method: Method that writes to the table :param **kwargs: Keyword arguments to pass to ``write_method`` :return: DynamoDB response :rtype: dict """ crypto_config, ddb_kwargs = crypto_config_method(**kwargs) ddb_kwargs["Item"] = encrypt_method( item=ddb_kwargs["Item"], crypto_config=crypto_config.with_item(_item_transformer(encrypt_method)(ddb_kwargs["Item"])), ) return write_method(**ddb_kwargs)
[ "def", "encrypt_put_item", "(", "encrypt_method", ",", "crypto_config_method", ",", "write_method", ",", "*", "*", "kwargs", ")", ":", "# type: (Callable, Callable, Callable, **Any) -> Dict", "# TODO: narrow this down", "crypto_config", ",", "ddb_kwargs", "=", "crypto_config_...
Transparently encrypt an item before putting it to the table. :param callable encrypt_method: Method to use to encrypt items :param callable crypto_config_method: Method that accepts ``kwargs`` and provides a :class:`CryptoConfig` :param callable write_method: Method that writes to the table :param **kwargs: Keyword arguments to pass to ``write_method`` :return: DynamoDB response :rtype: dict
[ "Transparently", "encrypt", "an", "item", "before", "putting", "it", "to", "the", "table", "." ]
8de3bbe13df39c59b21bf431010f7acfcf629a2f
https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/utils.py#L251-L268
train
31,102
aws/aws-dynamodb-encryption-python
src/dynamodb_encryption_sdk/internal/utils.py
encrypt_batch_write_item
def encrypt_batch_write_item(encrypt_method, crypto_config_method, write_method, **kwargs): # type: (Callable, Callable, Callable, **Any) -> Dict # TODO: narrow this down """Transparently encrypt multiple items before putting them in a batch request. :param callable encrypt_method: Method to use to encrypt items :param callable crypto_config_method: Method that accepts a table name string and provides a :class:`CryptoConfig` :param callable write_method: Method that writes to the table :param **kwargs: Keyword arguments to pass to ``write_method`` :return: DynamoDB response :rtype: dict """ request_crypto_config = kwargs.pop("crypto_config", None) table_crypto_configs = {} plaintext_items = copy.deepcopy(kwargs["RequestItems"]) for table_name, items in kwargs["RequestItems"].items(): if request_crypto_config is not None: crypto_config = request_crypto_config else: crypto_config = crypto_config_method(table_name=table_name) table_crypto_configs[table_name] = crypto_config for pos, value in enumerate(items): for request_type, item in value.items(): # We don't encrypt primary indexes, so we can ignore DeleteItem requests if request_type == "PutRequest": items[pos][request_type]["Item"] = encrypt_method( item=item["Item"], crypto_config=crypto_config.with_item(_item_transformer(encrypt_method)(item["Item"])), ) response = write_method(**kwargs) return _process_batch_write_response(plaintext_items, response, table_crypto_configs)
python
def encrypt_batch_write_item(encrypt_method, crypto_config_method, write_method, **kwargs): # type: (Callable, Callable, Callable, **Any) -> Dict # TODO: narrow this down """Transparently encrypt multiple items before putting them in a batch request. :param callable encrypt_method: Method to use to encrypt items :param callable crypto_config_method: Method that accepts a table name string and provides a :class:`CryptoConfig` :param callable write_method: Method that writes to the table :param **kwargs: Keyword arguments to pass to ``write_method`` :return: DynamoDB response :rtype: dict """ request_crypto_config = kwargs.pop("crypto_config", None) table_crypto_configs = {} plaintext_items = copy.deepcopy(kwargs["RequestItems"]) for table_name, items in kwargs["RequestItems"].items(): if request_crypto_config is not None: crypto_config = request_crypto_config else: crypto_config = crypto_config_method(table_name=table_name) table_crypto_configs[table_name] = crypto_config for pos, value in enumerate(items): for request_type, item in value.items(): # We don't encrypt primary indexes, so we can ignore DeleteItem requests if request_type == "PutRequest": items[pos][request_type]["Item"] = encrypt_method( item=item["Item"], crypto_config=crypto_config.with_item(_item_transformer(encrypt_method)(item["Item"])), ) response = write_method(**kwargs) return _process_batch_write_response(plaintext_items, response, table_crypto_configs)
[ "def", "encrypt_batch_write_item", "(", "encrypt_method", ",", "crypto_config_method", ",", "write_method", ",", "*", "*", "kwargs", ")", ":", "# type: (Callable, Callable, Callable, **Any) -> Dict", "# TODO: narrow this down", "request_crypto_config", "=", "kwargs", ".", "po...
Transparently encrypt multiple items before putting them in a batch request. :param callable encrypt_method: Method to use to encrypt items :param callable crypto_config_method: Method that accepts a table name string and provides a :class:`CryptoConfig` :param callable write_method: Method that writes to the table :param **kwargs: Keyword arguments to pass to ``write_method`` :return: DynamoDB response :rtype: dict
[ "Transparently", "encrypt", "multiple", "items", "before", "putting", "them", "in", "a", "batch", "request", "." ]
8de3bbe13df39c59b21bf431010f7acfcf629a2f
https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/utils.py#L271-L304
train
31,103
aws/aws-dynamodb-encryption-python
src/dynamodb_encryption_sdk/internal/utils.py
_process_batch_write_response
def _process_batch_write_response(request, response, table_crypto_config): # type: (Dict, Dict, Dict[Text, CryptoConfig]) -> Dict """Handle unprocessed items in the response from a transparently encrypted write. :param dict request: The DynamoDB plaintext request dictionary :param dict response: The DynamoDB response from the batch operation :param Dict[Text, CryptoConfig] table_crypto_config: table level CryptoConfig used in encrypting the request items :return: DynamoDB response, with any unprocessed items reverted back to the original plaintext values :rtype: dict """ try: unprocessed_items = response["UnprocessedItems"] except KeyError: return response # Unprocessed items need to be returned in their original state for table_name, unprocessed in unprocessed_items.items(): original_items = request[table_name] crypto_config = table_crypto_config[table_name] if crypto_config.encryption_context.partition_key_name: items_match = partial(_item_keys_match, crypto_config) else: items_match = partial(_item_attributes_match, crypto_config) for pos, operation in enumerate(unprocessed): for request_type, item in operation.items(): if request_type != "PutRequest": continue for plaintext_item in original_items: if plaintext_item.get(request_type) and items_match( plaintext_item[request_type]["Item"], item["Item"] ): unprocessed[pos] = plaintext_item.copy() break return response
python
def _process_batch_write_response(request, response, table_crypto_config): # type: (Dict, Dict, Dict[Text, CryptoConfig]) -> Dict """Handle unprocessed items in the response from a transparently encrypted write. :param dict request: The DynamoDB plaintext request dictionary :param dict response: The DynamoDB response from the batch operation :param Dict[Text, CryptoConfig] table_crypto_config: table level CryptoConfig used in encrypting the request items :return: DynamoDB response, with any unprocessed items reverted back to the original plaintext values :rtype: dict """ try: unprocessed_items = response["UnprocessedItems"] except KeyError: return response # Unprocessed items need to be returned in their original state for table_name, unprocessed in unprocessed_items.items(): original_items = request[table_name] crypto_config = table_crypto_config[table_name] if crypto_config.encryption_context.partition_key_name: items_match = partial(_item_keys_match, crypto_config) else: items_match = partial(_item_attributes_match, crypto_config) for pos, operation in enumerate(unprocessed): for request_type, item in operation.items(): if request_type != "PutRequest": continue for plaintext_item in original_items: if plaintext_item.get(request_type) and items_match( plaintext_item[request_type]["Item"], item["Item"] ): unprocessed[pos] = plaintext_item.copy() break return response
[ "def", "_process_batch_write_response", "(", "request", ",", "response", ",", "table_crypto_config", ")", ":", "# type: (Dict, Dict, Dict[Text, CryptoConfig]) -> Dict", "try", ":", "unprocessed_items", "=", "response", "[", "\"UnprocessedItems\"", "]", "except", "KeyError", ...
Handle unprocessed items in the response from a transparently encrypted write. :param dict request: The DynamoDB plaintext request dictionary :param dict response: The DynamoDB response from the batch operation :param Dict[Text, CryptoConfig] table_crypto_config: table level CryptoConfig used in encrypting the request items :return: DynamoDB response, with any unprocessed items reverted back to the original plaintext values :rtype: dict
[ "Handle", "unprocessed", "items", "in", "the", "response", "from", "a", "transparently", "encrypted", "write", "." ]
8de3bbe13df39c59b21bf431010f7acfcf629a2f
https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/utils.py#L307-L344
train
31,104
aws/aws-dynamodb-encryption-python
src/dynamodb_encryption_sdk/internal/utils.py
_item_attributes_match
def _item_attributes_match(crypto_config, plaintext_item, encrypted_item): # type: (CryptoConfig, Dict, Dict) -> Bool """Determines whether the unencrypted values in the plaintext items attributes are the same as those in the encrypted item. Essentially this uses brute force to cover when we don't know the primary and sort index attribute names, since they can't be encrypted. :param CryptoConfig crypto_config: CryptoConfig used in encrypting the given items :param dict plaintext_item: The plaintext item :param dict encrypted_item: The encrypted item :return: Bool response, True if the unencrypted attributes in the plaintext item match those in the encrypted item :rtype: bool """ for name, value in plaintext_item.items(): if crypto_config.attribute_actions.action(name) == CryptoAction.ENCRYPT_AND_SIGN: continue if encrypted_item.get(name) != value: return False return True
python
def _item_attributes_match(crypto_config, plaintext_item, encrypted_item): # type: (CryptoConfig, Dict, Dict) -> Bool """Determines whether the unencrypted values in the plaintext items attributes are the same as those in the encrypted item. Essentially this uses brute force to cover when we don't know the primary and sort index attribute names, since they can't be encrypted. :param CryptoConfig crypto_config: CryptoConfig used in encrypting the given items :param dict plaintext_item: The plaintext item :param dict encrypted_item: The encrypted item :return: Bool response, True if the unencrypted attributes in the plaintext item match those in the encrypted item :rtype: bool """ for name, value in plaintext_item.items(): if crypto_config.attribute_actions.action(name) == CryptoAction.ENCRYPT_AND_SIGN: continue if encrypted_item.get(name) != value: return False return True
[ "def", "_item_attributes_match", "(", "crypto_config", ",", "plaintext_item", ",", "encrypted_item", ")", ":", "# type: (CryptoConfig, Dict, Dict) -> Bool", "for", "name", ",", "value", "in", "plaintext_item", ".", "items", "(", ")", ":", "if", "crypto_config", ".", ...
Determines whether the unencrypted values in the plaintext items attributes are the same as those in the encrypted item. Essentially this uses brute force to cover when we don't know the primary and sort index attribute names, since they can't be encrypted. :param CryptoConfig crypto_config: CryptoConfig used in encrypting the given items :param dict plaintext_item: The plaintext item :param dict encrypted_item: The encrypted item :return: Bool response, True if the unencrypted attributes in the plaintext item match those in the encrypted item :rtype: bool
[ "Determines", "whether", "the", "unencrypted", "values", "in", "the", "plaintext", "items", "attributes", "are", "the", "same", "as", "those", "in", "the", "encrypted", "item", ".", "Essentially", "this", "uses", "brute", "force", "to", "cover", "when", "we", ...
8de3bbe13df39c59b21bf431010f7acfcf629a2f
https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/utils.py#L368-L389
train
31,105
Mic92/python-mpd2
mpd/asyncio.py
CommandResult._feed_line
def _feed_line(self, line): """Put the given line into the callback machinery, and set the result on a None line.""" if line is None: self.set_result(self._callback(self.__spooled_lines)) else: self.__spooled_lines.append(line)
python
def _feed_line(self, line): """Put the given line into the callback machinery, and set the result on a None line.""" if line is None: self.set_result(self._callback(self.__spooled_lines)) else: self.__spooled_lines.append(line)
[ "def", "_feed_line", "(", "self", ",", "line", ")", ":", "if", "line", "is", "None", ":", "self", ".", "set_result", "(", "self", ".", "_callback", "(", "self", ".", "__spooled_lines", ")", ")", "else", ":", "self", ".", "__spooled_lines", ".", "append...
Put the given line into the callback machinery, and set the result on a None line.
[ "Put", "the", "given", "line", "into", "the", "callback", "machinery", "and", "set", "the", "result", "on", "a", "None", "line", "." ]
fc2782009915d9b642ceef6e4d3b52fa6168998b
https://github.com/Mic92/python-mpd2/blob/fc2782009915d9b642ceef6e4d3b52fa6168998b/mpd/asyncio.py#L45-L50
train
31,106
Mic92/python-mpd2
mpd/base.py
mpd_command_provider
def mpd_command_provider(cls): """Decorator hooking up registered MPD commands to concrete client implementation. A class using this decorator must inherit from ``MPDClientBase`` and implement it's ``add_command`` function. """ def collect(cls, callbacks=dict()): """Collect MPD command callbacks from given class. Searches class __dict__ on given class and all it's bases for functions which have been decorated with @mpd_commands and returns a dict containing callback name as keys and (callback, callback implementing class) tuples as values. """ for name, ob in cls.__dict__.items(): if hasattr(ob, "mpd_commands") and name not in callbacks: callbacks[name] = (ob, cls) for base in cls.__bases__: callbacks = collect(base, callbacks) return callbacks for name, value in collect(cls).items(): callback, from_ = value for command in callback.mpd_commands: cls.add_command(command, callback) return cls
python
def mpd_command_provider(cls): """Decorator hooking up registered MPD commands to concrete client implementation. A class using this decorator must inherit from ``MPDClientBase`` and implement it's ``add_command`` function. """ def collect(cls, callbacks=dict()): """Collect MPD command callbacks from given class. Searches class __dict__ on given class and all it's bases for functions which have been decorated with @mpd_commands and returns a dict containing callback name as keys and (callback, callback implementing class) tuples as values. """ for name, ob in cls.__dict__.items(): if hasattr(ob, "mpd_commands") and name not in callbacks: callbacks[name] = (ob, cls) for base in cls.__bases__: callbacks = collect(base, callbacks) return callbacks for name, value in collect(cls).items(): callback, from_ = value for command in callback.mpd_commands: cls.add_command(command, callback) return cls
[ "def", "mpd_command_provider", "(", "cls", ")", ":", "def", "collect", "(", "cls", ",", "callbacks", "=", "dict", "(", ")", ")", ":", "\"\"\"Collect MPD command callbacks from given class.\n\n Searches class __dict__ on given class and all it's bases for functions\n ...
Decorator hooking up registered MPD commands to concrete client implementation. A class using this decorator must inherit from ``MPDClientBase`` and implement it's ``add_command`` function.
[ "Decorator", "hooking", "up", "registered", "MPD", "commands", "to", "concrete", "client", "implementation", "." ]
fc2782009915d9b642ceef6e4d3b52fa6168998b
https://github.com/Mic92/python-mpd2/blob/fc2782009915d9b642ceef6e4d3b52fa6168998b/mpd/base.py#L133-L159
train
31,107
Mic92/python-mpd2
mpd/base.py
_create_callback
def _create_callback(self, function, wrap_result): """Create MPD command related response callback. """ if not isinstance(function, Callable): return None def command_callback(): # command result callback expects response from MPD as iterable lines, # thus read available lines from socket res = function(self, self._read_lines()) # wrap result in iterator helper if desired if wrap_result: res = self._wrap_iterator(res) return res return command_callback
python
def _create_callback(self, function, wrap_result): """Create MPD command related response callback. """ if not isinstance(function, Callable): return None def command_callback(): # command result callback expects response from MPD as iterable lines, # thus read available lines from socket res = function(self, self._read_lines()) # wrap result in iterator helper if desired if wrap_result: res = self._wrap_iterator(res) return res return command_callback
[ "def", "_create_callback", "(", "self", ",", "function", ",", "wrap_result", ")", ":", "if", "not", "isinstance", "(", "function", ",", "Callable", ")", ":", "return", "None", "def", "command_callback", "(", ")", ":", "# command result callback expects response fr...
Create MPD command related response callback.
[ "Create", "MPD", "command", "related", "response", "callback", "." ]
fc2782009915d9b642ceef6e4d3b52fa6168998b
https://github.com/Mic92/python-mpd2/blob/fc2782009915d9b642ceef6e4d3b52fa6168998b/mpd/base.py#L360-L373
train
31,108
Mic92/python-mpd2
mpd/base.py
_create_command
def _create_command(wrapper, name, return_value, wrap_result): """Create MPD command related function. """ def mpd_command(self, *args): callback = _create_callback(self, return_value, wrap_result) return wrapper(self, name, args, callback) return mpd_command
python
def _create_command(wrapper, name, return_value, wrap_result): """Create MPD command related function. """ def mpd_command(self, *args): callback = _create_callback(self, return_value, wrap_result) return wrapper(self, name, args, callback) return mpd_command
[ "def", "_create_command", "(", "wrapper", ",", "name", ",", "return_value", ",", "wrap_result", ")", ":", "def", "mpd_command", "(", "self", ",", "*", "args", ")", ":", "callback", "=", "_create_callback", "(", "self", ",", "return_value", ",", "wrap_result"...
Create MPD command related function.
[ "Create", "MPD", "command", "related", "function", "." ]
fc2782009915d9b642ceef6e4d3b52fa6168998b
https://github.com/Mic92/python-mpd2/blob/fc2782009915d9b642ceef6e4d3b52fa6168998b/mpd/base.py#L376-L382
train
31,109
naught101/sobol_seq
sobol_seq/sobol_seq.py
i4_bit_hi1
def i4_bit_hi1(n): """ i4_bit_hi1 returns the position of the high 1 bit base 2 in an integer. Example: +------+-------------+----- | N | Binary | BIT +------|-------------+----- | 0 | 0 | 0 | 1 | 1 | 1 | 2 | 10 | 2 | 3 | 11 | 2 | 4 | 100 | 3 | 5 | 101 | 3 | 6 | 110 | 3 | 7 | 111 | 3 | 8 | 1000 | 4 | 9 | 1001 | 4 | 10 | 1010 | 4 | 11 | 1011 | 4 | 12 | 1100 | 4 | 13 | 1101 | 4 | 14 | 1110 | 4 | 15 | 1111 | 4 | 16 | 10000 | 5 | 17 | 10001 | 5 | 1023 | 1111111111 | 10 | 1024 | 10000000000 | 11 | 1025 | 10000000001 | 11 Parameters: Input, integer N, the integer to be measured. N should be nonnegative. If N is nonpositive, the value will always be 0. Output, integer BIT, the number of bits base 2. """ i = np.floor(n) bit = 0 while i > 0: bit += 1 i //= 2 return bit
python
def i4_bit_hi1(n): """ i4_bit_hi1 returns the position of the high 1 bit base 2 in an integer. Example: +------+-------------+----- | N | Binary | BIT +------|-------------+----- | 0 | 0 | 0 | 1 | 1 | 1 | 2 | 10 | 2 | 3 | 11 | 2 | 4 | 100 | 3 | 5 | 101 | 3 | 6 | 110 | 3 | 7 | 111 | 3 | 8 | 1000 | 4 | 9 | 1001 | 4 | 10 | 1010 | 4 | 11 | 1011 | 4 | 12 | 1100 | 4 | 13 | 1101 | 4 | 14 | 1110 | 4 | 15 | 1111 | 4 | 16 | 10000 | 5 | 17 | 10001 | 5 | 1023 | 1111111111 | 10 | 1024 | 10000000000 | 11 | 1025 | 10000000001 | 11 Parameters: Input, integer N, the integer to be measured. N should be nonnegative. If N is nonpositive, the value will always be 0. Output, integer BIT, the number of bits base 2. """ i = np.floor(n) bit = 0 while i > 0: bit += 1 i //= 2 return bit
[ "def", "i4_bit_hi1", "(", "n", ")", ":", "i", "=", "np", ".", "floor", "(", "n", ")", "bit", "=", "0", "while", "i", ">", "0", ":", "bit", "+=", "1", "i", "//=", "2", "return", "bit" ]
i4_bit_hi1 returns the position of the high 1 bit base 2 in an integer. Example: +------+-------------+----- | N | Binary | BIT +------|-------------+----- | 0 | 0 | 0 | 1 | 1 | 1 | 2 | 10 | 2 | 3 | 11 | 2 | 4 | 100 | 3 | 5 | 101 | 3 | 6 | 110 | 3 | 7 | 111 | 3 | 8 | 1000 | 4 | 9 | 1001 | 4 | 10 | 1010 | 4 | 11 | 1011 | 4 | 12 | 1100 | 4 | 13 | 1101 | 4 | 14 | 1110 | 4 | 15 | 1111 | 4 | 16 | 10000 | 5 | 17 | 10001 | 5 | 1023 | 1111111111 | 10 | 1024 | 10000000000 | 11 | 1025 | 10000000001 | 11 Parameters: Input, integer N, the integer to be measured. N should be nonnegative. If N is nonpositive, the value will always be 0. Output, integer BIT, the number of bits base 2.
[ "i4_bit_hi1", "returns", "the", "position", "of", "the", "high", "1", "bit", "base", "2", "in", "an", "integer", "." ]
6ac1799818a1b9a359a5fc86517173584fe34613
https://github.com/naught101/sobol_seq/blob/6ac1799818a1b9a359a5fc86517173584fe34613/sobol_seq/sobol_seq.py#L26-L67
train
31,110
naught101/sobol_seq
sobol_seq/sobol_seq.py
i4_bit_lo0
def i4_bit_lo0(n): """ I4_BIT_LO0 returns the position of the low 0 bit base 2 in an integer. Example: +------+------------+---- | N | Binary | BIT +------+------------+---- | 0 | 0 | 1 | 1 | 1 | 2 | 2 | 10 | 1 | 3 | 11 | 3 | 4 | 100 | 1 | 5 | 101 | 2 | 6 | 110 | 1 | 7 | 111 | 4 | 8 | 1000 | 1 | 9 | 1001 | 2 | 10 | 1010 | 1 | 11 | 1011 | 3 | 12 | 1100 | 1 | 13 | 1101 | 2 | 14 | 1110 | 1 | 15 | 1111 | 5 | 16 | 10000 | 1 | 17 | 10001 | 2 | 1023 | 1111111111 | 1 | 1024 | 0000000000 | 1 | 1025 | 0000000001 | 1 Parameters: Input, integer N, the integer to be measured. N should be nonnegative. Output, integer BIT, the position of the low 1 bit. """ bit = 1 i = np.floor(n) while i != 2 * (i // 2): bit += 1 i //= 2 return bit
python
def i4_bit_lo0(n): """ I4_BIT_LO0 returns the position of the low 0 bit base 2 in an integer. Example: +------+------------+---- | N | Binary | BIT +------+------------+---- | 0 | 0 | 1 | 1 | 1 | 2 | 2 | 10 | 1 | 3 | 11 | 3 | 4 | 100 | 1 | 5 | 101 | 2 | 6 | 110 | 1 | 7 | 111 | 4 | 8 | 1000 | 1 | 9 | 1001 | 2 | 10 | 1010 | 1 | 11 | 1011 | 3 | 12 | 1100 | 1 | 13 | 1101 | 2 | 14 | 1110 | 1 | 15 | 1111 | 5 | 16 | 10000 | 1 | 17 | 10001 | 2 | 1023 | 1111111111 | 1 | 1024 | 0000000000 | 1 | 1025 | 0000000001 | 1 Parameters: Input, integer N, the integer to be measured. N should be nonnegative. Output, integer BIT, the position of the low 1 bit. """ bit = 1 i = np.floor(n) while i != 2 * (i // 2): bit += 1 i //= 2 return bit
[ "def", "i4_bit_lo0", "(", "n", ")", ":", "bit", "=", "1", "i", "=", "np", ".", "floor", "(", "n", ")", "while", "i", "!=", "2", "*", "(", "i", "//", "2", ")", ":", "bit", "+=", "1", "i", "//=", "2", "return", "bit" ]
I4_BIT_LO0 returns the position of the low 0 bit base 2 in an integer. Example: +------+------------+---- | N | Binary | BIT +------+------------+---- | 0 | 0 | 1 | 1 | 1 | 2 | 2 | 10 | 1 | 3 | 11 | 3 | 4 | 100 | 1 | 5 | 101 | 2 | 6 | 110 | 1 | 7 | 111 | 4 | 8 | 1000 | 1 | 9 | 1001 | 2 | 10 | 1010 | 1 | 11 | 1011 | 3 | 12 | 1100 | 1 | 13 | 1101 | 2 | 14 | 1110 | 1 | 15 | 1111 | 5 | 16 | 10000 | 1 | 17 | 10001 | 2 | 1023 | 1111111111 | 1 | 1024 | 0000000000 | 1 | 1025 | 0000000001 | 1 Parameters: Input, integer N, the integer to be measured. N should be nonnegative. Output, integer BIT, the position of the low 1 bit.
[ "I4_BIT_LO0", "returns", "the", "position", "of", "the", "low", "0", "bit", "base", "2", "in", "an", "integer", "." ]
6ac1799818a1b9a359a5fc86517173584fe34613
https://github.com/naught101/sobol_seq/blob/6ac1799818a1b9a359a5fc86517173584fe34613/sobol_seq/sobol_seq.py#L70-L111
train
31,111
naught101/sobol_seq
sobol_seq/sobol_seq.py
i4_sobol_generate
def i4_sobol_generate(dim_num, n, skip=1): """ i4_sobol_generate generates a Sobol dataset. Parameters: Input, integer dim_num, the spatial dimension. Input, integer N, the number of points to generate. Input, integer SKIP, the number of initial points to skip. Output, real R(M,N), the points. """ r = np.full((n, dim_num), np.nan) for j in range(n): seed = j + skip r[j, 0:dim_num], next_seed = i4_sobol(dim_num, seed) return r
python
def i4_sobol_generate(dim_num, n, skip=1): """ i4_sobol_generate generates a Sobol dataset. Parameters: Input, integer dim_num, the spatial dimension. Input, integer N, the number of points to generate. Input, integer SKIP, the number of initial points to skip. Output, real R(M,N), the points. """ r = np.full((n, dim_num), np.nan) for j in range(n): seed = j + skip r[j, 0:dim_num], next_seed = i4_sobol(dim_num, seed) return r
[ "def", "i4_sobol_generate", "(", "dim_num", ",", "n", ",", "skip", "=", "1", ")", ":", "r", "=", "np", ".", "full", "(", "(", "n", ",", "dim_num", ")", ",", "np", ".", "nan", ")", "for", "j", "in", "range", "(", "n", ")", ":", "seed", "=", ...
i4_sobol_generate generates a Sobol dataset. Parameters: Input, integer dim_num, the spatial dimension. Input, integer N, the number of points to generate. Input, integer SKIP, the number of initial points to skip. Output, real R(M,N), the points.
[ "i4_sobol_generate", "generates", "a", "Sobol", "dataset", "." ]
6ac1799818a1b9a359a5fc86517173584fe34613
https://github.com/naught101/sobol_seq/blob/6ac1799818a1b9a359a5fc86517173584fe34613/sobol_seq/sobol_seq.py#L114-L130
train
31,112
naught101/sobol_seq
sobol_seq/sobol_seq.py
i4_sobol_generate_std_normal
def i4_sobol_generate_std_normal(dim_num, n, skip=1): """ Generates multivariate standard normal quasi-random variables. Parameters: Input, integer dim_num, the spatial dimension. Input, integer n, the number of points to generate. Input, integer SKIP, the number of initial points to skip. Output, real np array of shape (n, dim_num). """ sobols = i4_sobol_generate(dim_num, n, skip) normals = norm.ppf(sobols) return normals
python
def i4_sobol_generate_std_normal(dim_num, n, skip=1): """ Generates multivariate standard normal quasi-random variables. Parameters: Input, integer dim_num, the spatial dimension. Input, integer n, the number of points to generate. Input, integer SKIP, the number of initial points to skip. Output, real np array of shape (n, dim_num). """ sobols = i4_sobol_generate(dim_num, n, skip) normals = norm.ppf(sobols) return normals
[ "def", "i4_sobol_generate_std_normal", "(", "dim_num", ",", "n", ",", "skip", "=", "1", ")", ":", "sobols", "=", "i4_sobol_generate", "(", "dim_num", ",", "n", ",", "skip", ")", "normals", "=", "norm", ".", "ppf", "(", "sobols", ")", "return", "normals" ...
Generates multivariate standard normal quasi-random variables. Parameters: Input, integer dim_num, the spatial dimension. Input, integer n, the number of points to generate. Input, integer SKIP, the number of initial points to skip. Output, real np array of shape (n, dim_num).
[ "Generates", "multivariate", "standard", "normal", "quasi", "-", "random", "variables", "." ]
6ac1799818a1b9a359a5fc86517173584fe34613
https://github.com/naught101/sobol_seq/blob/6ac1799818a1b9a359a5fc86517173584fe34613/sobol_seq/sobol_seq.py#L133-L149
train
31,113
naught101/sobol_seq
sobol_seq/sobol_seq.py
i4_uniform
def i4_uniform(a, b, seed): """ i4_uniform returns a scaled pseudorandom I4. Discussion: The pseudorandom number will be scaled to be uniformly distributed between A and B. Reference: Paul Bratley, Bennett Fox, Linus Schrage, A Guide to Simulation, Springer Verlag, pages 201-202, 1983. Pierre L'Ecuyer, Random Number Generation, in Handbook of Simulation, edited by Jerry Banks, Wiley Interscience, page 95, 1998. Bennett Fox, Algorithm 647: Implementation and Relative Efficiency of Quasirandom Sequence Generators, ACM Transactions on Mathematical Software, Volume 12, Number 4, pages 362-376, 1986. Peter Lewis, Allen Goodman, James Miller A Pseudo-Random Number Generator for the System/360, IBM Systems Journal, Volume 8, pages 136-143, 1969. Parameters: Input, integer A, B, the minimum and maximum acceptable values. Input, integer SEED, a seed for the random number generator. Output, integer C, the randomly chosen integer. Output, integer SEED, the updated seed. """ if seed == 0: print('I4_UNIFORM - Fatal error!') print(' Input SEED = 0!') seed = np.floor(seed) a = round(a) b = round(b) seed = np.mod(seed, 2147483647) if seed < 0: seed += 2147483647 k = seed // 127773 seed = 16807 * (seed - k * 127773) - k * 2836 if seed < 0: seed += 2147483647 r = seed * 4.656612875E-10 # Scale R to lie between A-0.5 and B+0.5. r = (1.0 - r) * (min(a, b) - 0.5) + r * (max(a, b) + 0.5) # Use rounding to convert R to an integer between A and B. value = round(r) value = max(value, min(a, b)) value = min(value, max(a, b)) c = value return [int(c), int(seed)]
python
def i4_uniform(a, b, seed): """ i4_uniform returns a scaled pseudorandom I4. Discussion: The pseudorandom number will be scaled to be uniformly distributed between A and B. Reference: Paul Bratley, Bennett Fox, Linus Schrage, A Guide to Simulation, Springer Verlag, pages 201-202, 1983. Pierre L'Ecuyer, Random Number Generation, in Handbook of Simulation, edited by Jerry Banks, Wiley Interscience, page 95, 1998. Bennett Fox, Algorithm 647: Implementation and Relative Efficiency of Quasirandom Sequence Generators, ACM Transactions on Mathematical Software, Volume 12, Number 4, pages 362-376, 1986. Peter Lewis, Allen Goodman, James Miller A Pseudo-Random Number Generator for the System/360, IBM Systems Journal, Volume 8, pages 136-143, 1969. Parameters: Input, integer A, B, the minimum and maximum acceptable values. Input, integer SEED, a seed for the random number generator. Output, integer C, the randomly chosen integer. Output, integer SEED, the updated seed. """ if seed == 0: print('I4_UNIFORM - Fatal error!') print(' Input SEED = 0!') seed = np.floor(seed) a = round(a) b = round(b) seed = np.mod(seed, 2147483647) if seed < 0: seed += 2147483647 k = seed // 127773 seed = 16807 * (seed - k * 127773) - k * 2836 if seed < 0: seed += 2147483647 r = seed * 4.656612875E-10 # Scale R to lie between A-0.5 and B+0.5. r = (1.0 - r) * (min(a, b) - 0.5) + r * (max(a, b) + 0.5) # Use rounding to convert R to an integer between A and B. value = round(r) value = max(value, min(a, b)) value = min(value, max(a, b)) c = value return [int(c), int(seed)]
[ "def", "i4_uniform", "(", "a", ",", "b", ",", "seed", ")", ":", "if", "seed", "==", "0", ":", "print", "(", "'I4_UNIFORM - Fatal error!'", ")", "print", "(", "' Input SEED = 0!'", ")", "seed", "=", "np", ".", "floor", "(", "seed", ")", "a", "=", "ro...
i4_uniform returns a scaled pseudorandom I4. Discussion: The pseudorandom number will be scaled to be uniformly distributed between A and B. Reference: Paul Bratley, Bennett Fox, Linus Schrage, A Guide to Simulation, Springer Verlag, pages 201-202, 1983. Pierre L'Ecuyer, Random Number Generation, in Handbook of Simulation, edited by Jerry Banks, Wiley Interscience, page 95, 1998. Bennett Fox, Algorithm 647: Implementation and Relative Efficiency of Quasirandom Sequence Generators, ACM Transactions on Mathematical Software, Volume 12, Number 4, pages 362-376, 1986. Peter Lewis, Allen Goodman, James Miller A Pseudo-Random Number Generator for the System/360, IBM Systems Journal, Volume 8, pages 136-143, 1969. Parameters: Input, integer A, B, the minimum and maximum acceptable values. Input, integer SEED, a seed for the random number generator. Output, integer C, the randomly chosen integer. Output, integer SEED, the updated seed.
[ "i4_uniform", "returns", "a", "scaled", "pseudorandom", "I4", "." ]
6ac1799818a1b9a359a5fc86517173584fe34613
https://github.com/naught101/sobol_seq/blob/6ac1799818a1b9a359a5fc86517173584fe34613/sobol_seq/sobol_seq.py#L397-L468
train
31,114
naught101/sobol_seq
sobol_seq/sobol_seq.py
prime_ge
def prime_ge(n): """ PRIME_GE returns the smallest prime greater than or equal to N. Example: +-----+--------- | N | PRIME_GE +-----+--------- | -10 | 2 | 1 | 2 | 2 | 2 | 3 | 3 | 4 | 5 | 5 | 5 | 6 | 7 | 7 | 7 | 8 | 11 | 9 | 11 | 10 | 11 Parameters: Input, integer N, the number to be bounded. Output, integer P, the smallest prime number that is greater than or equal to N. """ p = max(np.ceil(n), 2) while not is_prime(p): p += 1 return p
python
def prime_ge(n): """ PRIME_GE returns the smallest prime greater than or equal to N. Example: +-----+--------- | N | PRIME_GE +-----+--------- | -10 | 2 | 1 | 2 | 2 | 2 | 3 | 3 | 4 | 5 | 5 | 5 | 6 | 7 | 7 | 7 | 8 | 11 | 9 | 11 | 10 | 11 Parameters: Input, integer N, the number to be bounded. Output, integer P, the smallest prime number that is greater than or equal to N. """ p = max(np.ceil(n), 2) while not is_prime(p): p += 1 return p
[ "def", "prime_ge", "(", "n", ")", ":", "p", "=", "max", "(", "np", ".", "ceil", "(", "n", ")", ",", "2", ")", "while", "not", "is_prime", "(", "p", ")", ":", "p", "+=", "1", "return", "p" ]
PRIME_GE returns the smallest prime greater than or equal to N. Example: +-----+--------- | N | PRIME_GE +-----+--------- | -10 | 2 | 1 | 2 | 2 | 2 | 3 | 3 | 4 | 5 | 5 | 5 | 6 | 7 | 7 | 7 | 8 | 11 | 9 | 11 | 10 | 11 Parameters: Input, integer N, the number to be bounded. Output, integer P, the smallest prime number that is greater than or equal to N.
[ "PRIME_GE", "returns", "the", "smallest", "prime", "greater", "than", "or", "equal", "to", "N", "." ]
6ac1799818a1b9a359a5fc86517173584fe34613
https://github.com/naught101/sobol_seq/blob/6ac1799818a1b9a359a5fc86517173584fe34613/sobol_seq/sobol_seq.py#L471-L501
train
31,115
naught101/sobol_seq
sobol_seq/sobol_seq.py
is_prime
def is_prime(n): """ is_prime returns True if N is a prime number, False otherwise Parameters: Input, integer N, the number to be checked. Output, boolean value, True or False """ if n != int(n) or n < 2: return False if n == 2 or n == 3: return True if n % 2 == 0 or n % 3 == 0: return False # All primes >3 are of the form 6n+1 or 6n+5 (6n, 6n+2, 6n+4 are 2-divisible, 6n+3 is 3-divisible) p = 5 root = int(np.ceil(np.sqrt(n))) while p <= root: if n % p == 0 or n % (p + 2) == 0: return False p += 6 return True
python
def is_prime(n): """ is_prime returns True if N is a prime number, False otherwise Parameters: Input, integer N, the number to be checked. Output, boolean value, True or False """ if n != int(n) or n < 2: return False if n == 2 or n == 3: return True if n % 2 == 0 or n % 3 == 0: return False # All primes >3 are of the form 6n+1 or 6n+5 (6n, 6n+2, 6n+4 are 2-divisible, 6n+3 is 3-divisible) p = 5 root = int(np.ceil(np.sqrt(n))) while p <= root: if n % p == 0 or n % (p + 2) == 0: return False p += 6 return True
[ "def", "is_prime", "(", "n", ")", ":", "if", "n", "!=", "int", "(", "n", ")", "or", "n", "<", "2", ":", "return", "False", "if", "n", "==", "2", "or", "n", "==", "3", ":", "return", "True", "if", "n", "%", "2", "==", "0", "or", "n", "%", ...
is_prime returns True if N is a prime number, False otherwise Parameters: Input, integer N, the number to be checked. Output, boolean value, True or False
[ "is_prime", "returns", "True", "if", "N", "is", "a", "prime", "number", "False", "otherwise" ]
6ac1799818a1b9a359a5fc86517173584fe34613
https://github.com/naught101/sobol_seq/blob/6ac1799818a1b9a359a5fc86517173584fe34613/sobol_seq/sobol_seq.py#L504-L526
train
31,116
davedoesdev/python-jwt
python_jwt/__init__.py
generate_jwt
def generate_jwt(claims, priv_key=None, algorithm='PS512', lifetime=None, expires=None, not_before=None, jti_size=16, other_headers=None): """ Generate a JSON Web Token. :param claims: The claims you want included in the signature. :type claims: dict :param priv_key: The private key to be used to sign the token. Note: if you pass ``None`` then the token will be returned with an empty cryptographic signature and :obj:`algorithm` will be forced to the value ``none``. :type priv_key: `jwcrypto.jwk.JWK <https://jwcrypto.readthedocs.io/en/latest/jwk.html>`_ :param algorithm: The algorithm to use for generating the signature. ``RS256``, ``RS384``, ``RS512``, ``PS256``, ``PS384``, ``PS512``, ``ES256``, ``ES384``, ``ES512``, ``HS256``, ``HS384``, ``HS512`` and ``none`` are supported. :type algorithm: str :param lifetime: How long the token is valid for. :type lifetime: datetime.timedelta :param expires: When the token expires (if :obj:`lifetime` isn't specified) :type expires: datetime.datetime :param not_before: When the token is valid from. Defaults to current time (if ``None`` is passed). :type not_before: datetime.datetime :param jti_size: Size in bytes of the unique token ID to put into the token (can be used to detect replay attacks). Defaults to 16 (128 bits). Specify 0 or ``None`` to omit the JTI from the token. :type jti_size: int :param other_headers: Any headers other than "typ" and "alg" may be specified, they will be included in the header. :type other_headers: dict :rtype: unicode :returns: The JSON Web Token. Note this includes a header, the claims and a cryptographic signature. The following extra claims are added, per the `JWT spec <http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html>`_: - **exp** (*IntDate*) -- The UTC expiry date and time of the token, in number of seconds from 1970-01-01T0:0:0Z UTC. - **iat** (*IntDate*) -- The UTC date and time at which the token was generated. - **nbf** (*IntDate*) -- The UTC valid-from date and time of the token. - **jti** (*str*) -- A unique identifier for the token. :raises: ValueError: If other_headers contains either the "typ" or "alg" header """ header = { 'typ': 'JWT', 'alg': algorithm if priv_key else 'none' } if other_headers is not None: redefined_keys = set(header.keys()) & set(other_headers.keys()) if redefined_keys: raise ValueError('other_headers re-specified the headers: {}'.format(', '.join(redefined_keys))) header.update(other_headers) claims = dict(claims) now = datetime.utcnow() if jti_size: claims['jti'] = base64url_encode(urandom(jti_size)) claims['nbf'] = timegm((not_before or now).utctimetuple()) claims['iat'] = timegm(now.utctimetuple()) if lifetime: claims['exp'] = timegm((now + lifetime).utctimetuple()) elif expires: claims['exp'] = timegm(expires.utctimetuple()) if header['alg'] == 'none': signature = '' else: token = JWS(json_encode(claims)) token.add_signature(priv_key, protected=header) signature = json_decode(token.serialize())['signature'] return u'%s.%s.%s' % ( base64url_encode(json_encode(header)), base64url_encode(json_encode(claims)), signature )
python
def generate_jwt(claims, priv_key=None, algorithm='PS512', lifetime=None, expires=None, not_before=None, jti_size=16, other_headers=None): """ Generate a JSON Web Token. :param claims: The claims you want included in the signature. :type claims: dict :param priv_key: The private key to be used to sign the token. Note: if you pass ``None`` then the token will be returned with an empty cryptographic signature and :obj:`algorithm` will be forced to the value ``none``. :type priv_key: `jwcrypto.jwk.JWK <https://jwcrypto.readthedocs.io/en/latest/jwk.html>`_ :param algorithm: The algorithm to use for generating the signature. ``RS256``, ``RS384``, ``RS512``, ``PS256``, ``PS384``, ``PS512``, ``ES256``, ``ES384``, ``ES512``, ``HS256``, ``HS384``, ``HS512`` and ``none`` are supported. :type algorithm: str :param lifetime: How long the token is valid for. :type lifetime: datetime.timedelta :param expires: When the token expires (if :obj:`lifetime` isn't specified) :type expires: datetime.datetime :param not_before: When the token is valid from. Defaults to current time (if ``None`` is passed). :type not_before: datetime.datetime :param jti_size: Size in bytes of the unique token ID to put into the token (can be used to detect replay attacks). Defaults to 16 (128 bits). Specify 0 or ``None`` to omit the JTI from the token. :type jti_size: int :param other_headers: Any headers other than "typ" and "alg" may be specified, they will be included in the header. :type other_headers: dict :rtype: unicode :returns: The JSON Web Token. Note this includes a header, the claims and a cryptographic signature. The following extra claims are added, per the `JWT spec <http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html>`_: - **exp** (*IntDate*) -- The UTC expiry date and time of the token, in number of seconds from 1970-01-01T0:0:0Z UTC. - **iat** (*IntDate*) -- The UTC date and time at which the token was generated. - **nbf** (*IntDate*) -- The UTC valid-from date and time of the token. - **jti** (*str*) -- A unique identifier for the token. :raises: ValueError: If other_headers contains either the "typ" or "alg" header """ header = { 'typ': 'JWT', 'alg': algorithm if priv_key else 'none' } if other_headers is not None: redefined_keys = set(header.keys()) & set(other_headers.keys()) if redefined_keys: raise ValueError('other_headers re-specified the headers: {}'.format(', '.join(redefined_keys))) header.update(other_headers) claims = dict(claims) now = datetime.utcnow() if jti_size: claims['jti'] = base64url_encode(urandom(jti_size)) claims['nbf'] = timegm((not_before or now).utctimetuple()) claims['iat'] = timegm(now.utctimetuple()) if lifetime: claims['exp'] = timegm((now + lifetime).utctimetuple()) elif expires: claims['exp'] = timegm(expires.utctimetuple()) if header['alg'] == 'none': signature = '' else: token = JWS(json_encode(claims)) token.add_signature(priv_key, protected=header) signature = json_decode(token.serialize())['signature'] return u'%s.%s.%s' % ( base64url_encode(json_encode(header)), base64url_encode(json_encode(claims)), signature )
[ "def", "generate_jwt", "(", "claims", ",", "priv_key", "=", "None", ",", "algorithm", "=", "'PS512'", ",", "lifetime", "=", "None", ",", "expires", "=", "None", ",", "not_before", "=", "None", ",", "jti_size", "=", "16", ",", "other_headers", "=", "None"...
Generate a JSON Web Token. :param claims: The claims you want included in the signature. :type claims: dict :param priv_key: The private key to be used to sign the token. Note: if you pass ``None`` then the token will be returned with an empty cryptographic signature and :obj:`algorithm` will be forced to the value ``none``. :type priv_key: `jwcrypto.jwk.JWK <https://jwcrypto.readthedocs.io/en/latest/jwk.html>`_ :param algorithm: The algorithm to use for generating the signature. ``RS256``, ``RS384``, ``RS512``, ``PS256``, ``PS384``, ``PS512``, ``ES256``, ``ES384``, ``ES512``, ``HS256``, ``HS384``, ``HS512`` and ``none`` are supported. :type algorithm: str :param lifetime: How long the token is valid for. :type lifetime: datetime.timedelta :param expires: When the token expires (if :obj:`lifetime` isn't specified) :type expires: datetime.datetime :param not_before: When the token is valid from. Defaults to current time (if ``None`` is passed). :type not_before: datetime.datetime :param jti_size: Size in bytes of the unique token ID to put into the token (can be used to detect replay attacks). Defaults to 16 (128 bits). Specify 0 or ``None`` to omit the JTI from the token. :type jti_size: int :param other_headers: Any headers other than "typ" and "alg" may be specified, they will be included in the header. :type other_headers: dict :rtype: unicode :returns: The JSON Web Token. Note this includes a header, the claims and a cryptographic signature. The following extra claims are added, per the `JWT spec <http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html>`_: - **exp** (*IntDate*) -- The UTC expiry date and time of the token, in number of seconds from 1970-01-01T0:0:0Z UTC. - **iat** (*IntDate*) -- The UTC date and time at which the token was generated. - **nbf** (*IntDate*) -- The UTC valid-from date and time of the token. - **jti** (*str*) -- A unique identifier for the token. :raises: ValueError: If other_headers contains either the "typ" or "alg" header
[ "Generate", "a", "JSON", "Web", "Token", "." ]
5c753a26955cc666f00f6ff8e601406d95071368
https://github.com/davedoesdev/python-jwt/blob/5c753a26955cc666f00f6ff8e601406d95071368/python_jwt/__init__.py#L17-L96
train
31,117
davedoesdev/python-jwt
python_jwt/__init__.py
verify_jwt
def verify_jwt(jwt, pub_key=None, allowed_algs=None, iat_skew=timedelta(), checks_optional=False, ignore_not_implemented=False): """ Verify a JSON Web Token. :param jwt: The JSON Web Token to verify. :type jwt: str or unicode :param pub_key: The public key to be used to verify the token. Note: if you pass ``None`` and **allowed_algs** contains ``none`` then the token's signature will not be verified. :type pub_key: `jwcrypto.jwk.JWK <https://jwcrypto.readthedocs.io/en/latest/jwk.html>`_ :param allowed_algs: Algorithms expected to be used to sign the token. The ``in`` operator is used to test membership. :type allowed_algs: list or NoneType (meaning an empty list) :param iat_skew: The amount of leeway to allow between the issuer's clock and the verifier's clock when verifiying that the token was generated in the past. Defaults to no leeway. :type iat_skew: datetime.timedelta :param checks_optional: If ``False``, then the token must contain the **typ** header property and the **iat**, **nbf** and **exp** claim properties. :type checks_optional: bool :param ignore_not_implemented: If ``False``, then the token must *not* contain the **jku**, **jwk**, **x5u**, **x5c** or **x5t** header properties. :type ignore_not_implemented: bool :rtype: tuple :returns: ``(header, claims)`` if the token was verified successfully. The token must pass the following tests: - Its header must contain a property **alg** with a value in **allowed_algs**. - Its signature must verify using **pub_key** (unless its algorithm is ``none`` and ``none`` is in **allowed_algs**). - If the corresponding property is present or **checks_optional** is ``False``: - Its header must contain a property **typ** with the value ``JWT``. - Its claims must contain a property **iat** which represents a date in the past (taking into account :obj:`iat_skew`). - Its claims must contain a property **nbf** which represents a date in the past. - Its claims must contain a property **exp** which represents a date in the future. :raises: If the token failed to verify. """ if allowed_algs is None: allowed_algs = [] if not isinstance(allowed_algs, list): # jwcrypto only supports list of allowed algorithms raise _JWTError('allowed_algs must be a list') header, claims, _ = jwt.split('.') parsed_header = json_decode(base64url_decode(header)) alg = parsed_header.get('alg') if alg is None: raise _JWTError('alg header not present') if alg not in allowed_algs: raise _JWTError('algorithm not allowed: ' + alg) if not ignore_not_implemented: for k in parsed_header: if k not in JWSHeaderRegistry: raise _JWTError('unknown header: ' + k) if not JWSHeaderRegistry[k].supported: raise _JWTError('header not implemented: ' + k) if pub_key: token = JWS() token.allowed_algs = allowed_algs token.deserialize(jwt, pub_key) elif 'none' not in allowed_algs: raise _JWTError('no key but none alg not allowed') parsed_claims = json_decode(base64url_decode(claims)) utcnow = datetime.utcnow() now = timegm(utcnow.utctimetuple()) typ = parsed_header.get('typ') if typ is None: if not checks_optional: raise _JWTError('typ header not present') elif typ != 'JWT': raise _JWTError('typ header is not JWT') iat = parsed_claims.get('iat') if iat is None: if not checks_optional: raise _JWTError('iat claim not present') elif iat > timegm((utcnow + iat_skew).utctimetuple()): raise _JWTError('issued in the future') nbf = parsed_claims.get('nbf') if nbf is None: if not checks_optional: raise _JWTError('nbf claim not present') elif nbf > now: raise _JWTError('not yet valid') exp = parsed_claims.get('exp') if exp is None: if not checks_optional: raise _JWTError('exp claim not present') elif exp <= now: raise _JWTError('expired') return parsed_header, parsed_claims
python
def verify_jwt(jwt, pub_key=None, allowed_algs=None, iat_skew=timedelta(), checks_optional=False, ignore_not_implemented=False): """ Verify a JSON Web Token. :param jwt: The JSON Web Token to verify. :type jwt: str or unicode :param pub_key: The public key to be used to verify the token. Note: if you pass ``None`` and **allowed_algs** contains ``none`` then the token's signature will not be verified. :type pub_key: `jwcrypto.jwk.JWK <https://jwcrypto.readthedocs.io/en/latest/jwk.html>`_ :param allowed_algs: Algorithms expected to be used to sign the token. The ``in`` operator is used to test membership. :type allowed_algs: list or NoneType (meaning an empty list) :param iat_skew: The amount of leeway to allow between the issuer's clock and the verifier's clock when verifiying that the token was generated in the past. Defaults to no leeway. :type iat_skew: datetime.timedelta :param checks_optional: If ``False``, then the token must contain the **typ** header property and the **iat**, **nbf** and **exp** claim properties. :type checks_optional: bool :param ignore_not_implemented: If ``False``, then the token must *not* contain the **jku**, **jwk**, **x5u**, **x5c** or **x5t** header properties. :type ignore_not_implemented: bool :rtype: tuple :returns: ``(header, claims)`` if the token was verified successfully. The token must pass the following tests: - Its header must contain a property **alg** with a value in **allowed_algs**. - Its signature must verify using **pub_key** (unless its algorithm is ``none`` and ``none`` is in **allowed_algs**). - If the corresponding property is present or **checks_optional** is ``False``: - Its header must contain a property **typ** with the value ``JWT``. - Its claims must contain a property **iat** which represents a date in the past (taking into account :obj:`iat_skew`). - Its claims must contain a property **nbf** which represents a date in the past. - Its claims must contain a property **exp** which represents a date in the future. :raises: If the token failed to verify. """ if allowed_algs is None: allowed_algs = [] if not isinstance(allowed_algs, list): # jwcrypto only supports list of allowed algorithms raise _JWTError('allowed_algs must be a list') header, claims, _ = jwt.split('.') parsed_header = json_decode(base64url_decode(header)) alg = parsed_header.get('alg') if alg is None: raise _JWTError('alg header not present') if alg not in allowed_algs: raise _JWTError('algorithm not allowed: ' + alg) if not ignore_not_implemented: for k in parsed_header: if k not in JWSHeaderRegistry: raise _JWTError('unknown header: ' + k) if not JWSHeaderRegistry[k].supported: raise _JWTError('header not implemented: ' + k) if pub_key: token = JWS() token.allowed_algs = allowed_algs token.deserialize(jwt, pub_key) elif 'none' not in allowed_algs: raise _JWTError('no key but none alg not allowed') parsed_claims = json_decode(base64url_decode(claims)) utcnow = datetime.utcnow() now = timegm(utcnow.utctimetuple()) typ = parsed_header.get('typ') if typ is None: if not checks_optional: raise _JWTError('typ header not present') elif typ != 'JWT': raise _JWTError('typ header is not JWT') iat = parsed_claims.get('iat') if iat is None: if not checks_optional: raise _JWTError('iat claim not present') elif iat > timegm((utcnow + iat_skew).utctimetuple()): raise _JWTError('issued in the future') nbf = parsed_claims.get('nbf') if nbf is None: if not checks_optional: raise _JWTError('nbf claim not present') elif nbf > now: raise _JWTError('not yet valid') exp = parsed_claims.get('exp') if exp is None: if not checks_optional: raise _JWTError('exp claim not present') elif exp <= now: raise _JWTError('expired') return parsed_header, parsed_claims
[ "def", "verify_jwt", "(", "jwt", ",", "pub_key", "=", "None", ",", "allowed_algs", "=", "None", ",", "iat_skew", "=", "timedelta", "(", ")", ",", "checks_optional", "=", "False", ",", "ignore_not_implemented", "=", "False", ")", ":", "if", "allowed_algs", ...
Verify a JSON Web Token. :param jwt: The JSON Web Token to verify. :type jwt: str or unicode :param pub_key: The public key to be used to verify the token. Note: if you pass ``None`` and **allowed_algs** contains ``none`` then the token's signature will not be verified. :type pub_key: `jwcrypto.jwk.JWK <https://jwcrypto.readthedocs.io/en/latest/jwk.html>`_ :param allowed_algs: Algorithms expected to be used to sign the token. The ``in`` operator is used to test membership. :type allowed_algs: list or NoneType (meaning an empty list) :param iat_skew: The amount of leeway to allow between the issuer's clock and the verifier's clock when verifiying that the token was generated in the past. Defaults to no leeway. :type iat_skew: datetime.timedelta :param checks_optional: If ``False``, then the token must contain the **typ** header property and the **iat**, **nbf** and **exp** claim properties. :type checks_optional: bool :param ignore_not_implemented: If ``False``, then the token must *not* contain the **jku**, **jwk**, **x5u**, **x5c** or **x5t** header properties. :type ignore_not_implemented: bool :rtype: tuple :returns: ``(header, claims)`` if the token was verified successfully. The token must pass the following tests: - Its header must contain a property **alg** with a value in **allowed_algs**. - Its signature must verify using **pub_key** (unless its algorithm is ``none`` and ``none`` is in **allowed_algs**). - If the corresponding property is present or **checks_optional** is ``False``: - Its header must contain a property **typ** with the value ``JWT``. - Its claims must contain a property **iat** which represents a date in the past (taking into account :obj:`iat_skew`). - Its claims must contain a property **nbf** which represents a date in the past. - Its claims must contain a property **exp** which represents a date in the future. :raises: If the token failed to verify.
[ "Verify", "a", "JSON", "Web", "Token", "." ]
5c753a26955cc666f00f6ff8e601406d95071368
https://github.com/davedoesdev/python-jwt/blob/5c753a26955cc666f00f6ff8e601406d95071368/python_jwt/__init__.py#L100-L205
train
31,118
davedoesdev/python-jwt
python_jwt/__init__.py
process_jwt
def process_jwt(jwt): """ Process a JSON Web Token without verifying it. Call this before :func:`verify_jwt` if you need access to the header or claims in the token before verifying it. For example, the claims might identify the issuer such that you can retrieve the appropriate public key. :param jwt: The JSON Web Token to verify. :type jwt: str or unicode :rtype: tuple :returns: ``(header, claims)`` """ header, claims, _ = jwt.split('.') parsed_header = json_decode(base64url_decode(header)) parsed_claims = json_decode(base64url_decode(claims)) return parsed_header, parsed_claims
python
def process_jwt(jwt): """ Process a JSON Web Token without verifying it. Call this before :func:`verify_jwt` if you need access to the header or claims in the token before verifying it. For example, the claims might identify the issuer such that you can retrieve the appropriate public key. :param jwt: The JSON Web Token to verify. :type jwt: str or unicode :rtype: tuple :returns: ``(header, claims)`` """ header, claims, _ = jwt.split('.') parsed_header = json_decode(base64url_decode(header)) parsed_claims = json_decode(base64url_decode(claims)) return parsed_header, parsed_claims
[ "def", "process_jwt", "(", "jwt", ")", ":", "header", ",", "claims", ",", "_", "=", "jwt", ".", "split", "(", "'.'", ")", "parsed_header", "=", "json_decode", "(", "base64url_decode", "(", "header", ")", ")", "parsed_claims", "=", "json_decode", "(", "ba...
Process a JSON Web Token without verifying it. Call this before :func:`verify_jwt` if you need access to the header or claims in the token before verifying it. For example, the claims might identify the issuer such that you can retrieve the appropriate public key. :param jwt: The JSON Web Token to verify. :type jwt: str or unicode :rtype: tuple :returns: ``(header, claims)``
[ "Process", "a", "JSON", "Web", "Token", "without", "verifying", "it", "." ]
5c753a26955cc666f00f6ff8e601406d95071368
https://github.com/davedoesdev/python-jwt/blob/5c753a26955cc666f00f6ff8e601406d95071368/python_jwt/__init__.py#L209-L224
train
31,119
davedoesdev/python-jwt
bench/unitbench.py
Benchmark.run
def run(self, reporter=None): """This should generally not be overloaded. Runs the benchmark functions that are found in the child class. """ if not reporter: reporter = ConsoleReporter() benchmarks = sorted(self._find_benchmarks()) reporter.write_titles(map(self._function_name_to_title, benchmarks)) for value in self.input(): results = [] for b in benchmarks: method = getattr(self, b) arg_count = len(inspect.getargspec(method)[0]) if arg_count == 2: results.append(self._run_benchmark(method, value)) elif arg_count == 1: results.append(self._run_benchmark(method)) reporter.write_results(str(value), results)
python
def run(self, reporter=None): """This should generally not be overloaded. Runs the benchmark functions that are found in the child class. """ if not reporter: reporter = ConsoleReporter() benchmarks = sorted(self._find_benchmarks()) reporter.write_titles(map(self._function_name_to_title, benchmarks)) for value in self.input(): results = [] for b in benchmarks: method = getattr(self, b) arg_count = len(inspect.getargspec(method)[0]) if arg_count == 2: results.append(self._run_benchmark(method, value)) elif arg_count == 1: results.append(self._run_benchmark(method)) reporter.write_results(str(value), results)
[ "def", "run", "(", "self", ",", "reporter", "=", "None", ")", ":", "if", "not", "reporter", ":", "reporter", "=", "ConsoleReporter", "(", ")", "benchmarks", "=", "sorted", "(", "self", ".", "_find_benchmarks", "(", ")", ")", "reporter", ".", "write_title...
This should generally not be overloaded. Runs the benchmark functions that are found in the child class.
[ "This", "should", "generally", "not", "be", "overloaded", ".", "Runs", "the", "benchmark", "functions", "that", "are", "found", "in", "the", "child", "class", "." ]
5c753a26955cc666f00f6ff8e601406d95071368
https://github.com/davedoesdev/python-jwt/blob/5c753a26955cc666f00f6ff8e601406d95071368/bench/unitbench.py#L165-L185
train
31,120
davedoesdev/python-jwt
bench/unitbench.py
Benchmark._find_benchmarks
def _find_benchmarks(self): """Return a suite of all tests cases contained in testCaseClass""" def is_bench_method(attrname, prefix="bench"): return attrname.startswith(prefix) and hasattr(getattr(self.__class__, attrname), '__call__') return list(filter(is_bench_method, dir(self.__class__)))
python
def _find_benchmarks(self): """Return a suite of all tests cases contained in testCaseClass""" def is_bench_method(attrname, prefix="bench"): return attrname.startswith(prefix) and hasattr(getattr(self.__class__, attrname), '__call__') return list(filter(is_bench_method, dir(self.__class__)))
[ "def", "_find_benchmarks", "(", "self", ")", ":", "def", "is_bench_method", "(", "attrname", ",", "prefix", "=", "\"bench\"", ")", ":", "return", "attrname", ".", "startswith", "(", "prefix", ")", "and", "hasattr", "(", "getattr", "(", "self", ".", "__clas...
Return a suite of all tests cases contained in testCaseClass
[ "Return", "a", "suite", "of", "all", "tests", "cases", "contained", "in", "testCaseClass" ]
5c753a26955cc666f00f6ff8e601406d95071368
https://github.com/davedoesdev/python-jwt/blob/5c753a26955cc666f00f6ff8e601406d95071368/bench/unitbench.py#L228-L232
train
31,121
ansible/tacacs_plus
tacacs_plus/client.py
TACACSClient.send
def send(self, body, req_type, seq_no=1): """ Send a TACACS+ message body :param body: packed bytes, i.e., `struct.pack(...)` :param req_type: TAC_PLUS_AUTHEN, TAC_PLUS_AUTHOR, TAC_PLUS_ACCT :param seq_no: The sequence number of the current packet. The first packet in a session MUST have the sequence number 1 and each subsequent packet will increment the sequence number by one. Thus clients only send packets containing odd sequence numbers, and TACACS+ servers only send packets containing even sequence numbers. :return: TACACSPacket :raises: socket.timeout, socket.error """ # construct a packet header = TACACSHeader( self.version, req_type, self.session_id, len(body.packed), seq_no=seq_no ) packet = TACACSPacket(header, body.packed, self.secret) logger.debug('\n'.join([ body.__class__.__name__, 'sent header <%s>' % header, 'sent body <%s>' % body, ])) self.sock.send(bytes(packet)) readable, _, _ = select.select([self.sock], [], [], self.timeout) if readable: # TACACS+ header packets are always 12 bytes header_bytes = self.sock.recv(12) resp_header = TACACSHeader.unpacked(header_bytes) # If the reply header doesn't match, it's likely a non-TACACS+ TCP # service answering with data we don't antipicate. Bail out. if any([ resp_header.version_max != header.version_max, resp_header.type != header.type, resp_header.session_id != header.session_id ]): logger.error('\n'.join([ resp_header.__class__.__name__, 'recv header <%s>' % resp_header, str(resp_header.packed) ])) raise socket.error # read the number of bytes specified in the response header body_bytes = six.b('') remaining = resp_header.length while remaining > 0: body_bytes += self.sock.recv(remaining) remaining = resp_header.length - len(body_bytes) return TACACSPacket( resp_header, body_bytes, self.secret ) raise socket.timeout
python
def send(self, body, req_type, seq_no=1): """ Send a TACACS+ message body :param body: packed bytes, i.e., `struct.pack(...)` :param req_type: TAC_PLUS_AUTHEN, TAC_PLUS_AUTHOR, TAC_PLUS_ACCT :param seq_no: The sequence number of the current packet. The first packet in a session MUST have the sequence number 1 and each subsequent packet will increment the sequence number by one. Thus clients only send packets containing odd sequence numbers, and TACACS+ servers only send packets containing even sequence numbers. :return: TACACSPacket :raises: socket.timeout, socket.error """ # construct a packet header = TACACSHeader( self.version, req_type, self.session_id, len(body.packed), seq_no=seq_no ) packet = TACACSPacket(header, body.packed, self.secret) logger.debug('\n'.join([ body.__class__.__name__, 'sent header <%s>' % header, 'sent body <%s>' % body, ])) self.sock.send(bytes(packet)) readable, _, _ = select.select([self.sock], [], [], self.timeout) if readable: # TACACS+ header packets are always 12 bytes header_bytes = self.sock.recv(12) resp_header = TACACSHeader.unpacked(header_bytes) # If the reply header doesn't match, it's likely a non-TACACS+ TCP # service answering with data we don't antipicate. Bail out. if any([ resp_header.version_max != header.version_max, resp_header.type != header.type, resp_header.session_id != header.session_id ]): logger.error('\n'.join([ resp_header.__class__.__name__, 'recv header <%s>' % resp_header, str(resp_header.packed) ])) raise socket.error # read the number of bytes specified in the response header body_bytes = six.b('') remaining = resp_header.length while remaining > 0: body_bytes += self.sock.recv(remaining) remaining = resp_header.length - len(body_bytes) return TACACSPacket( resp_header, body_bytes, self.secret ) raise socket.timeout
[ "def", "send", "(", "self", ",", "body", ",", "req_type", ",", "seq_no", "=", "1", ")", ":", "# construct a packet", "header", "=", "TACACSHeader", "(", "self", ".", "version", ",", "req_type", ",", "self", ".", "session_id", ",", "len", "(", "body", "...
Send a TACACS+ message body :param body: packed bytes, i.e., `struct.pack(...)` :param req_type: TAC_PLUS_AUTHEN, TAC_PLUS_AUTHOR, TAC_PLUS_ACCT :param seq_no: The sequence number of the current packet. The first packet in a session MUST have the sequence number 1 and each subsequent packet will increment the sequence number by one. Thus clients only send packets containing odd sequence numbers, and TACACS+ servers only send packets containing even sequence numbers. :return: TACACSPacket :raises: socket.timeout, socket.error
[ "Send", "a", "TACACS", "+", "message", "body" ]
de0d01372169c8849fa284d75097e57367c8930f
https://github.com/ansible/tacacs_plus/blob/de0d01372169c8849fa284d75097e57367c8930f/tacacs_plus/client.py#L88-L153
train
31,122
ansible/tacacs_plus
tacacs_plus/client.py
TACACSClient.authenticate
def authenticate(self, username, password, priv_lvl=TAC_PLUS_PRIV_LVL_MIN, authen_type=TAC_PLUS_AUTHEN_TYPE_ASCII, chap_ppp_id=None, chap_challenge=None, rem_addr=TAC_PLUS_VIRTUAL_REM_ADDR, port=TAC_PLUS_VIRTUAL_PORT): """ Authenticate to a TACACS+ server with a username and password. :param username: :param password: :param priv_lvl: :param authen_type: TAC_PLUS_AUTHEN_TYPE_ASCII, TAC_PLUS_AUTHEN_TYPE_PAP, TAC_PLUS_AUTHEN_TYPE_CHAP :param chap_ppp_id: PPP ID when authen_type == 'chap' :param chap_challenge: challenge value when authen_type == 'chap' :param rem_addr: AAA request source, default to TAC_PLUS_VIRTUAL_REM_ADDR :param port: AAA port, default to TAC_PLUS_VIRTUAL_PORT :return: TACACSAuthenticationReply :raises: socket.timeout, socket.error """ start_data = six.b('') if authen_type in (TAC_PLUS_AUTHEN_TYPE_PAP, TAC_PLUS_AUTHEN_TYPE_CHAP): self.version_min = TAC_PLUS_MINOR_VER_ONE if authen_type == TAC_PLUS_AUTHEN_TYPE_PAP: start_data = six.b(password) if authen_type == TAC_PLUS_AUTHEN_TYPE_CHAP: if not isinstance(chap_ppp_id, six.string_types): raise ValueError('chap_ppp_id must be a string') if len(chap_ppp_id) != 1: raise ValueError('chap_ppp_id must be a 1-byte string') if not isinstance(chap_challenge, six.string_types): raise ValueError('chap_challenge must be a string') if len(chap_challenge) > 255: raise ValueError('chap_challenge may not be more 255 bytes') start_data = ( six.b(chap_ppp_id) + six.b(chap_challenge) + md5(six.b( chap_ppp_id + password + chap_challenge )).digest() ) with self.closing(): packet = self.send( TACACSAuthenticationStart(username, authen_type, priv_lvl, start_data, rem_addr=rem_addr, port=port), TAC_PLUS_AUTHEN ) reply = TACACSAuthenticationReply.unpacked(packet.body) logger.debug('\n'.join([ reply.__class__.__name__, 'recv header <%s>' % packet.header, 'recv body <%s>' % reply ])) if authen_type == TAC_PLUS_AUTHEN_TYPE_ASCII and reply.getpass: packet = self.send(TACACSAuthenticationContinue(password), TAC_PLUS_AUTHEN, packet.seq_no + 1) reply = TACACSAuthenticationReply.unpacked(packet.body) logger.debug('\n'.join([ reply.__class__.__name__, 'recv header <%s>' % packet.header, 'recv body <%s>' % reply ])) if reply.flags == TAC_PLUS_CONTINUE_FLAG_ABORT: reply.status = TAC_PLUS_AUTHEN_STATUS_FAIL return reply
python
def authenticate(self, username, password, priv_lvl=TAC_PLUS_PRIV_LVL_MIN, authen_type=TAC_PLUS_AUTHEN_TYPE_ASCII, chap_ppp_id=None, chap_challenge=None, rem_addr=TAC_PLUS_VIRTUAL_REM_ADDR, port=TAC_PLUS_VIRTUAL_PORT): """ Authenticate to a TACACS+ server with a username and password. :param username: :param password: :param priv_lvl: :param authen_type: TAC_PLUS_AUTHEN_TYPE_ASCII, TAC_PLUS_AUTHEN_TYPE_PAP, TAC_PLUS_AUTHEN_TYPE_CHAP :param chap_ppp_id: PPP ID when authen_type == 'chap' :param chap_challenge: challenge value when authen_type == 'chap' :param rem_addr: AAA request source, default to TAC_PLUS_VIRTUAL_REM_ADDR :param port: AAA port, default to TAC_PLUS_VIRTUAL_PORT :return: TACACSAuthenticationReply :raises: socket.timeout, socket.error """ start_data = six.b('') if authen_type in (TAC_PLUS_AUTHEN_TYPE_PAP, TAC_PLUS_AUTHEN_TYPE_CHAP): self.version_min = TAC_PLUS_MINOR_VER_ONE if authen_type == TAC_PLUS_AUTHEN_TYPE_PAP: start_data = six.b(password) if authen_type == TAC_PLUS_AUTHEN_TYPE_CHAP: if not isinstance(chap_ppp_id, six.string_types): raise ValueError('chap_ppp_id must be a string') if len(chap_ppp_id) != 1: raise ValueError('chap_ppp_id must be a 1-byte string') if not isinstance(chap_challenge, six.string_types): raise ValueError('chap_challenge must be a string') if len(chap_challenge) > 255: raise ValueError('chap_challenge may not be more 255 bytes') start_data = ( six.b(chap_ppp_id) + six.b(chap_challenge) + md5(six.b( chap_ppp_id + password + chap_challenge )).digest() ) with self.closing(): packet = self.send( TACACSAuthenticationStart(username, authen_type, priv_lvl, start_data, rem_addr=rem_addr, port=port), TAC_PLUS_AUTHEN ) reply = TACACSAuthenticationReply.unpacked(packet.body) logger.debug('\n'.join([ reply.__class__.__name__, 'recv header <%s>' % packet.header, 'recv body <%s>' % reply ])) if authen_type == TAC_PLUS_AUTHEN_TYPE_ASCII and reply.getpass: packet = self.send(TACACSAuthenticationContinue(password), TAC_PLUS_AUTHEN, packet.seq_no + 1) reply = TACACSAuthenticationReply.unpacked(packet.body) logger.debug('\n'.join([ reply.__class__.__name__, 'recv header <%s>' % packet.header, 'recv body <%s>' % reply ])) if reply.flags == TAC_PLUS_CONTINUE_FLAG_ABORT: reply.status = TAC_PLUS_AUTHEN_STATUS_FAIL return reply
[ "def", "authenticate", "(", "self", ",", "username", ",", "password", ",", "priv_lvl", "=", "TAC_PLUS_PRIV_LVL_MIN", ",", "authen_type", "=", "TAC_PLUS_AUTHEN_TYPE_ASCII", ",", "chap_ppp_id", "=", "None", ",", "chap_challenge", "=", "None", ",", "rem_addr", "=", ...
Authenticate to a TACACS+ server with a username and password. :param username: :param password: :param priv_lvl: :param authen_type: TAC_PLUS_AUTHEN_TYPE_ASCII, TAC_PLUS_AUTHEN_TYPE_PAP, TAC_PLUS_AUTHEN_TYPE_CHAP :param chap_ppp_id: PPP ID when authen_type == 'chap' :param chap_challenge: challenge value when authen_type == 'chap' :param rem_addr: AAA request source, default to TAC_PLUS_VIRTUAL_REM_ADDR :param port: AAA port, default to TAC_PLUS_VIRTUAL_PORT :return: TACACSAuthenticationReply :raises: socket.timeout, socket.error
[ "Authenticate", "to", "a", "TACACS", "+", "server", "with", "a", "username", "and", "password", "." ]
de0d01372169c8849fa284d75097e57367c8930f
https://github.com/ansible/tacacs_plus/blob/de0d01372169c8849fa284d75097e57367c8930f/tacacs_plus/client.py#L155-L224
train
31,123
ansible/tacacs_plus
tacacs_plus/client.py
TACACSClient.authorize
def authorize(self, username, arguments=[], authen_type=TAC_PLUS_AUTHEN_TYPE_ASCII, priv_lvl=TAC_PLUS_PRIV_LVL_MIN, rem_addr=TAC_PLUS_VIRTUAL_REM_ADDR, port=TAC_PLUS_VIRTUAL_PORT): """ Authorize with a TACACS+ server. :param username: :param arguments: The authorization arguments :param authen_type: TAC_PLUS_AUTHEN_TYPE_ASCII, TAC_PLUS_AUTHEN_TYPE_PAP, TAC_PLUS_AUTHEN_TYPE_CHAP :param priv_lvl: Minimal Required priv_lvl. :param rem_addr: AAA request source, default to TAC_PLUS_VIRTUAL_REM_ADDR :param port: AAA port, default to TAC_PLUS_VIRTUAL_PORT :return: TACACSAuthenticationReply :raises: socket.timeout, socket.error """ with self.closing(): packet = self.send( TACACSAuthorizationStart(username, TAC_PLUS_AUTHEN_METH_TACACSPLUS, priv_lvl, authen_type, arguments, rem_addr=rem_addr, port=port), TAC_PLUS_AUTHOR ) reply = TACACSAuthorizationReply.unpacked(packet.body) logger.debug('\n'.join([ reply.__class__.__name__, 'recv header <%s>' % packet.header, 'recv body <%s>' % reply ])) reply_arguments = dict([ arg.split(six.b('='), 1) for arg in reply.arguments or [] if arg.find(six.b('=')) > -1] ) user_priv_lvl = int(reply_arguments.get( six.b('priv-lvl'), TAC_PLUS_PRIV_LVL_MAX)) if user_priv_lvl < priv_lvl: reply.status = TAC_PLUS_AUTHOR_STATUS_FAIL return reply
python
def authorize(self, username, arguments=[], authen_type=TAC_PLUS_AUTHEN_TYPE_ASCII, priv_lvl=TAC_PLUS_PRIV_LVL_MIN, rem_addr=TAC_PLUS_VIRTUAL_REM_ADDR, port=TAC_PLUS_VIRTUAL_PORT): """ Authorize with a TACACS+ server. :param username: :param arguments: The authorization arguments :param authen_type: TAC_PLUS_AUTHEN_TYPE_ASCII, TAC_PLUS_AUTHEN_TYPE_PAP, TAC_PLUS_AUTHEN_TYPE_CHAP :param priv_lvl: Minimal Required priv_lvl. :param rem_addr: AAA request source, default to TAC_PLUS_VIRTUAL_REM_ADDR :param port: AAA port, default to TAC_PLUS_VIRTUAL_PORT :return: TACACSAuthenticationReply :raises: socket.timeout, socket.error """ with self.closing(): packet = self.send( TACACSAuthorizationStart(username, TAC_PLUS_AUTHEN_METH_TACACSPLUS, priv_lvl, authen_type, arguments, rem_addr=rem_addr, port=port), TAC_PLUS_AUTHOR ) reply = TACACSAuthorizationReply.unpacked(packet.body) logger.debug('\n'.join([ reply.__class__.__name__, 'recv header <%s>' % packet.header, 'recv body <%s>' % reply ])) reply_arguments = dict([ arg.split(six.b('='), 1) for arg in reply.arguments or [] if arg.find(six.b('=')) > -1] ) user_priv_lvl = int(reply_arguments.get( six.b('priv-lvl'), TAC_PLUS_PRIV_LVL_MAX)) if user_priv_lvl < priv_lvl: reply.status = TAC_PLUS_AUTHOR_STATUS_FAIL return reply
[ "def", "authorize", "(", "self", ",", "username", ",", "arguments", "=", "[", "]", ",", "authen_type", "=", "TAC_PLUS_AUTHEN_TYPE_ASCII", ",", "priv_lvl", "=", "TAC_PLUS_PRIV_LVL_MIN", ",", "rem_addr", "=", "TAC_PLUS_VIRTUAL_REM_ADDR", ",", "port", "=", "TAC_PLUS_...
Authorize with a TACACS+ server. :param username: :param arguments: The authorization arguments :param authen_type: TAC_PLUS_AUTHEN_TYPE_ASCII, TAC_PLUS_AUTHEN_TYPE_PAP, TAC_PLUS_AUTHEN_TYPE_CHAP :param priv_lvl: Minimal Required priv_lvl. :param rem_addr: AAA request source, default to TAC_PLUS_VIRTUAL_REM_ADDR :param port: AAA port, default to TAC_PLUS_VIRTUAL_PORT :return: TACACSAuthenticationReply :raises: socket.timeout, socket.error
[ "Authorize", "with", "a", "TACACS", "+", "server", "." ]
de0d01372169c8849fa284d75097e57367c8930f
https://github.com/ansible/tacacs_plus/blob/de0d01372169c8849fa284d75097e57367c8930f/tacacs_plus/client.py#L226-L266
train
31,124
ansible/tacacs_plus
tacacs_plus/client.py
TACACSClient.account
def account(self, username, flags, arguments=[], authen_type=TAC_PLUS_AUTHEN_TYPE_ASCII, priv_lvl=TAC_PLUS_PRIV_LVL_MIN, rem_addr=TAC_PLUS_VIRTUAL_REM_ADDR, port=TAC_PLUS_VIRTUAL_PORT): """ Account with a TACACS+ server. :param username: :param flags: TAC_PLUS_ACCT_FLAG_START, TAC_PLUS_ACCT_FLAG_WATCHDOG, TAC_PLUS_ACCT_FLAG_STOP :param arguments: The authorization arguments :param authen_type: TAC_PLUS_AUTHEN_TYPE_ASCII, TAC_PLUS_AUTHEN_TYPE_PAP, TAC_PLUS_AUTHEN_TYPE_CHAP :param priv_lvl: Minimal Required priv_lvl. :param rem_addr: AAA request source, default to TAC_PLUS_VIRTUAL_REM_ADDR :param port: AAA port, default to TAC_PLUS_VIRTUAL_PORT :return: TACACSAccountingReply :raises: socket.timeout, socket.error """ with self.closing(): packet = self.send( TACACSAccountingStart(username, flags, TAC_PLUS_AUTHEN_METH_TACACSPLUS, priv_lvl, authen_type, arguments, rem_addr=rem_addr, port=port), TAC_PLUS_ACCT ) reply = TACACSAccountingReply.unpacked(packet.body) logger.debug('\n'.join([ reply.__class__.__name__, 'recv header <%s>' % packet.header, 'recv body <%s>' % reply ])) return reply
python
def account(self, username, flags, arguments=[], authen_type=TAC_PLUS_AUTHEN_TYPE_ASCII, priv_lvl=TAC_PLUS_PRIV_LVL_MIN, rem_addr=TAC_PLUS_VIRTUAL_REM_ADDR, port=TAC_PLUS_VIRTUAL_PORT): """ Account with a TACACS+ server. :param username: :param flags: TAC_PLUS_ACCT_FLAG_START, TAC_PLUS_ACCT_FLAG_WATCHDOG, TAC_PLUS_ACCT_FLAG_STOP :param arguments: The authorization arguments :param authen_type: TAC_PLUS_AUTHEN_TYPE_ASCII, TAC_PLUS_AUTHEN_TYPE_PAP, TAC_PLUS_AUTHEN_TYPE_CHAP :param priv_lvl: Minimal Required priv_lvl. :param rem_addr: AAA request source, default to TAC_PLUS_VIRTUAL_REM_ADDR :param port: AAA port, default to TAC_PLUS_VIRTUAL_PORT :return: TACACSAccountingReply :raises: socket.timeout, socket.error """ with self.closing(): packet = self.send( TACACSAccountingStart(username, flags, TAC_PLUS_AUTHEN_METH_TACACSPLUS, priv_lvl, authen_type, arguments, rem_addr=rem_addr, port=port), TAC_PLUS_ACCT ) reply = TACACSAccountingReply.unpacked(packet.body) logger.debug('\n'.join([ reply.__class__.__name__, 'recv header <%s>' % packet.header, 'recv body <%s>' % reply ])) return reply
[ "def", "account", "(", "self", ",", "username", ",", "flags", ",", "arguments", "=", "[", "]", ",", "authen_type", "=", "TAC_PLUS_AUTHEN_TYPE_ASCII", ",", "priv_lvl", "=", "TAC_PLUS_PRIV_LVL_MIN", ",", "rem_addr", "=", "TAC_PLUS_VIRTUAL_REM_ADDR", ",", "port", "...
Account with a TACACS+ server. :param username: :param flags: TAC_PLUS_ACCT_FLAG_START, TAC_PLUS_ACCT_FLAG_WATCHDOG, TAC_PLUS_ACCT_FLAG_STOP :param arguments: The authorization arguments :param authen_type: TAC_PLUS_AUTHEN_TYPE_ASCII, TAC_PLUS_AUTHEN_TYPE_PAP, TAC_PLUS_AUTHEN_TYPE_CHAP :param priv_lvl: Minimal Required priv_lvl. :param rem_addr: AAA request source, default to TAC_PLUS_VIRTUAL_REM_ADDR :param port: AAA port, default to TAC_PLUS_VIRTUAL_PORT :return: TACACSAccountingReply :raises: socket.timeout, socket.error
[ "Account", "with", "a", "TACACS", "+", "server", "." ]
de0d01372169c8849fa284d75097e57367c8930f
https://github.com/ansible/tacacs_plus/blob/de0d01372169c8849fa284d75097e57367c8930f/tacacs_plus/client.py#L268-L302
train
31,125
IBM-Cloud/gp-python-client
gpclient/gpserviceaccount.py
GPServiceAccount.__get_user_env_vars
def __get_user_env_vars(self): """Return the user defined environment variables""" return (os.environ.get(self.GP_URL_ENV_VAR), os.environ.get(self.GP_INSTANCE_ID_ENV_VAR), os.environ.get(self.GP_USER_ID_ENV_VAR), os.environ.get(self.GP_PASSWORD_ENV_VAR), os.environ.get(self.GP_IAM_API_KEY_ENV_VAR))
python
def __get_user_env_vars(self): """Return the user defined environment variables""" return (os.environ.get(self.GP_URL_ENV_VAR), os.environ.get(self.GP_INSTANCE_ID_ENV_VAR), os.environ.get(self.GP_USER_ID_ENV_VAR), os.environ.get(self.GP_PASSWORD_ENV_VAR), os.environ.get(self.GP_IAM_API_KEY_ENV_VAR))
[ "def", "__get_user_env_vars", "(", "self", ")", ":", "return", "(", "os", ".", "environ", ".", "get", "(", "self", ".", "GP_URL_ENV_VAR", ")", ",", "os", ".", "environ", ".", "get", "(", "self", ".", "GP_INSTANCE_ID_ENV_VAR", ")", ",", "os", ".", "envi...
Return the user defined environment variables
[ "Return", "the", "user", "defined", "environment", "variables" ]
082c6cdc250fb61bea99cba8ac3ee855ee77a410
https://github.com/IBM-Cloud/gp-python-client/blob/082c6cdc250fb61bea99cba8ac3ee855ee77a410/gpclient/gpserviceaccount.py#L203-L209
train
31,126
IBM-Cloud/gp-python-client
gpclient/gpserviceaccount.py
GPServiceAccount.__parse_vcap_services_env_var
def __parse_vcap_services_env_var(self, serviceInstanceName=None): """Parse the ``VCAP_SERVICES`` env var and search for the necessary values """ vcapServices = os.environ.get(self.__VCAP_SERVICES_ENV_VAR) if not vcapServices: return (None, None, None, None, None) parsedVcapServices = json.loads(vcapServices) gpServicesInstances = [] for serviceName in parsedVcapServices: if self.__gpServiceNameRegex.match(serviceName): serviceInstances = parsedVcapServices.get(serviceName) for serviceInstance in serviceInstances: gpServicesInstances.append(serviceInstance) if not gpServicesInstances: return (None, None, None, None, None) targetGPServiceInstance = None # use first service if no name is provided if not serviceInstanceName: targetGPServiceInstance = gpServicesInstances[0] else: # search for service name for gpServiceInstance in gpServicesInstances: if gpServiceInstance.get(self.__NAME_KEY)== serviceInstanceName: targetGPServiceInstance = gpServiceInstance break # service was not found if not targetGPServiceInstance: return (None, None, None, None, None) credentials = targetGPServiceInstance.get(self.__CREDENTIALS_KEY) if not credentials: return (None, None, None, None, None) url = credentials.get(self.__URL_KEY) instanceId = credentials.get(self.__INSTANCE_ID_KEY) userId = credentials.get(self.__USER_ID_KEY) password = credentials.get(self.__PASSWORD_KEY) apiKey = credentials.get(self.__IAM_API_KEY_KEY) return (url, instanceId, userId, password, apiKey)
python
def __parse_vcap_services_env_var(self, serviceInstanceName=None): """Parse the ``VCAP_SERVICES`` env var and search for the necessary values """ vcapServices = os.environ.get(self.__VCAP_SERVICES_ENV_VAR) if not vcapServices: return (None, None, None, None, None) parsedVcapServices = json.loads(vcapServices) gpServicesInstances = [] for serviceName in parsedVcapServices: if self.__gpServiceNameRegex.match(serviceName): serviceInstances = parsedVcapServices.get(serviceName) for serviceInstance in serviceInstances: gpServicesInstances.append(serviceInstance) if not gpServicesInstances: return (None, None, None, None, None) targetGPServiceInstance = None # use first service if no name is provided if not serviceInstanceName: targetGPServiceInstance = gpServicesInstances[0] else: # search for service name for gpServiceInstance in gpServicesInstances: if gpServiceInstance.get(self.__NAME_KEY)== serviceInstanceName: targetGPServiceInstance = gpServiceInstance break # service was not found if not targetGPServiceInstance: return (None, None, None, None, None) credentials = targetGPServiceInstance.get(self.__CREDENTIALS_KEY) if not credentials: return (None, None, None, None, None) url = credentials.get(self.__URL_KEY) instanceId = credentials.get(self.__INSTANCE_ID_KEY) userId = credentials.get(self.__USER_ID_KEY) password = credentials.get(self.__PASSWORD_KEY) apiKey = credentials.get(self.__IAM_API_KEY_KEY) return (url, instanceId, userId, password, apiKey)
[ "def", "__parse_vcap_services_env_var", "(", "self", ",", "serviceInstanceName", "=", "None", ")", ":", "vcapServices", "=", "os", ".", "environ", ".", "get", "(", "self", ".", "__VCAP_SERVICES_ENV_VAR", ")", "if", "not", "vcapServices", ":", "return", "(", "N...
Parse the ``VCAP_SERVICES`` env var and search for the necessary values
[ "Parse", "the", "VCAP_SERVICES", "env", "var", "and", "search", "for", "the", "necessary", "values" ]
082c6cdc250fb61bea99cba8ac3ee855ee77a410
https://github.com/IBM-Cloud/gp-python-client/blob/082c6cdc250fb61bea99cba8ac3ee855ee77a410/gpclient/gpserviceaccount.py#L211-L258
train
31,127
IBM-Cloud/gp-python-client
gpclient/gpclient.py
GPClient.__prepare_gprest_call
def __prepare_gprest_call(self, requestURL, params=None, headers=None, restType='GET', body=None): """Returns Authorization type and GP headers """ if self.__serviceAccount.is_iam_enabled(): auth = None iam_api_key_header = { self.__AUTHORIZATION_HEADER_KEY: str('API-KEY '+self.__serviceAccount.get_api_key()) } if not headers is None: headers.update(iam_api_key_header) else: headers = iam_api_key_header elif self.__auth == self.BASIC_AUTH: auth = (self.__serviceAccount.get_user_id(), self.__serviceAccount.get_password()) elif self.__auth == self.HMAC_AUTH: auth = None # need to prepare url by appending params to the end # before creating the hmac headers fakeRequest = requests.PreparedRequest() fakeRequest.prepare_url(requestURL, params=params) preparedUrl = fakeRequest.url hmacHeaders = self.__get_gaas_hmac_headers(method=restType, url=preparedUrl, body=body) if not headers is None: headers.update(hmacHeaders) else: headers = hmacHeaders return auth, headers
python
def __prepare_gprest_call(self, requestURL, params=None, headers=None, restType='GET', body=None): """Returns Authorization type and GP headers """ if self.__serviceAccount.is_iam_enabled(): auth = None iam_api_key_header = { self.__AUTHORIZATION_HEADER_KEY: str('API-KEY '+self.__serviceAccount.get_api_key()) } if not headers is None: headers.update(iam_api_key_header) else: headers = iam_api_key_header elif self.__auth == self.BASIC_AUTH: auth = (self.__serviceAccount.get_user_id(), self.__serviceAccount.get_password()) elif self.__auth == self.HMAC_AUTH: auth = None # need to prepare url by appending params to the end # before creating the hmac headers fakeRequest = requests.PreparedRequest() fakeRequest.prepare_url(requestURL, params=params) preparedUrl = fakeRequest.url hmacHeaders = self.__get_gaas_hmac_headers(method=restType, url=preparedUrl, body=body) if not headers is None: headers.update(hmacHeaders) else: headers = hmacHeaders return auth, headers
[ "def", "__prepare_gprest_call", "(", "self", ",", "requestURL", ",", "params", "=", "None", ",", "headers", "=", "None", ",", "restType", "=", "'GET'", ",", "body", "=", "None", ")", ":", "if", "self", ".", "__serviceAccount", ".", "is_iam_enabled", "(", ...
Returns Authorization type and GP headers
[ "Returns", "Authorization", "type", "and", "GP", "headers" ]
082c6cdc250fb61bea99cba8ac3ee855ee77a410
https://github.com/IBM-Cloud/gp-python-client/blob/082c6cdc250fb61bea99cba8ac3ee855ee77a410/gpclient/gpclient.py#L226-L256
train
31,128
IBM-Cloud/gp-python-client
gpclient/gpclient.py
GPClient.__process_gprest_response
def __process_gprest_response(self, r=None, restType='GET'): """Returns the processed response for rest calls """ if r is None: logging.info('No response for REST '+restType+' request') return None httpStatus = r.status_code logging.info('HTTP status code: %s', httpStatus) if httpStatus == requests.codes.ok or \ httpStatus == requests.codes.created: jsonR = r.json() if jsonR: statusStr = 'REST response status: %s' % \ jsonR.get(self.__RESPONSE_STATUS_KEY) msgStr = 'REST response message: %s' % \ jsonR.get(self.__RESPONSE_MESSAGE_KEY) logging.info(statusStr) logging.info(msgStr) return jsonR else: logging.warning('Unable to parse JSON body.') logging.warning(r.text) return None logging.warning('Invalid HTTP status code.') logging.warning(r.text) return r.json()
python
def __process_gprest_response(self, r=None, restType='GET'): """Returns the processed response for rest calls """ if r is None: logging.info('No response for REST '+restType+' request') return None httpStatus = r.status_code logging.info('HTTP status code: %s', httpStatus) if httpStatus == requests.codes.ok or \ httpStatus == requests.codes.created: jsonR = r.json() if jsonR: statusStr = 'REST response status: %s' % \ jsonR.get(self.__RESPONSE_STATUS_KEY) msgStr = 'REST response message: %s' % \ jsonR.get(self.__RESPONSE_MESSAGE_KEY) logging.info(statusStr) logging.info(msgStr) return jsonR else: logging.warning('Unable to parse JSON body.') logging.warning(r.text) return None logging.warning('Invalid HTTP status code.') logging.warning(r.text) return r.json()
[ "def", "__process_gprest_response", "(", "self", ",", "r", "=", "None", ",", "restType", "=", "'GET'", ")", ":", "if", "r", "is", "None", ":", "logging", ".", "info", "(", "'No response for REST '", "+", "restType", "+", "' request'", ")", "return", "None"...
Returns the processed response for rest calls
[ "Returns", "the", "processed", "response", "for", "rest", "calls" ]
082c6cdc250fb61bea99cba8ac3ee855ee77a410
https://github.com/IBM-Cloud/gp-python-client/blob/082c6cdc250fb61bea99cba8ac3ee855ee77a410/gpclient/gpclient.py#L258-L285
train
31,129
IBM-Cloud/gp-python-client
gpclient/gpclient.py
GPClient.__perform_rest_call
def __perform_rest_call(self, requestURL, params=None, headers=None, restType='GET', body=None): """Returns the JSON representation of the response if the response status was ok, returns ``None`` otherwise. """ auth, headers = self.__prepare_gprest_call(requestURL, params=params, headers=headers, restType=restType, body=body) if restType == 'GET': r = requests.get(requestURL, auth=auth, headers=headers, params=params) elif restType == 'PUT': r = requests.put(requestURL, data=body, auth=auth, headers=headers, params=params) elif restType == 'POST': r = requests.post(requestURL, data=body, auth=auth, headers=headers, params=params) elif restType == 'DELETE': r = requests.delete(requestURL, auth=auth, headers=headers, params=params) resp = self.__process_gprest_response(r, restType=restType) return resp
python
def __perform_rest_call(self, requestURL, params=None, headers=None, restType='GET', body=None): """Returns the JSON representation of the response if the response status was ok, returns ``None`` otherwise. """ auth, headers = self.__prepare_gprest_call(requestURL, params=params, headers=headers, restType=restType, body=body) if restType == 'GET': r = requests.get(requestURL, auth=auth, headers=headers, params=params) elif restType == 'PUT': r = requests.put(requestURL, data=body, auth=auth, headers=headers, params=params) elif restType == 'POST': r = requests.post(requestURL, data=body, auth=auth, headers=headers, params=params) elif restType == 'DELETE': r = requests.delete(requestURL, auth=auth, headers=headers, params=params) resp = self.__process_gprest_response(r, restType=restType) return resp
[ "def", "__perform_rest_call", "(", "self", ",", "requestURL", ",", "params", "=", "None", ",", "headers", "=", "None", ",", "restType", "=", "'GET'", ",", "body", "=", "None", ")", ":", "auth", ",", "headers", "=", "self", ".", "__prepare_gprest_call", "...
Returns the JSON representation of the response if the response status was ok, returns ``None`` otherwise.
[ "Returns", "the", "JSON", "representation", "of", "the", "response", "if", "the", "response", "status", "was", "ok", "returns", "None", "otherwise", "." ]
082c6cdc250fb61bea99cba8ac3ee855ee77a410
https://github.com/IBM-Cloud/gp-python-client/blob/082c6cdc250fb61bea99cba8ac3ee855ee77a410/gpclient/gpclient.py#L287-L301
train
31,130
IBM-Cloud/gp-python-client
gpclient/gpclient.py
GPClient.createReaderUser
def createReaderUser(self,accessibleBundles=None): """Creates a new reader user with access to the specified bundle Ids""" url = self.__serviceAccount.get_url() + '/' + \ self.__serviceAccount.get_instance_id()+ '/v2/users/new' headers = {'content-type': 'application/json'} data = {} data['type'] = 'READER' if accessibleBundles is not None: data['bundles']=accessibleBundles json_data = json.dumps(data) response = self.__perform_rest_call(requestURL=url, restType='POST', body=json_data, headers=headers) return response
python
def createReaderUser(self,accessibleBundles=None): """Creates a new reader user with access to the specified bundle Ids""" url = self.__serviceAccount.get_url() + '/' + \ self.__serviceAccount.get_instance_id()+ '/v2/users/new' headers = {'content-type': 'application/json'} data = {} data['type'] = 'READER' if accessibleBundles is not None: data['bundles']=accessibleBundles json_data = json.dumps(data) response = self.__perform_rest_call(requestURL=url, restType='POST', body=json_data, headers=headers) return response
[ "def", "createReaderUser", "(", "self", ",", "accessibleBundles", "=", "None", ")", ":", "url", "=", "self", ".", "__serviceAccount", ".", "get_url", "(", ")", "+", "'/'", "+", "self", ".", "__serviceAccount", ".", "get_instance_id", "(", ")", "+", "'/v2/u...
Creates a new reader user with access to the specified bundle Ids
[ "Creates", "a", "new", "reader", "user", "with", "access", "to", "the", "specified", "bundle", "Ids" ]
082c6cdc250fb61bea99cba8ac3ee855ee77a410
https://github.com/IBM-Cloud/gp-python-client/blob/082c6cdc250fb61bea99cba8ac3ee855ee77a410/gpclient/gpclient.py#L304-L317
train
31,131
IBM-Cloud/gp-python-client
gpclient/gpclient.py
GPClient.__has_language
def __has_language(self, bundleId, languageId): """Returns ``True`` if the bundle has the language, ``False`` otherwise """ return True if self.__get_language_data(bundleId=bundleId, languageId=languageId) \ else False
python
def __has_language(self, bundleId, languageId): """Returns ``True`` if the bundle has the language, ``False`` otherwise """ return True if self.__get_language_data(bundleId=bundleId, languageId=languageId) \ else False
[ "def", "__has_language", "(", "self", ",", "bundleId", ",", "languageId", ")", ":", "return", "True", "if", "self", ".", "__get_language_data", "(", "bundleId", "=", "bundleId", ",", "languageId", "=", "languageId", ")", "else", "False" ]
Returns ``True`` if the bundle has the language, ``False`` otherwise
[ "Returns", "True", "if", "the", "bundle", "has", "the", "language", "False", "otherwise" ]
082c6cdc250fb61bea99cba8ac3ee855ee77a410
https://github.com/IBM-Cloud/gp-python-client/blob/082c6cdc250fb61bea99cba8ac3ee855ee77a410/gpclient/gpclient.py#L387-L392
train
31,132
IBM-Cloud/gp-python-client
gpclient/gpclient.py
GPClient.__get_keys_map
def __get_keys_map(self, bundleId, languageId, fallback=False): """Returns key-value pairs for the specified language. If fallback is ``True``, source language value is used if translated value is not available. """ return self.__get_language_data(bundleId=bundleId, languageId=languageId, fallback=fallback)
python
def __get_keys_map(self, bundleId, languageId, fallback=False): """Returns key-value pairs for the specified language. If fallback is ``True``, source language value is used if translated value is not available. """ return self.__get_language_data(bundleId=bundleId, languageId=languageId, fallback=fallback)
[ "def", "__get_keys_map", "(", "self", ",", "bundleId", ",", "languageId", ",", "fallback", "=", "False", ")", ":", "return", "self", ".", "__get_language_data", "(", "bundleId", "=", "bundleId", ",", "languageId", "=", "languageId", ",", "fallback", "=", "fa...
Returns key-value pairs for the specified language. If fallback is ``True``, source language value is used if translated value is not available.
[ "Returns", "key", "-", "value", "pairs", "for", "the", "specified", "language", ".", "If", "fallback", "is", "True", "source", "language", "value", "is", "used", "if", "translated", "value", "is", "not", "available", "." ]
082c6cdc250fb61bea99cba8ac3ee855ee77a410
https://github.com/IBM-Cloud/gp-python-client/blob/082c6cdc250fb61bea99cba8ac3ee855ee77a410/gpclient/gpclient.py#L394-L400
train
31,133
IBM-Cloud/gp-python-client
gpclient/gpclient.py
GPClient.__get_value
def __get_value(self, bundleId, languageId, resourceKey, fallback=False): """Returns the value for the key. If fallback is ``True``, source language value is used if translated value is not available. If the key is not found, returns ``None``. """ resourceEntryData = self.__get_resource_entry_data(bundleId=bundleId, languageId=languageId, resourceKey=resourceKey, fallback=fallback) if not resourceEntryData: return None value = resourceEntryData.get(self.__RESPONSE_TRANSLATION_KEY) return value
python
def __get_value(self, bundleId, languageId, resourceKey, fallback=False): """Returns the value for the key. If fallback is ``True``, source language value is used if translated value is not available. If the key is not found, returns ``None``. """ resourceEntryData = self.__get_resource_entry_data(bundleId=bundleId, languageId=languageId, resourceKey=resourceKey, fallback=fallback) if not resourceEntryData: return None value = resourceEntryData.get(self.__RESPONSE_TRANSLATION_KEY) return value
[ "def", "__get_value", "(", "self", ",", "bundleId", ",", "languageId", ",", "resourceKey", ",", "fallback", "=", "False", ")", ":", "resourceEntryData", "=", "self", ".", "__get_resource_entry_data", "(", "bundleId", "=", "bundleId", ",", "languageId", "=", "l...
Returns the value for the key. If fallback is ``True``, source language value is used if translated value is not available. If the key is not found, returns ``None``.
[ "Returns", "the", "value", "for", "the", "key", ".", "If", "fallback", "is", "True", "source", "language", "value", "is", "used", "if", "translated", "value", "is", "not", "available", ".", "If", "the", "key", "is", "not", "found", "returns", "None", "."...
082c6cdc250fb61bea99cba8ac3ee855ee77a410
https://github.com/IBM-Cloud/gp-python-client/blob/082c6cdc250fb61bea99cba8ac3ee855ee77a410/gpclient/gpclient.py#L402-L415
train
31,134
IBM-Cloud/gp-python-client
gpclient/gpclient.py
GPClient.get_avaliable_languages
def get_avaliable_languages(self, bundleId): """Returns a list of avaliable languages in the bundle""" bundleData = self.__get_bundle_data(bundleId) if not bundleData: return [] sourceLanguage = bundleData.get(self.__RESPONSE_SRC_LANGUAGE_KEY) languages = bundleData.get(self.__RESPONSE_TARGET_LANGUAGES_KEY) languages.append(sourceLanguage) return languages if languages else []
python
def get_avaliable_languages(self, bundleId): """Returns a list of avaliable languages in the bundle""" bundleData = self.__get_bundle_data(bundleId) if not bundleData: return [] sourceLanguage = bundleData.get(self.__RESPONSE_SRC_LANGUAGE_KEY) languages = bundleData.get(self.__RESPONSE_TARGET_LANGUAGES_KEY) languages.append(sourceLanguage) return languages if languages else []
[ "def", "get_avaliable_languages", "(", "self", ",", "bundleId", ")", ":", "bundleData", "=", "self", ".", "__get_bundle_data", "(", "bundleId", ")", "if", "not", "bundleData", ":", "return", "[", "]", "sourceLanguage", "=", "bundleData", ".", "get", "(", "se...
Returns a list of avaliable languages in the bundle
[ "Returns", "a", "list", "of", "avaliable", "languages", "in", "the", "bundle" ]
082c6cdc250fb61bea99cba8ac3ee855ee77a410
https://github.com/IBM-Cloud/gp-python-client/blob/082c6cdc250fb61bea99cba8ac3ee855ee77a410/gpclient/gpclient.py#L423-L434
train
31,135
IBM-Cloud/gp-python-client
gpclient/gpclient.py
GPClient.create_bundle
def create_bundle(self, bundleId, data=None): """Creates a bundle using Globalization Pipeline service""" headers={'content-type':'application/json'} url = self.__get_base_bundle_url() + "/" + bundleId if data is None: data = {} data['sourceLanguage'] = 'en' data['targetLanguages'] = [] data['notes']=[] data['metadata']={} data['partner']='' data['segmentSeparatorPattern']='' data['noTranslationPattern']='' json_data = json.dumps(data) response = self.__perform_rest_call(requestURL=url, restType='PUT', body=json_data, headers=headers) return response
python
def create_bundle(self, bundleId, data=None): """Creates a bundle using Globalization Pipeline service""" headers={'content-type':'application/json'} url = self.__get_base_bundle_url() + "/" + bundleId if data is None: data = {} data['sourceLanguage'] = 'en' data['targetLanguages'] = [] data['notes']=[] data['metadata']={} data['partner']='' data['segmentSeparatorPattern']='' data['noTranslationPattern']='' json_data = json.dumps(data) response = self.__perform_rest_call(requestURL=url, restType='PUT', body=json_data, headers=headers) return response
[ "def", "create_bundle", "(", "self", ",", "bundleId", ",", "data", "=", "None", ")", ":", "headers", "=", "{", "'content-type'", ":", "'application/json'", "}", "url", "=", "self", ".", "__get_base_bundle_url", "(", ")", "+", "\"/\"", "+", "bundleId", "if"...
Creates a bundle using Globalization Pipeline service
[ "Creates", "a", "bundle", "using", "Globalization", "Pipeline", "service" ]
082c6cdc250fb61bea99cba8ac3ee855ee77a410
https://github.com/IBM-Cloud/gp-python-client/blob/082c6cdc250fb61bea99cba8ac3ee855ee77a410/gpclient/gpclient.py#L436-L451
train
31,136
IBM-Cloud/gp-python-client
gpclient/gpclient.py
GPClient.update_resource_entry
def update_resource_entry(self, bundleId, languageId, resourceKey, data=None): """Updates the resource entry for a particular key in a target language for a specific bundle in the globalization pipeline""" headers={'content-type':'application/json'} url = self.__get_base_bundle_url() + "/" + bundleId + "/" + languageId + "/" + resourceKey json_data = {} if not data is None: json_data = json.dumps(data) response = self.__perform_rest_call(requestURL=url, restType='POST', body=json_data, headers=headers) return response
python
def update_resource_entry(self, bundleId, languageId, resourceKey, data=None): """Updates the resource entry for a particular key in a target language for a specific bundle in the globalization pipeline""" headers={'content-type':'application/json'} url = self.__get_base_bundle_url() + "/" + bundleId + "/" + languageId + "/" + resourceKey json_data = {} if not data is None: json_data = json.dumps(data) response = self.__perform_rest_call(requestURL=url, restType='POST', body=json_data, headers=headers) return response
[ "def", "update_resource_entry", "(", "self", ",", "bundleId", ",", "languageId", ",", "resourceKey", ",", "data", "=", "None", ")", ":", "headers", "=", "{", "'content-type'", ":", "'application/json'", "}", "url", "=", "self", ".", "__get_base_bundle_url", "(...
Updates the resource entry for a particular key in a target language for a specific bundle in the globalization pipeline
[ "Updates", "the", "resource", "entry", "for", "a", "particular", "key", "in", "a", "target", "language", "for", "a", "specific", "bundle", "in", "the", "globalization", "pipeline" ]
082c6cdc250fb61bea99cba8ac3ee855ee77a410
https://github.com/IBM-Cloud/gp-python-client/blob/082c6cdc250fb61bea99cba8ac3ee855ee77a410/gpclient/gpclient.py#L480-L489
train
31,137
IBM-Cloud/gp-python-client
gpclient/gptranslations.py
GPTranslations.__get_return_value
def __get_return_value(self, messageKey, value): """Determines the return value; used to prevent code duplication """ # if value is not None, return it # otherwise, either use the Translations fallback if there is one, # or return the message key back if value: return value else: if self._fallback: return self._fallback.gettext(messageKey) else: return messageKey
python
def __get_return_value(self, messageKey, value): """Determines the return value; used to prevent code duplication """ # if value is not None, return it # otherwise, either use the Translations fallback if there is one, # or return the message key back if value: return value else: if self._fallback: return self._fallback.gettext(messageKey) else: return messageKey
[ "def", "__get_return_value", "(", "self", ",", "messageKey", ",", "value", ")", ":", "# if value is not None, return it\r", "# otherwise, either use the Translations fallback if there is one,\r", "# or return the message key back\r", "if", "value", ":", "return", "value", "else",...
Determines the return value; used to prevent code duplication
[ "Determines", "the", "return", "value", ";", "used", "to", "prevent", "code", "duplication" ]
082c6cdc250fb61bea99cba8ac3ee855ee77a410
https://github.com/IBM-Cloud/gp-python-client/blob/082c6cdc250fb61bea99cba8ac3ee855ee77a410/gpclient/gptranslations.py#L107-L118
train
31,138
FlorianRhiem/pyGLFW
glfw/library.py
_find_library_candidates
def _find_library_candidates(library_names, library_file_extensions, library_search_paths): """ Finds and returns filenames which might be the library you are looking for. """ candidates = set() for library_name in library_names: for search_path in library_search_paths: glob_query = os.path.join(search_path, '*'+library_name+'*') for filename in glob.iglob(glob_query): filename = os.path.realpath(filename) if filename in candidates: continue basename = os.path.basename(filename) if basename.startswith('lib'+library_name): basename_end = basename[len('lib'+library_name):] elif basename.startswith(library_name): basename_end = basename[len(library_name):] else: continue for file_extension in library_file_extensions: if basename_end.startswith(file_extension): if basename_end[len(file_extension):][:1] in ('', '.'): candidates.add(filename) if basename_end.endswith(file_extension): basename_middle = basename_end[:-len(file_extension)] if all(c in '0123456789.' for c in basename_middle): candidates.add(filename) return candidates
python
def _find_library_candidates(library_names, library_file_extensions, library_search_paths): """ Finds and returns filenames which might be the library you are looking for. """ candidates = set() for library_name in library_names: for search_path in library_search_paths: glob_query = os.path.join(search_path, '*'+library_name+'*') for filename in glob.iglob(glob_query): filename = os.path.realpath(filename) if filename in candidates: continue basename = os.path.basename(filename) if basename.startswith('lib'+library_name): basename_end = basename[len('lib'+library_name):] elif basename.startswith(library_name): basename_end = basename[len(library_name):] else: continue for file_extension in library_file_extensions: if basename_end.startswith(file_extension): if basename_end[len(file_extension):][:1] in ('', '.'): candidates.add(filename) if basename_end.endswith(file_extension): basename_middle = basename_end[:-len(file_extension)] if all(c in '0123456789.' for c in basename_middle): candidates.add(filename) return candidates
[ "def", "_find_library_candidates", "(", "library_names", ",", "library_file_extensions", ",", "library_search_paths", ")", ":", "candidates", "=", "set", "(", ")", "for", "library_name", "in", "library_names", ":", "for", "search_path", "in", "library_search_paths", "...
Finds and returns filenames which might be the library you are looking for.
[ "Finds", "and", "returns", "filenames", "which", "might", "be", "the", "library", "you", "are", "looking", "for", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/library.py#L17-L46
train
31,139
FlorianRhiem/pyGLFW
glfw/library.py
_load_library
def _load_library(library_names, library_file_extensions, library_search_paths, version_check_callback): """ Finds, loads and returns the most recent version of the library. """ candidates = _find_library_candidates(library_names, library_file_extensions, library_search_paths) library_versions = [] for filename in candidates: version = version_check_callback(filename) if version is not None and version >= (3, 0, 0): library_versions.append((version, filename)) if not library_versions: return None library_versions.sort() return ctypes.CDLL(library_versions[-1][1])
python
def _load_library(library_names, library_file_extensions, library_search_paths, version_check_callback): """ Finds, loads and returns the most recent version of the library. """ candidates = _find_library_candidates(library_names, library_file_extensions, library_search_paths) library_versions = [] for filename in candidates: version = version_check_callback(filename) if version is not None and version >= (3, 0, 0): library_versions.append((version, filename)) if not library_versions: return None library_versions.sort() return ctypes.CDLL(library_versions[-1][1])
[ "def", "_load_library", "(", "library_names", ",", "library_file_extensions", ",", "library_search_paths", ",", "version_check_callback", ")", ":", "candidates", "=", "_find_library_candidates", "(", "library_names", ",", "library_file_extensions", ",", "library_search_paths"...
Finds, loads and returns the most recent version of the library.
[ "Finds", "loads", "and", "returns", "the", "most", "recent", "version", "of", "the", "library", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/library.py#L49-L66
train
31,140
FlorianRhiem/pyGLFW
glfw/library.py
_get_library_search_paths
def _get_library_search_paths(): """ Returns a list of library search paths, considering of the current working directory, default paths and paths from environment variables. """ search_paths = [ '', '/usr/lib64', '/usr/local/lib64', '/usr/lib', '/usr/local/lib', '/run/current-system/sw/lib', '/usr/lib/x86_64-linux-gnu/', os.path.abspath(os.path.dirname(__file__)) ] if sys.platform == 'darwin': path_environment_variable = 'DYLD_LIBRARY_PATH' else: path_environment_variable = 'LD_LIBRARY_PATH' if path_environment_variable in os.environ: search_paths.extend(os.environ[path_environment_variable].split(':')) return search_paths
python
def _get_library_search_paths(): """ Returns a list of library search paths, considering of the current working directory, default paths and paths from environment variables. """ search_paths = [ '', '/usr/lib64', '/usr/local/lib64', '/usr/lib', '/usr/local/lib', '/run/current-system/sw/lib', '/usr/lib/x86_64-linux-gnu/', os.path.abspath(os.path.dirname(__file__)) ] if sys.platform == 'darwin': path_environment_variable = 'DYLD_LIBRARY_PATH' else: path_environment_variable = 'LD_LIBRARY_PATH' if path_environment_variable in os.environ: search_paths.extend(os.environ[path_environment_variable].split(':')) return search_paths
[ "def", "_get_library_search_paths", "(", ")", ":", "search_paths", "=", "[", "''", ",", "'/usr/lib64'", ",", "'/usr/local/lib64'", ",", "'/usr/lib'", ",", "'/usr/local/lib'", ",", "'/run/current-system/sw/lib'", ",", "'/usr/lib/x86_64-linux-gnu/'", ",", "os", ".", "pa...
Returns a list of library search paths, considering of the current working directory, default paths and paths from environment variables.
[ "Returns", "a", "list", "of", "library", "search", "paths", "considering", "of", "the", "current", "working", "directory", "default", "paths", "and", "paths", "from", "environment", "variables", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/library.py#L123-L144
train
31,141
FlorianRhiem/pyGLFW
glfw/__init__.py
_prepare_errcheck
def _prepare_errcheck(): """ This function sets the errcheck attribute of all ctypes wrapped functions to evaluate the _exc_info_from_callback global variable and re-raise any exceptions that might have been raised in callbacks. It also modifies all callback types to automatically wrap the function using the _callback_exception_decorator. """ def errcheck(result, *args): global _exc_info_from_callback if _exc_info_from_callback is not None: exc = _exc_info_from_callback _exc_info_from_callback = None _reraise(exc[1], exc[2]) return result for symbol in dir(_glfw): if symbol.startswith('glfw'): getattr(_glfw, symbol).errcheck = errcheck _globals = globals() for symbol in _globals: if symbol.startswith('_GLFW') and symbol.endswith('fun'): def wrapper_cfunctype(func, cfunctype=_globals[symbol]): return cfunctype(_callback_exception_decorator(func)) _globals[symbol] = wrapper_cfunctype
python
def _prepare_errcheck(): """ This function sets the errcheck attribute of all ctypes wrapped functions to evaluate the _exc_info_from_callback global variable and re-raise any exceptions that might have been raised in callbacks. It also modifies all callback types to automatically wrap the function using the _callback_exception_decorator. """ def errcheck(result, *args): global _exc_info_from_callback if _exc_info_from_callback is not None: exc = _exc_info_from_callback _exc_info_from_callback = None _reraise(exc[1], exc[2]) return result for symbol in dir(_glfw): if symbol.startswith('glfw'): getattr(_glfw, symbol).errcheck = errcheck _globals = globals() for symbol in _globals: if symbol.startswith('_GLFW') and symbol.endswith('fun'): def wrapper_cfunctype(func, cfunctype=_globals[symbol]): return cfunctype(_callback_exception_decorator(func)) _globals[symbol] = wrapper_cfunctype
[ "def", "_prepare_errcheck", "(", ")", ":", "def", "errcheck", "(", "result", ",", "*", "args", ")", ":", "global", "_exc_info_from_callback", "if", "_exc_info_from_callback", "is", "not", "None", ":", "exc", "=", "_exc_info_from_callback", "_exc_info_from_callback",...
This function sets the errcheck attribute of all ctypes wrapped functions to evaluate the _exc_info_from_callback global variable and re-raise any exceptions that might have been raised in callbacks. It also modifies all callback types to automatically wrap the function using the _callback_exception_decorator.
[ "This", "function", "sets", "the", "errcheck", "attribute", "of", "all", "ctypes", "wrapped", "functions", "to", "evaluate", "the", "_exc_info_from_callback", "global", "variable", "and", "re", "-", "raise", "any", "exceptions", "that", "might", "have", "been", ...
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L503-L528
train
31,142
FlorianRhiem/pyGLFW
glfw/__init__.py
init
def init(): """ Initializes the GLFW library. Wrapper for: int glfwInit(void); """ cwd = _getcwd() res = _glfw.glfwInit() os.chdir(cwd) return res
python
def init(): """ Initializes the GLFW library. Wrapper for: int glfwInit(void); """ cwd = _getcwd() res = _glfw.glfwInit() os.chdir(cwd) return res
[ "def", "init", "(", ")", ":", "cwd", "=", "_getcwd", "(", ")", "res", "=", "_glfw", ".", "glfwInit", "(", ")", "os", ".", "chdir", "(", "cwd", ")", "return", "res" ]
Initializes the GLFW library. Wrapper for: int glfwInit(void);
[ "Initializes", "the", "GLFW", "library", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L599-L609
train
31,143
FlorianRhiem/pyGLFW
glfw/__init__.py
terminate
def terminate(): """ Terminates the GLFW library. Wrapper for: void glfwTerminate(void); """ for callback_repository in _callback_repositories: for window_addr in list(callback_repository.keys()): del callback_repository[window_addr] for window_addr in list(_window_user_data_repository.keys()): del _window_user_data_repository[window_addr] _glfw.glfwTerminate()
python
def terminate(): """ Terminates the GLFW library. Wrapper for: void glfwTerminate(void); """ for callback_repository in _callback_repositories: for window_addr in list(callback_repository.keys()): del callback_repository[window_addr] for window_addr in list(_window_user_data_repository.keys()): del _window_user_data_repository[window_addr] _glfw.glfwTerminate()
[ "def", "terminate", "(", ")", ":", "for", "callback_repository", "in", "_callback_repositories", ":", "for", "window_addr", "in", "list", "(", "callback_repository", ".", "keys", "(", ")", ")", ":", "del", "callback_repository", "[", "window_addr", "]", "for", ...
Terminates the GLFW library. Wrapper for: void glfwTerminate(void);
[ "Terminates", "the", "GLFW", "library", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L613-L626
train
31,144
FlorianRhiem/pyGLFW
glfw/__init__.py
get_version
def get_version(): """ Retrieves the version of the GLFW library. Wrapper for: void glfwGetVersion(int* major, int* minor, int* rev); """ major_value = ctypes.c_int(0) major = ctypes.pointer(major_value) minor_value = ctypes.c_int(0) minor = ctypes.pointer(minor_value) rev_value = ctypes.c_int(0) rev = ctypes.pointer(rev_value) _glfw.glfwGetVersion(major, minor, rev) return major_value.value, minor_value.value, rev_value.value
python
def get_version(): """ Retrieves the version of the GLFW library. Wrapper for: void glfwGetVersion(int* major, int* minor, int* rev); """ major_value = ctypes.c_int(0) major = ctypes.pointer(major_value) minor_value = ctypes.c_int(0) minor = ctypes.pointer(minor_value) rev_value = ctypes.c_int(0) rev = ctypes.pointer(rev_value) _glfw.glfwGetVersion(major, minor, rev) return major_value.value, minor_value.value, rev_value.value
[ "def", "get_version", "(", ")", ":", "major_value", "=", "ctypes", ".", "c_int", "(", "0", ")", "major", "=", "ctypes", ".", "pointer", "(", "major_value", ")", "minor_value", "=", "ctypes", ".", "c_int", "(", "0", ")", "minor", "=", "ctypes", ".", "...
Retrieves the version of the GLFW library. Wrapper for: void glfwGetVersion(int* major, int* minor, int* rev);
[ "Retrieves", "the", "version", "of", "the", "GLFW", "library", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L632-L646
train
31,145
FlorianRhiem/pyGLFW
glfw/__init__.py
_raise_glfw_errors_as_exceptions
def _raise_glfw_errors_as_exceptions(error_code, description): """ Default error callback that raises GLFWError exceptions for glfw errors. Set an alternative error callback or set glfw.ERROR_REPORTING to False to disable this behavior. """ global ERROR_REPORTING if ERROR_REPORTING: message = "(%d) %s" % (error_code, description) raise GLFWError(message)
python
def _raise_glfw_errors_as_exceptions(error_code, description): """ Default error callback that raises GLFWError exceptions for glfw errors. Set an alternative error callback or set glfw.ERROR_REPORTING to False to disable this behavior. """ global ERROR_REPORTING if ERROR_REPORTING: message = "(%d) %s" % (error_code, description) raise GLFWError(message)
[ "def", "_raise_glfw_errors_as_exceptions", "(", "error_code", ",", "description", ")", ":", "global", "ERROR_REPORTING", "if", "ERROR_REPORTING", ":", "message", "=", "\"(%d) %s\"", "%", "(", "error_code", ",", "description", ")", "raise", "GLFWError", "(", "message...
Default error callback that raises GLFWError exceptions for glfw errors. Set an alternative error callback or set glfw.ERROR_REPORTING to False to disable this behavior.
[ "Default", "error", "callback", "that", "raises", "GLFWError", "exceptions", "for", "glfw", "errors", ".", "Set", "an", "alternative", "error", "callback", "or", "set", "glfw", ".", "ERROR_REPORTING", "to", "False", "to", "disable", "this", "behavior", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L660-L669
train
31,146
FlorianRhiem/pyGLFW
glfw/__init__.py
get_monitors
def get_monitors(): """ Returns the currently connected monitors. Wrapper for: GLFWmonitor** glfwGetMonitors(int* count); """ count_value = ctypes.c_int(0) count = ctypes.pointer(count_value) result = _glfw.glfwGetMonitors(count) monitors = [result[i] for i in range(count_value.value)] return monitors
python
def get_monitors(): """ Returns the currently connected monitors. Wrapper for: GLFWmonitor** glfwGetMonitors(int* count); """ count_value = ctypes.c_int(0) count = ctypes.pointer(count_value) result = _glfw.glfwGetMonitors(count) monitors = [result[i] for i in range(count_value.value)] return monitors
[ "def", "get_monitors", "(", ")", ":", "count_value", "=", "ctypes", ".", "c_int", "(", "0", ")", "count", "=", "ctypes", ".", "pointer", "(", "count_value", ")", "result", "=", "_glfw", ".", "glfwGetMonitors", "(", "count", ")", "monitors", "=", "[", "...
Returns the currently connected monitors. Wrapper for: GLFWmonitor** glfwGetMonitors(int* count);
[ "Returns", "the", "currently", "connected", "monitors", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L698-L709
train
31,147
FlorianRhiem/pyGLFW
glfw/__init__.py
get_monitor_pos
def get_monitor_pos(monitor): """ Returns the position of the monitor's viewport on the virtual screen. Wrapper for: void glfwGetMonitorPos(GLFWmonitor* monitor, int* xpos, int* ypos); """ xpos_value = ctypes.c_int(0) xpos = ctypes.pointer(xpos_value) ypos_value = ctypes.c_int(0) ypos = ctypes.pointer(ypos_value) _glfw.glfwGetMonitorPos(monitor, xpos, ypos) return xpos_value.value, ypos_value.value
python
def get_monitor_pos(monitor): """ Returns the position of the monitor's viewport on the virtual screen. Wrapper for: void glfwGetMonitorPos(GLFWmonitor* monitor, int* xpos, int* ypos); """ xpos_value = ctypes.c_int(0) xpos = ctypes.pointer(xpos_value) ypos_value = ctypes.c_int(0) ypos = ctypes.pointer(ypos_value) _glfw.glfwGetMonitorPos(monitor, xpos, ypos) return xpos_value.value, ypos_value.value
[ "def", "get_monitor_pos", "(", "monitor", ")", ":", "xpos_value", "=", "ctypes", ".", "c_int", "(", "0", ")", "xpos", "=", "ctypes", ".", "pointer", "(", "xpos_value", ")", "ypos_value", "=", "ctypes", ".", "c_int", "(", "0", ")", "ypos", "=", "ctypes"...
Returns the position of the monitor's viewport on the virtual screen. Wrapper for: void glfwGetMonitorPos(GLFWmonitor* monitor, int* xpos, int* ypos);
[ "Returns", "the", "position", "of", "the", "monitor", "s", "viewport", "on", "the", "virtual", "screen", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L726-L738
train
31,148
FlorianRhiem/pyGLFW
glfw/__init__.py
get_monitor_physical_size
def get_monitor_physical_size(monitor): """ Returns the physical size of the monitor. Wrapper for: void glfwGetMonitorPhysicalSize(GLFWmonitor* monitor, int* width, int* height); """ width_value = ctypes.c_int(0) width = ctypes.pointer(width_value) height_value = ctypes.c_int(0) height = ctypes.pointer(height_value) _glfw.glfwGetMonitorPhysicalSize(monitor, width, height) return width_value.value, height_value.value
python
def get_monitor_physical_size(monitor): """ Returns the physical size of the monitor. Wrapper for: void glfwGetMonitorPhysicalSize(GLFWmonitor* monitor, int* width, int* height); """ width_value = ctypes.c_int(0) width = ctypes.pointer(width_value) height_value = ctypes.c_int(0) height = ctypes.pointer(height_value) _glfw.glfwGetMonitorPhysicalSize(monitor, width, height) return width_value.value, height_value.value
[ "def", "get_monitor_physical_size", "(", "monitor", ")", ":", "width_value", "=", "ctypes", ".", "c_int", "(", "0", ")", "width", "=", "ctypes", ".", "pointer", "(", "width_value", ")", "height_value", "=", "ctypes", ".", "c_int", "(", "0", ")", "height", ...
Returns the physical size of the monitor. Wrapper for: void glfwGetMonitorPhysicalSize(GLFWmonitor* monitor, int* width, int* height);
[ "Returns", "the", "physical", "size", "of", "the", "monitor", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L744-L756
train
31,149
FlorianRhiem/pyGLFW
glfw/__init__.py
set_monitor_callback
def set_monitor_callback(cbfun): """ Sets the monitor configuration callback. Wrapper for: GLFWmonitorfun glfwSetMonitorCallback(GLFWmonitorfun cbfun); """ global _monitor_callback previous_callback = _monitor_callback if cbfun is None: cbfun = 0 c_cbfun = _GLFWmonitorfun(cbfun) _monitor_callback = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetMonitorCallback(cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
python
def set_monitor_callback(cbfun): """ Sets the monitor configuration callback. Wrapper for: GLFWmonitorfun glfwSetMonitorCallback(GLFWmonitorfun cbfun); """ global _monitor_callback previous_callback = _monitor_callback if cbfun is None: cbfun = 0 c_cbfun = _GLFWmonitorfun(cbfun) _monitor_callback = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetMonitorCallback(cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
[ "def", "set_monitor_callback", "(", "cbfun", ")", ":", "global", "_monitor_callback", "previous_callback", "=", "_monitor_callback", "if", "cbfun", "is", "None", ":", "cbfun", "=", "0", "c_cbfun", "=", "_GLFWmonitorfun", "(", "cbfun", ")", "_monitor_callback", "="...
Sets the monitor configuration callback. Wrapper for: GLFWmonitorfun glfwSetMonitorCallback(GLFWmonitorfun cbfun);
[ "Sets", "the", "monitor", "configuration", "callback", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L772-L788
train
31,150
FlorianRhiem/pyGLFW
glfw/__init__.py
get_video_modes
def get_video_modes(monitor): """ Returns the available video modes for the specified monitor. Wrapper for: const GLFWvidmode* glfwGetVideoModes(GLFWmonitor* monitor, int* count); """ count_value = ctypes.c_int(0) count = ctypes.pointer(count_value) result = _glfw.glfwGetVideoModes(monitor, count) videomodes = [result[i].unwrap() for i in range(count_value.value)] return videomodes
python
def get_video_modes(monitor): """ Returns the available video modes for the specified monitor. Wrapper for: const GLFWvidmode* glfwGetVideoModes(GLFWmonitor* monitor, int* count); """ count_value = ctypes.c_int(0) count = ctypes.pointer(count_value) result = _glfw.glfwGetVideoModes(monitor, count) videomodes = [result[i].unwrap() for i in range(count_value.value)] return videomodes
[ "def", "get_video_modes", "(", "monitor", ")", ":", "count_value", "=", "ctypes", ".", "c_int", "(", "0", ")", "count", "=", "ctypes", ".", "pointer", "(", "count_value", ")", "result", "=", "_glfw", ".", "glfwGetVideoModes", "(", "monitor", ",", "count", ...
Returns the available video modes for the specified monitor. Wrapper for: const GLFWvidmode* glfwGetVideoModes(GLFWmonitor* monitor, int* count);
[ "Returns", "the", "available", "video", "modes", "for", "the", "specified", "monitor", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L793-L804
train
31,151
FlorianRhiem/pyGLFW
glfw/__init__.py
set_gamma_ramp
def set_gamma_ramp(monitor, ramp): """ Sets the current gamma ramp for the specified monitor. Wrapper for: void glfwSetGammaRamp(GLFWmonitor* monitor, const GLFWgammaramp* ramp); """ gammaramp = _GLFWgammaramp() gammaramp.wrap(ramp) _glfw.glfwSetGammaRamp(monitor, ctypes.pointer(gammaramp))
python
def set_gamma_ramp(monitor, ramp): """ Sets the current gamma ramp for the specified monitor. Wrapper for: void glfwSetGammaRamp(GLFWmonitor* monitor, const GLFWgammaramp* ramp); """ gammaramp = _GLFWgammaramp() gammaramp.wrap(ramp) _glfw.glfwSetGammaRamp(monitor, ctypes.pointer(gammaramp))
[ "def", "set_gamma_ramp", "(", "monitor", ",", "ramp", ")", ":", "gammaramp", "=", "_GLFWgammaramp", "(", ")", "gammaramp", ".", "wrap", "(", "ramp", ")", "_glfw", ".", "glfwSetGammaRamp", "(", "monitor", ",", "ctypes", ".", "pointer", "(", "gammaramp", ")"...
Sets the current gamma ramp for the specified monitor. Wrapper for: void glfwSetGammaRamp(GLFWmonitor* monitor, const GLFWgammaramp* ramp);
[ "Sets", "the", "current", "gamma", "ramp", "for", "the", "specified", "monitor", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L845-L854
train
31,152
FlorianRhiem/pyGLFW
glfw/__init__.py
create_window
def create_window(width, height, title, monitor, share): """ Creates a window and its associated context. Wrapper for: GLFWwindow* glfwCreateWindow(int width, int height, const char* title, GLFWmonitor* monitor, GLFWwindow* share); """ return _glfw.glfwCreateWindow(width, height, _to_char_p(title), monitor, share)
python
def create_window(width, height, title, monitor, share): """ Creates a window and its associated context. Wrapper for: GLFWwindow* glfwCreateWindow(int width, int height, const char* title, GLFWmonitor* monitor, GLFWwindow* share); """ return _glfw.glfwCreateWindow(width, height, _to_char_p(title), monitor, share)
[ "def", "create_window", "(", "width", ",", "height", ",", "title", ",", "monitor", ",", "share", ")", ":", "return", "_glfw", ".", "glfwCreateWindow", "(", "width", ",", "height", ",", "_to_char_p", "(", "title", ")", ",", "monitor", ",", "share", ")" ]
Creates a window and its associated context. Wrapper for: GLFWwindow* glfwCreateWindow(int width, int height, const char* title, GLFWmonitor* monitor, GLFWwindow* share);
[ "Creates", "a", "window", "and", "its", "associated", "context", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L885-L893
train
31,153
FlorianRhiem/pyGLFW
glfw/__init__.py
get_window_pos
def get_window_pos(window): """ Retrieves the position of the client area of the specified window. Wrapper for: void glfwGetWindowPos(GLFWwindow* window, int* xpos, int* ypos); """ xpos_value = ctypes.c_int(0) xpos = ctypes.pointer(xpos_value) ypos_value = ctypes.c_int(0) ypos = ctypes.pointer(ypos_value) _glfw.glfwGetWindowPos(window, xpos, ypos) return xpos_value.value, ypos_value.value
python
def get_window_pos(window): """ Retrieves the position of the client area of the specified window. Wrapper for: void glfwGetWindowPos(GLFWwindow* window, int* xpos, int* ypos); """ xpos_value = ctypes.c_int(0) xpos = ctypes.pointer(xpos_value) ypos_value = ctypes.c_int(0) ypos = ctypes.pointer(ypos_value) _glfw.glfwGetWindowPos(window, xpos, ypos) return xpos_value.value, ypos_value.value
[ "def", "get_window_pos", "(", "window", ")", ":", "xpos_value", "=", "ctypes", ".", "c_int", "(", "0", ")", "xpos", "=", "ctypes", ".", "pointer", "(", "xpos_value", ")", "ypos_value", "=", "ctypes", ".", "c_int", "(", "0", ")", "ypos", "=", "ctypes", ...
Retrieves the position of the client area of the specified window. Wrapper for: void glfwGetWindowPos(GLFWwindow* window, int* xpos, int* ypos);
[ "Retrieves", "the", "position", "of", "the", "client", "area", "of", "the", "specified", "window", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L952-L964
train
31,154
FlorianRhiem/pyGLFW
glfw/__init__.py
get_window_size
def get_window_size(window): """ Retrieves the size of the client area of the specified window. Wrapper for: void glfwGetWindowSize(GLFWwindow* window, int* width, int* height); """ width_value = ctypes.c_int(0) width = ctypes.pointer(width_value) height_value = ctypes.c_int(0) height = ctypes.pointer(height_value) _glfw.glfwGetWindowSize(window, width, height) return width_value.value, height_value.value
python
def get_window_size(window): """ Retrieves the size of the client area of the specified window. Wrapper for: void glfwGetWindowSize(GLFWwindow* window, int* width, int* height); """ width_value = ctypes.c_int(0) width = ctypes.pointer(width_value) height_value = ctypes.c_int(0) height = ctypes.pointer(height_value) _glfw.glfwGetWindowSize(window, width, height) return width_value.value, height_value.value
[ "def", "get_window_size", "(", "window", ")", ":", "width_value", "=", "ctypes", ".", "c_int", "(", "0", ")", "width", "=", "ctypes", ".", "pointer", "(", "width_value", ")", "height_value", "=", "ctypes", ".", "c_int", "(", "0", ")", "height", "=", "c...
Retrieves the size of the client area of the specified window. Wrapper for: void glfwGetWindowSize(GLFWwindow* window, int* width, int* height);
[ "Retrieves", "the", "size", "of", "the", "client", "area", "of", "the", "specified", "window", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L983-L995
train
31,155
FlorianRhiem/pyGLFW
glfw/__init__.py
get_framebuffer_size
def get_framebuffer_size(window): """ Retrieves the size of the framebuffer of the specified window. Wrapper for: void glfwGetFramebufferSize(GLFWwindow* window, int* width, int* height); """ width_value = ctypes.c_int(0) width = ctypes.pointer(width_value) height_value = ctypes.c_int(0) height = ctypes.pointer(height_value) _glfw.glfwGetFramebufferSize(window, width, height) return width_value.value, height_value.value
python
def get_framebuffer_size(window): """ Retrieves the size of the framebuffer of the specified window. Wrapper for: void glfwGetFramebufferSize(GLFWwindow* window, int* width, int* height); """ width_value = ctypes.c_int(0) width = ctypes.pointer(width_value) height_value = ctypes.c_int(0) height = ctypes.pointer(height_value) _glfw.glfwGetFramebufferSize(window, width, height) return width_value.value, height_value.value
[ "def", "get_framebuffer_size", "(", "window", ")", ":", "width_value", "=", "ctypes", ".", "c_int", "(", "0", ")", "width", "=", "ctypes", ".", "pointer", "(", "width_value", ")", "height_value", "=", "ctypes", ".", "c_int", "(", "0", ")", "height", "=",...
Retrieves the size of the framebuffer of the specified window. Wrapper for: void glfwGetFramebufferSize(GLFWwindow* window, int* width, int* height);
[ "Retrieves", "the", "size", "of", "the", "framebuffer", "of", "the", "specified", "window", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L1014-L1026
train
31,156
FlorianRhiem/pyGLFW
glfw/__init__.py
set_window_user_pointer
def set_window_user_pointer(window, pointer): """ Sets the user pointer of the specified window. You may pass a normal python object into this function and it will be wrapped automatically. The object will be kept in existence until the pointer is set to something else or until the window is destroyed. Wrapper for: void glfwSetWindowUserPointer(GLFWwindow* window, void* pointer); """ data = (False, pointer) if not isinstance(pointer, ctypes.c_void_p): data = (True, pointer) # Create a void pointer for the python object pointer = ctypes.cast(ctypes.pointer(ctypes.py_object(pointer)), ctypes.c_void_p) window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value _window_user_data_repository[window_addr] = data _glfw.glfwSetWindowUserPointer(window, pointer)
python
def set_window_user_pointer(window, pointer): """ Sets the user pointer of the specified window. You may pass a normal python object into this function and it will be wrapped automatically. The object will be kept in existence until the pointer is set to something else or until the window is destroyed. Wrapper for: void glfwSetWindowUserPointer(GLFWwindow* window, void* pointer); """ data = (False, pointer) if not isinstance(pointer, ctypes.c_void_p): data = (True, pointer) # Create a void pointer for the python object pointer = ctypes.cast(ctypes.pointer(ctypes.py_object(pointer)), ctypes.c_void_p) window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value _window_user_data_repository[window_addr] = data _glfw.glfwSetWindowUserPointer(window, pointer)
[ "def", "set_window_user_pointer", "(", "window", ",", "pointer", ")", ":", "data", "=", "(", "False", ",", "pointer", ")", "if", "not", "isinstance", "(", "pointer", ",", "ctypes", ".", "c_void_p", ")", ":", "data", "=", "(", "True", ",", "pointer", ")...
Sets the user pointer of the specified window. You may pass a normal python object into this function and it will be wrapped automatically. The object will be kept in existence until the pointer is set to something else or until the window is destroyed. Wrapper for: void glfwSetWindowUserPointer(GLFWwindow* window, void* pointer);
[ "Sets", "the", "user", "pointer", "of", "the", "specified", "window", ".", "You", "may", "pass", "a", "normal", "python", "object", "into", "this", "function", "and", "it", "will", "be", "wrapped", "automatically", ".", "The", "object", "will", "be", "kept...
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L1099-L1118
train
31,157
FlorianRhiem/pyGLFW
glfw/__init__.py
get_window_user_pointer
def get_window_user_pointer(window): """ Returns the user pointer of the specified window. Wrapper for: void* glfwGetWindowUserPointer(GLFWwindow* window); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _window_user_data_repository: data = _window_user_data_repository[window_addr] is_wrapped_py_object = data[0] if is_wrapped_py_object: return data[1] return _glfw.glfwGetWindowUserPointer(window)
python
def get_window_user_pointer(window): """ Returns the user pointer of the specified window. Wrapper for: void* glfwGetWindowUserPointer(GLFWwindow* window); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _window_user_data_repository: data = _window_user_data_repository[window_addr] is_wrapped_py_object = data[0] if is_wrapped_py_object: return data[1] return _glfw.glfwGetWindowUserPointer(window)
[ "def", "get_window_user_pointer", "(", "window", ")", ":", "window_addr", "=", "ctypes", ".", "cast", "(", "ctypes", ".", "pointer", "(", "window", ")", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_long", ")", ")", ".", "contents", ".", "value",...
Returns the user pointer of the specified window. Wrapper for: void* glfwGetWindowUserPointer(GLFWwindow* window);
[ "Returns", "the", "user", "pointer", "of", "the", "specified", "window", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L1122-L1138
train
31,158
FlorianRhiem/pyGLFW
glfw/__init__.py
set_window_pos_callback
def set_window_pos_callback(window, cbfun): """ Sets the position callback for the specified window. Wrapper for: GLFWwindowposfun glfwSetWindowPosCallback(GLFWwindow* window, GLFWwindowposfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _window_pos_callback_repository: previous_callback = _window_pos_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWwindowposfun(cbfun) _window_pos_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetWindowPosCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
python
def set_window_pos_callback(window, cbfun): """ Sets the position callback for the specified window. Wrapper for: GLFWwindowposfun glfwSetWindowPosCallback(GLFWwindow* window, GLFWwindowposfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _window_pos_callback_repository: previous_callback = _window_pos_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWwindowposfun(cbfun) _window_pos_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetWindowPosCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
[ "def", "set_window_pos_callback", "(", "window", ",", "cbfun", ")", ":", "window_addr", "=", "ctypes", ".", "cast", "(", "ctypes", ".", "pointer", "(", "window", ")", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_long", ")", ")", ".", "contents",...
Sets the position callback for the specified window. Wrapper for: GLFWwindowposfun glfwSetWindowPosCallback(GLFWwindow* window, GLFWwindowposfun cbfun);
[ "Sets", "the", "position", "callback", "for", "the", "specified", "window", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L1145-L1165
train
31,159
FlorianRhiem/pyGLFW
glfw/__init__.py
set_window_size_callback
def set_window_size_callback(window, cbfun): """ Sets the size callback for the specified window. Wrapper for: GLFWwindowsizefun glfwSetWindowSizeCallback(GLFWwindow* window, GLFWwindowsizefun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _window_size_callback_repository: previous_callback = _window_size_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWwindowsizefun(cbfun) _window_size_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetWindowSizeCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
python
def set_window_size_callback(window, cbfun): """ Sets the size callback for the specified window. Wrapper for: GLFWwindowsizefun glfwSetWindowSizeCallback(GLFWwindow* window, GLFWwindowsizefun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _window_size_callback_repository: previous_callback = _window_size_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWwindowsizefun(cbfun) _window_size_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetWindowSizeCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
[ "def", "set_window_size_callback", "(", "window", ",", "cbfun", ")", ":", "window_addr", "=", "ctypes", ".", "cast", "(", "ctypes", ".", "pointer", "(", "window", ")", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_long", ")", ")", ".", "contents"...
Sets the size callback for the specified window. Wrapper for: GLFWwindowsizefun glfwSetWindowSizeCallback(GLFWwindow* window, GLFWwindowsizefun cbfun);
[ "Sets", "the", "size", "callback", "for", "the", "specified", "window", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L1172-L1192
train
31,160
FlorianRhiem/pyGLFW
glfw/__init__.py
set_window_close_callback
def set_window_close_callback(window, cbfun): """ Sets the close callback for the specified window. Wrapper for: GLFWwindowclosefun glfwSetWindowCloseCallback(GLFWwindow* window, GLFWwindowclosefun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _window_close_callback_repository: previous_callback = _window_close_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWwindowclosefun(cbfun) _window_close_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetWindowCloseCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
python
def set_window_close_callback(window, cbfun): """ Sets the close callback for the specified window. Wrapper for: GLFWwindowclosefun glfwSetWindowCloseCallback(GLFWwindow* window, GLFWwindowclosefun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _window_close_callback_repository: previous_callback = _window_close_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWwindowclosefun(cbfun) _window_close_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetWindowCloseCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
[ "def", "set_window_close_callback", "(", "window", ",", "cbfun", ")", ":", "window_addr", "=", "ctypes", ".", "cast", "(", "ctypes", ".", "pointer", "(", "window", ")", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_long", ")", ")", ".", "contents...
Sets the close callback for the specified window. Wrapper for: GLFWwindowclosefun glfwSetWindowCloseCallback(GLFWwindow* window, GLFWwindowclosefun cbfun);
[ "Sets", "the", "close", "callback", "for", "the", "specified", "window", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L1199-L1219
train
31,161
FlorianRhiem/pyGLFW
glfw/__init__.py
set_window_refresh_callback
def set_window_refresh_callback(window, cbfun): """ Sets the refresh callback for the specified window. Wrapper for: GLFWwindowrefreshfun glfwSetWindowRefreshCallback(GLFWwindow* window, GLFWwindowrefreshfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _window_refresh_callback_repository: previous_callback = _window_refresh_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWwindowrefreshfun(cbfun) _window_refresh_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetWindowRefreshCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
python
def set_window_refresh_callback(window, cbfun): """ Sets the refresh callback for the specified window. Wrapper for: GLFWwindowrefreshfun glfwSetWindowRefreshCallback(GLFWwindow* window, GLFWwindowrefreshfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _window_refresh_callback_repository: previous_callback = _window_refresh_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWwindowrefreshfun(cbfun) _window_refresh_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetWindowRefreshCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
[ "def", "set_window_refresh_callback", "(", "window", ",", "cbfun", ")", ":", "window_addr", "=", "ctypes", ".", "cast", "(", "ctypes", ".", "pointer", "(", "window", ")", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_long", ")", ")", ".", "conten...
Sets the refresh callback for the specified window. Wrapper for: GLFWwindowrefreshfun glfwSetWindowRefreshCallback(GLFWwindow* window, GLFWwindowrefreshfun cbfun);
[ "Sets", "the", "refresh", "callback", "for", "the", "specified", "window", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L1226-L1246
train
31,162
FlorianRhiem/pyGLFW
glfw/__init__.py
set_window_focus_callback
def set_window_focus_callback(window, cbfun): """ Sets the focus callback for the specified window. Wrapper for: GLFWwindowfocusfun glfwSetWindowFocusCallback(GLFWwindow* window, GLFWwindowfocusfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _window_focus_callback_repository: previous_callback = _window_focus_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWwindowfocusfun(cbfun) _window_focus_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetWindowFocusCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
python
def set_window_focus_callback(window, cbfun): """ Sets the focus callback for the specified window. Wrapper for: GLFWwindowfocusfun glfwSetWindowFocusCallback(GLFWwindow* window, GLFWwindowfocusfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _window_focus_callback_repository: previous_callback = _window_focus_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWwindowfocusfun(cbfun) _window_focus_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetWindowFocusCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
[ "def", "set_window_focus_callback", "(", "window", ",", "cbfun", ")", ":", "window_addr", "=", "ctypes", ".", "cast", "(", "ctypes", ".", "pointer", "(", "window", ")", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_long", ")", ")", ".", "contents...
Sets the focus callback for the specified window. Wrapper for: GLFWwindowfocusfun glfwSetWindowFocusCallback(GLFWwindow* window, GLFWwindowfocusfun cbfun);
[ "Sets", "the", "focus", "callback", "for", "the", "specified", "window", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L1253-L1273
train
31,163
FlorianRhiem/pyGLFW
glfw/__init__.py
set_window_iconify_callback
def set_window_iconify_callback(window, cbfun): """ Sets the iconify callback for the specified window. Wrapper for: GLFWwindowiconifyfun glfwSetWindowIconifyCallback(GLFWwindow* window, GLFWwindowiconifyfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _window_iconify_callback_repository: previous_callback = _window_iconify_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWwindowiconifyfun(cbfun) _window_iconify_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetWindowIconifyCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
python
def set_window_iconify_callback(window, cbfun): """ Sets the iconify callback for the specified window. Wrapper for: GLFWwindowiconifyfun glfwSetWindowIconifyCallback(GLFWwindow* window, GLFWwindowiconifyfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _window_iconify_callback_repository: previous_callback = _window_iconify_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWwindowiconifyfun(cbfun) _window_iconify_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetWindowIconifyCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
[ "def", "set_window_iconify_callback", "(", "window", ",", "cbfun", ")", ":", "window_addr", "=", "ctypes", ".", "cast", "(", "ctypes", ".", "pointer", "(", "window", ")", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_long", ")", ")", ".", "conten...
Sets the iconify callback for the specified window. Wrapper for: GLFWwindowiconifyfun glfwSetWindowIconifyCallback(GLFWwindow* window, GLFWwindowiconifyfun cbfun);
[ "Sets", "the", "iconify", "callback", "for", "the", "specified", "window", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L1280-L1300
train
31,164
FlorianRhiem/pyGLFW
glfw/__init__.py
set_framebuffer_size_callback
def set_framebuffer_size_callback(window, cbfun): """ Sets the framebuffer resize callback for the specified window. Wrapper for: GLFWframebuffersizefun glfwSetFramebufferSizeCallback(GLFWwindow* window, GLFWframebuffersizefun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _framebuffer_size_callback_repository: previous_callback = _framebuffer_size_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWframebuffersizefun(cbfun) _framebuffer_size_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetFramebufferSizeCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
python
def set_framebuffer_size_callback(window, cbfun): """ Sets the framebuffer resize callback for the specified window. Wrapper for: GLFWframebuffersizefun glfwSetFramebufferSizeCallback(GLFWwindow* window, GLFWframebuffersizefun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _framebuffer_size_callback_repository: previous_callback = _framebuffer_size_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWframebuffersizefun(cbfun) _framebuffer_size_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetFramebufferSizeCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
[ "def", "set_framebuffer_size_callback", "(", "window", ",", "cbfun", ")", ":", "window_addr", "=", "ctypes", ".", "cast", "(", "ctypes", ".", "pointer", "(", "window", ")", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_long", ")", ")", ".", "cont...
Sets the framebuffer resize callback for the specified window. Wrapper for: GLFWframebuffersizefun glfwSetFramebufferSizeCallback(GLFWwindow* window, GLFWframebuffersizefun cbfun);
[ "Sets", "the", "framebuffer", "resize", "callback", "for", "the", "specified", "window", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L1307-L1327
train
31,165
FlorianRhiem/pyGLFW
glfw/__init__.py
get_cursor_pos
def get_cursor_pos(window): """ Retrieves the last reported cursor position, relative to the client area of the window. Wrapper for: void glfwGetCursorPos(GLFWwindow* window, double* xpos, double* ypos); """ xpos_value = ctypes.c_double(0.0) xpos = ctypes.pointer(xpos_value) ypos_value = ctypes.c_double(0.0) ypos = ctypes.pointer(ypos_value) _glfw.glfwGetCursorPos(window, xpos, ypos) return xpos_value.value, ypos_value.value
python
def get_cursor_pos(window): """ Retrieves the last reported cursor position, relative to the client area of the window. Wrapper for: void glfwGetCursorPos(GLFWwindow* window, double* xpos, double* ypos); """ xpos_value = ctypes.c_double(0.0) xpos = ctypes.pointer(xpos_value) ypos_value = ctypes.c_double(0.0) ypos = ctypes.pointer(ypos_value) _glfw.glfwGetCursorPos(window, xpos, ypos) return xpos_value.value, ypos_value.value
[ "def", "get_cursor_pos", "(", "window", ")", ":", "xpos_value", "=", "ctypes", ".", "c_double", "(", "0.0", ")", "xpos", "=", "ctypes", ".", "pointer", "(", "xpos_value", ")", "ypos_value", "=", "ctypes", ".", "c_double", "(", "0.0", ")", "ypos", "=", ...
Retrieves the last reported cursor position, relative to the client area of the window. Wrapper for: void glfwGetCursorPos(GLFWwindow* window, double* xpos, double* ypos);
[ "Retrieves", "the", "last", "reported", "cursor", "position", "relative", "to", "the", "client", "area", "of", "the", "window", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L1410-L1423
train
31,166
FlorianRhiem/pyGLFW
glfw/__init__.py
set_key_callback
def set_key_callback(window, cbfun): """ Sets the key callback. Wrapper for: GLFWkeyfun glfwSetKeyCallback(GLFWwindow* window, GLFWkeyfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _key_callback_repository: previous_callback = _key_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWkeyfun(cbfun) _key_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetKeyCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
python
def set_key_callback(window, cbfun): """ Sets the key callback. Wrapper for: GLFWkeyfun glfwSetKeyCallback(GLFWwindow* window, GLFWkeyfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _key_callback_repository: previous_callback = _key_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWkeyfun(cbfun) _key_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetKeyCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
[ "def", "set_key_callback", "(", "window", ",", "cbfun", ")", ":", "window_addr", "=", "ctypes", ".", "cast", "(", "ctypes", ".", "pointer", "(", "window", ")", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_long", ")", ")", ".", "contents", ".",...
Sets the key callback. Wrapper for: GLFWkeyfun glfwSetKeyCallback(GLFWwindow* window, GLFWkeyfun cbfun);
[ "Sets", "the", "key", "callback", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L1443-L1463
train
31,167
FlorianRhiem/pyGLFW
glfw/__init__.py
set_char_callback
def set_char_callback(window, cbfun): """ Sets the Unicode character callback. Wrapper for: GLFWcharfun glfwSetCharCallback(GLFWwindow* window, GLFWcharfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _char_callback_repository: previous_callback = _char_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWcharfun(cbfun) _char_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetCharCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
python
def set_char_callback(window, cbfun): """ Sets the Unicode character callback. Wrapper for: GLFWcharfun glfwSetCharCallback(GLFWwindow* window, GLFWcharfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _char_callback_repository: previous_callback = _char_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWcharfun(cbfun) _char_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetCharCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
[ "def", "set_char_callback", "(", "window", ",", "cbfun", ")", ":", "window_addr", "=", "ctypes", ".", "cast", "(", "ctypes", ".", "pointer", "(", "window", ")", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_long", ")", ")", ".", "contents", "."...
Sets the Unicode character callback. Wrapper for: GLFWcharfun glfwSetCharCallback(GLFWwindow* window, GLFWcharfun cbfun);
[ "Sets", "the", "Unicode", "character", "callback", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L1470-L1490
train
31,168
FlorianRhiem/pyGLFW
glfw/__init__.py
set_mouse_button_callback
def set_mouse_button_callback(window, cbfun): """ Sets the mouse button callback. Wrapper for: GLFWmousebuttonfun glfwSetMouseButtonCallback(GLFWwindow* window, GLFWmousebuttonfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _mouse_button_callback_repository: previous_callback = _mouse_button_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWmousebuttonfun(cbfun) _mouse_button_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetMouseButtonCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
python
def set_mouse_button_callback(window, cbfun): """ Sets the mouse button callback. Wrapper for: GLFWmousebuttonfun glfwSetMouseButtonCallback(GLFWwindow* window, GLFWmousebuttonfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _mouse_button_callback_repository: previous_callback = _mouse_button_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWmousebuttonfun(cbfun) _mouse_button_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetMouseButtonCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
[ "def", "set_mouse_button_callback", "(", "window", ",", "cbfun", ")", ":", "window_addr", "=", "ctypes", ".", "cast", "(", "ctypes", ".", "pointer", "(", "window", ")", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_long", ")", ")", ".", "contents...
Sets the mouse button callback. Wrapper for: GLFWmousebuttonfun glfwSetMouseButtonCallback(GLFWwindow* window, GLFWmousebuttonfun cbfun);
[ "Sets", "the", "mouse", "button", "callback", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L1497-L1517
train
31,169
FlorianRhiem/pyGLFW
glfw/__init__.py
set_cursor_pos_callback
def set_cursor_pos_callback(window, cbfun): """ Sets the cursor position callback. Wrapper for: GLFWcursorposfun glfwSetCursorPosCallback(GLFWwindow* window, GLFWcursorposfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _cursor_pos_callback_repository: previous_callback = _cursor_pos_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWcursorposfun(cbfun) _cursor_pos_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetCursorPosCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
python
def set_cursor_pos_callback(window, cbfun): """ Sets the cursor position callback. Wrapper for: GLFWcursorposfun glfwSetCursorPosCallback(GLFWwindow* window, GLFWcursorposfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _cursor_pos_callback_repository: previous_callback = _cursor_pos_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWcursorposfun(cbfun) _cursor_pos_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetCursorPosCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
[ "def", "set_cursor_pos_callback", "(", "window", ",", "cbfun", ")", ":", "window_addr", "=", "ctypes", ".", "cast", "(", "ctypes", ".", "pointer", "(", "window", ")", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_long", ")", ")", ".", "contents",...
Sets the cursor position callback. Wrapper for: GLFWcursorposfun glfwSetCursorPosCallback(GLFWwindow* window, GLFWcursorposfun cbfun);
[ "Sets", "the", "cursor", "position", "callback", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L1524-L1544
train
31,170
FlorianRhiem/pyGLFW
glfw/__init__.py
set_scroll_callback
def set_scroll_callback(window, cbfun): """ Sets the scroll callback. Wrapper for: GLFWscrollfun glfwSetScrollCallback(GLFWwindow* window, GLFWscrollfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _scroll_callback_repository: previous_callback = _scroll_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWscrollfun(cbfun) _scroll_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetScrollCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
python
def set_scroll_callback(window, cbfun): """ Sets the scroll callback. Wrapper for: GLFWscrollfun glfwSetScrollCallback(GLFWwindow* window, GLFWscrollfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _scroll_callback_repository: previous_callback = _scroll_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWscrollfun(cbfun) _scroll_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetScrollCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
[ "def", "set_scroll_callback", "(", "window", ",", "cbfun", ")", ":", "window_addr", "=", "ctypes", ".", "cast", "(", "ctypes", ".", "pointer", "(", "window", ")", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_long", ")", ")", ".", "contents", "...
Sets the scroll callback. Wrapper for: GLFWscrollfun glfwSetScrollCallback(GLFWwindow* window, GLFWscrollfun cbfun);
[ "Sets", "the", "scroll", "callback", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L1578-L1598
train
31,171
FlorianRhiem/pyGLFW
glfw/__init__.py
get_joystick_axes
def get_joystick_axes(joy): """ Returns the values of all axes of the specified joystick. Wrapper for: const float* glfwGetJoystickAxes(int joy, int* count); """ count_value = ctypes.c_int(0) count = ctypes.pointer(count_value) result = _glfw.glfwGetJoystickAxes(joy, count) return result, count_value.value
python
def get_joystick_axes(joy): """ Returns the values of all axes of the specified joystick. Wrapper for: const float* glfwGetJoystickAxes(int joy, int* count); """ count_value = ctypes.c_int(0) count = ctypes.pointer(count_value) result = _glfw.glfwGetJoystickAxes(joy, count) return result, count_value.value
[ "def", "get_joystick_axes", "(", "joy", ")", ":", "count_value", "=", "ctypes", ".", "c_int", "(", "0", ")", "count", "=", "ctypes", ".", "pointer", "(", "count_value", ")", "result", "=", "_glfw", ".", "glfwGetJoystickAxes", "(", "joy", ",", "count", ")...
Returns the values of all axes of the specified joystick. Wrapper for: const float* glfwGetJoystickAxes(int joy, int* count);
[ "Returns", "the", "values", "of", "all", "axes", "of", "the", "specified", "joystick", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L1614-L1624
train
31,172
FlorianRhiem/pyGLFW
glfw/__init__.py
get_joystick_buttons
def get_joystick_buttons(joy): """ Returns the state of all buttons of the specified joystick. Wrapper for: const unsigned char* glfwGetJoystickButtons(int joy, int* count); """ count_value = ctypes.c_int(0) count = ctypes.pointer(count_value) result = _glfw.glfwGetJoystickButtons(joy, count) return result, count_value.value
python
def get_joystick_buttons(joy): """ Returns the state of all buttons of the specified joystick. Wrapper for: const unsigned char* glfwGetJoystickButtons(int joy, int* count); """ count_value = ctypes.c_int(0) count = ctypes.pointer(count_value) result = _glfw.glfwGetJoystickButtons(joy, count) return result, count_value.value
[ "def", "get_joystick_buttons", "(", "joy", ")", ":", "count_value", "=", "ctypes", ".", "c_int", "(", "0", ")", "count", "=", "ctypes", ".", "pointer", "(", "count_value", ")", "result", "=", "_glfw", ".", "glfwGetJoystickButtons", "(", "joy", ",", "count"...
Returns the state of all buttons of the specified joystick. Wrapper for: const unsigned char* glfwGetJoystickButtons(int joy, int* count);
[ "Returns", "the", "state", "of", "all", "buttons", "of", "the", "specified", "joystick", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L1629-L1639
train
31,173
FlorianRhiem/pyGLFW
glfw/__init__.py
_GLFWvidmode.unwrap
def unwrap(self): """ Returns a GLFWvidmode object. """ size = self.Size(self.width, self.height) bits = self.Bits(self.red_bits, self.green_bits, self.blue_bits) return self.GLFWvidmode(size, bits, self.refresh_rate)
python
def unwrap(self): """ Returns a GLFWvidmode object. """ size = self.Size(self.width, self.height) bits = self.Bits(self.red_bits, self.green_bits, self.blue_bits) return self.GLFWvidmode(size, bits, self.refresh_rate)
[ "def", "unwrap", "(", "self", ")", ":", "size", "=", "self", ".", "Size", "(", "self", ".", "width", ",", "self", ".", "height", ")", "bits", "=", "self", ".", "Bits", "(", "self", ".", "red_bits", ",", "self", ".", "green_bits", ",", "self", "."...
Returns a GLFWvidmode object.
[ "Returns", "a", "GLFWvidmode", "object", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L118-L124
train
31,174
FlorianRhiem/pyGLFW
glfw/__init__.py
_GLFWgammaramp.unwrap
def unwrap(self): """ Returns a GLFWgammaramp object. """ red = [self.red[i] for i in range(self.size)] green = [self.green[i] for i in range(self.size)] blue = [self.blue[i] for i in range(self.size)] if NORMALIZE_GAMMA_RAMPS: red = [value / 65535.0 for value in red] green = [value / 65535.0 for value in green] blue = [value / 65535.0 for value in blue] return self.GLFWgammaramp(red, green, blue)
python
def unwrap(self): """ Returns a GLFWgammaramp object. """ red = [self.red[i] for i in range(self.size)] green = [self.green[i] for i in range(self.size)] blue = [self.blue[i] for i in range(self.size)] if NORMALIZE_GAMMA_RAMPS: red = [value / 65535.0 for value in red] green = [value / 65535.0 for value in green] blue = [value / 65535.0 for value in blue] return self.GLFWgammaramp(red, green, blue)
[ "def", "unwrap", "(", "self", ")", ":", "red", "=", "[", "self", ".", "red", "[", "i", "]", "for", "i", "in", "range", "(", "self", ".", "size", ")", "]", "green", "=", "[", "self", ".", "green", "[", "i", "]", "for", "i", "in", "range", "(...
Returns a GLFWgammaramp object.
[ "Returns", "a", "GLFWgammaramp", "object", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L175-L186
train
31,175
FlorianRhiem/pyGLFW
glfw/__init__.py
_GLFWimage.unwrap
def unwrap(self): """ Returns a GLFWimage object. """ pixels = [[[int(c) for c in p] for p in l] for l in self.pixels_array] return self.GLFWimage(self.width, self.height, pixels)
python
def unwrap(self): """ Returns a GLFWimage object. """ pixels = [[[int(c) for c in p] for p in l] for l in self.pixels_array] return self.GLFWimage(self.width, self.height, pixels)
[ "def", "unwrap", "(", "self", ")", ":", "pixels", "=", "[", "[", "[", "int", "(", "c", ")", "for", "c", "in", "p", "]", "for", "p", "in", "l", "]", "for", "l", "in", "self", ".", "pixels_array", "]", "return", "self", ".", "GLFWimage", "(", "...
Returns a GLFWimage object.
[ "Returns", "a", "GLFWimage", "object", "." ]
87767dfbe15ba15d2a8338cdfddf6afc6a25dff5
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L240-L245
train
31,176
wadda/gps3
gps3/gps3threaded.py
GPS3mechanism.stream_data
def stream_data(self, host=HOST, port=GPSD_PORT, enable=True, gpsd_protocol=PROTOCOL, devicepath=None): """ Connect and command, point and shoot, flail and bail """ self.socket.connect(host, port) self.socket.watch(enable, gpsd_protocol, devicepath)
python
def stream_data(self, host=HOST, port=GPSD_PORT, enable=True, gpsd_protocol=PROTOCOL, devicepath=None): """ Connect and command, point and shoot, flail and bail """ self.socket.connect(host, port) self.socket.watch(enable, gpsd_protocol, devicepath)
[ "def", "stream_data", "(", "self", ",", "host", "=", "HOST", ",", "port", "=", "GPSD_PORT", ",", "enable", "=", "True", ",", "gpsd_protocol", "=", "PROTOCOL", ",", "devicepath", "=", "None", ")", ":", "self", ".", "socket", ".", "connect", "(", "host",...
Connect and command, point and shoot, flail and bail
[ "Connect", "and", "command", "point", "and", "shoot", "flail", "and", "bail" ]
91adcd7073b891b135b2a46d039ce2125cf09a09
https://github.com/wadda/gps3/blob/91adcd7073b891b135b2a46d039ce2125cf09a09/gps3/gps3threaded.py#L32-L36
train
31,177
wadda/gps3
gps3/gps3threaded.py
GPS3mechanism.unpack_data
def unpack_data(self, usnap=.2): # 2/10th second sleep between empty requests """ Iterates over socket response and unpacks values of object attributes. Sleeping here has the greatest response to cpu cycles short of blocking sockets """ for new_data in self.socket: if new_data: self.data_stream.unpack(new_data) else: sleep(usnap)
python
def unpack_data(self, usnap=.2): # 2/10th second sleep between empty requests """ Iterates over socket response and unpacks values of object attributes. Sleeping here has the greatest response to cpu cycles short of blocking sockets """ for new_data in self.socket: if new_data: self.data_stream.unpack(new_data) else: sleep(usnap)
[ "def", "unpack_data", "(", "self", ",", "usnap", "=", ".2", ")", ":", "# 2/10th second sleep between empty requests", "for", "new_data", "in", "self", ".", "socket", ":", "if", "new_data", ":", "self", ".", "data_stream", ".", "unpack", "(", "new_data", ")", ...
Iterates over socket response and unpacks values of object attributes. Sleeping here has the greatest response to cpu cycles short of blocking sockets
[ "Iterates", "over", "socket", "response", "and", "unpacks", "values", "of", "object", "attributes", ".", "Sleeping", "here", "has", "the", "greatest", "response", "to", "cpu", "cycles", "short", "of", "blocking", "sockets" ]
91adcd7073b891b135b2a46d039ce2125cf09a09
https://github.com/wadda/gps3/blob/91adcd7073b891b135b2a46d039ce2125cf09a09/gps3/gps3threaded.py#L38-L46
train
31,178
wadda/gps3
gps3/gps3threaded.py
GPS3mechanism.run_thread
def run_thread(self, usnap=.2, daemon=True): """run thread with data """ # self.stream_data() # Unless other changes are made this would limit to localhost only. try: gps3_data_thread = Thread(target=self.unpack_data, args={usnap: usnap}, daemon=daemon) except TypeError: # threading.Thread() only accepts daemon argument in Python 3.3 gps3_data_thread = Thread(target=self.unpack_data, args={usnap: usnap}) gps3_data_thread.setDaemon(daemon) gps3_data_thread.start()
python
def run_thread(self, usnap=.2, daemon=True): """run thread with data """ # self.stream_data() # Unless other changes are made this would limit to localhost only. try: gps3_data_thread = Thread(target=self.unpack_data, args={usnap: usnap}, daemon=daemon) except TypeError: # threading.Thread() only accepts daemon argument in Python 3.3 gps3_data_thread = Thread(target=self.unpack_data, args={usnap: usnap}) gps3_data_thread.setDaemon(daemon) gps3_data_thread.start()
[ "def", "run_thread", "(", "self", ",", "usnap", "=", ".2", ",", "daemon", "=", "True", ")", ":", "# self.stream_data() # Unless other changes are made this would limit to localhost only.", "try", ":", "gps3_data_thread", "=", "Thread", "(", "target", "=", "self", ".",...
run thread with data
[ "run", "thread", "with", "data" ]
91adcd7073b891b135b2a46d039ce2125cf09a09
https://github.com/wadda/gps3/blob/91adcd7073b891b135b2a46d039ce2125cf09a09/gps3/gps3threaded.py#L48-L58
train
31,179
wadda/gps3
examples/human.py
add_args
def add_args(): """Adds commandline arguments and formatted Help""" parser = argparse.ArgumentParser() parser.add_argument('-host', action='store', dest='host', default='127.0.0.1', help='DEFAULT "127.0.0.1"') parser.add_argument('-port', action='store', dest='port', default='2947', help='DEFAULT 2947', type=int) parser.add_argument('-json', dest='gpsd_protocol', const='json', action='store_const', default='json', help='DEFAULT JSON objects */') parser.add_argument('-device', dest='devicepath', action='store', help='alternate devicepath e.g.,"-device /dev/ttyUSB4"') # Infrequently used options parser.add_argument('-nmea', dest='gpsd_protocol', const='nmea', action='store_const', help='*/ output in NMEA */') # parser.add_argument('-rare', dest='gpsd_protocol', const='rare', action='store_const', help='*/ output of packets in hex */') # parser.add_argument('-raw', dest='gpsd_protocol', const='raw', action='store_const', help='*/ output of raw packets */') # parser.add_argument('-scaled', dest='gpsd_protocol', const='scaled', action='store_const', help='*/ scale output to floats */') # parser.add_argument('-timing', dest='gpsd_protocol', const='timing', action='store_const', help='*/ timing information */') # parser.add_argument('-split24', dest='gpsd_protocol', const='split24', action='store_const', help='*/ split AIS Type 24s */') # parser.add_argument('-pps', dest='gpsd_protocol', const='pps', action='store_const', help='*/ enable PPS JSON */') parser.add_argument('-v', '--version', action='version', version='Version: {}'.format(__version__)) cli_args = parser.parse_args() return cli_args
python
def add_args(): """Adds commandline arguments and formatted Help""" parser = argparse.ArgumentParser() parser.add_argument('-host', action='store', dest='host', default='127.0.0.1', help='DEFAULT "127.0.0.1"') parser.add_argument('-port', action='store', dest='port', default='2947', help='DEFAULT 2947', type=int) parser.add_argument('-json', dest='gpsd_protocol', const='json', action='store_const', default='json', help='DEFAULT JSON objects */') parser.add_argument('-device', dest='devicepath', action='store', help='alternate devicepath e.g.,"-device /dev/ttyUSB4"') # Infrequently used options parser.add_argument('-nmea', dest='gpsd_protocol', const='nmea', action='store_const', help='*/ output in NMEA */') # parser.add_argument('-rare', dest='gpsd_protocol', const='rare', action='store_const', help='*/ output of packets in hex */') # parser.add_argument('-raw', dest='gpsd_protocol', const='raw', action='store_const', help='*/ output of raw packets */') # parser.add_argument('-scaled', dest='gpsd_protocol', const='scaled', action='store_const', help='*/ scale output to floats */') # parser.add_argument('-timing', dest='gpsd_protocol', const='timing', action='store_const', help='*/ timing information */') # parser.add_argument('-split24', dest='gpsd_protocol', const='split24', action='store_const', help='*/ split AIS Type 24s */') # parser.add_argument('-pps', dest='gpsd_protocol', const='pps', action='store_const', help='*/ enable PPS JSON */') parser.add_argument('-v', '--version', action='version', version='Version: {}'.format(__version__)) cli_args = parser.parse_args() return cli_args
[ "def", "add_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'-host'", ",", "action", "=", "'store'", ",", "dest", "=", "'host'", ",", "default", "=", "'127.0.0.1'", ",", "help", "=", ...
Adds commandline arguments and formatted Help
[ "Adds", "commandline", "arguments", "and", "formatted", "Help" ]
91adcd7073b891b135b2a46d039ce2125cf09a09
https://github.com/wadda/gps3/blob/91adcd7073b891b135b2a46d039ce2125cf09a09/examples/human.py#L39-L57
train
31,180
wadda/gps3
examples/human.py
make_time
def make_time(gps_datetime_str): """Makes datetime object from string object""" if not 'n/a' == gps_datetime_str: datetime_string = gps_datetime_str datetime_object = datetime.strptime(datetime_string, "%Y-%m-%dT%H:%M:%S") return datetime_object
python
def make_time(gps_datetime_str): """Makes datetime object from string object""" if not 'n/a' == gps_datetime_str: datetime_string = gps_datetime_str datetime_object = datetime.strptime(datetime_string, "%Y-%m-%dT%H:%M:%S") return datetime_object
[ "def", "make_time", "(", "gps_datetime_str", ")", ":", "if", "not", "'n/a'", "==", "gps_datetime_str", ":", "datetime_string", "=", "gps_datetime_str", "datetime_object", "=", "datetime", ".", "strptime", "(", "datetime_string", ",", "\"%Y-%m-%dT%H:%M:%S\"", ")", "r...
Makes datetime object from string object
[ "Makes", "datetime", "object", "from", "string", "object" ]
91adcd7073b891b135b2a46d039ce2125cf09a09
https://github.com/wadda/gps3/blob/91adcd7073b891b135b2a46d039ce2125cf09a09/examples/human.py#L81-L86
train
31,181
wadda/gps3
examples/human.py
elapsed_time_from
def elapsed_time_from(start_time): """calculate time delta from latched time and current time""" time_then = make_time(start_time) time_now = datetime.utcnow().replace(microsecond=0) if time_then is None: return delta_t = time_now - time_then return delta_t
python
def elapsed_time_from(start_time): """calculate time delta from latched time and current time""" time_then = make_time(start_time) time_now = datetime.utcnow().replace(microsecond=0) if time_then is None: return delta_t = time_now - time_then return delta_t
[ "def", "elapsed_time_from", "(", "start_time", ")", ":", "time_then", "=", "make_time", "(", "start_time", ")", "time_now", "=", "datetime", ".", "utcnow", "(", ")", ".", "replace", "(", "microsecond", "=", "0", ")", "if", "time_then", "is", "None", ":", ...
calculate time delta from latched time and current time
[ "calculate", "time", "delta", "from", "latched", "time", "and", "current", "time" ]
91adcd7073b891b135b2a46d039ce2125cf09a09
https://github.com/wadda/gps3/blob/91adcd7073b891b135b2a46d039ce2125cf09a09/examples/human.py#L89-L96
train
31,182
wadda/gps3
examples/human.py
unit_conversion
def unit_conversion(thing, units, length=False): """converts base data between metric, imperial, or nautical units""" if 'n/a' == thing: return 'n/a' try: thing = round(thing * CONVERSION[units][0 + length], 2) except TypeError: thing = 'fubar' return thing, CONVERSION[units][2 + length]
python
def unit_conversion(thing, units, length=False): """converts base data between metric, imperial, or nautical units""" if 'n/a' == thing: return 'n/a' try: thing = round(thing * CONVERSION[units][0 + length], 2) except TypeError: thing = 'fubar' return thing, CONVERSION[units][2 + length]
[ "def", "unit_conversion", "(", "thing", ",", "units", ",", "length", "=", "False", ")", ":", "if", "'n/a'", "==", "thing", ":", "return", "'n/a'", "try", ":", "thing", "=", "round", "(", "thing", "*", "CONVERSION", "[", "units", "]", "[", "0", "+", ...
converts base data between metric, imperial, or nautical units
[ "converts", "base", "data", "between", "metric", "imperial", "or", "nautical", "units" ]
91adcd7073b891b135b2a46d039ce2125cf09a09
https://github.com/wadda/gps3/blob/91adcd7073b891b135b2a46d039ce2125cf09a09/examples/human.py#L99-L107
train
31,183
wadda/gps3
examples/human.py
shut_down
def shut_down(): """Closes connection and restores terminal""" curses.nocbreak() curses.echo() curses.endwin() gpsd_socket.close() print('Keyboard interrupt received\nTerminated by user\nGood Bye.\n') sys.exit(1)
python
def shut_down(): """Closes connection and restores terminal""" curses.nocbreak() curses.echo() curses.endwin() gpsd_socket.close() print('Keyboard interrupt received\nTerminated by user\nGood Bye.\n') sys.exit(1)
[ "def", "shut_down", "(", ")", ":", "curses", ".", "nocbreak", "(", ")", "curses", ".", "echo", "(", ")", "curses", ".", "endwin", "(", ")", "gpsd_socket", ".", "close", "(", ")", "print", "(", "'Keyboard interrupt received\\nTerminated by user\\nGood Bye.\\n'", ...
Closes connection and restores terminal
[ "Closes", "connection", "and", "restores", "terminal" ]
91adcd7073b891b135b2a46d039ce2125cf09a09
https://github.com/wadda/gps3/blob/91adcd7073b891b135b2a46d039ce2125cf09a09/examples/human.py#L292-L299
train
31,184
wadda/gps3
gps3/gps3.py
GPSDSocket.close
def close(self): """turn off stream and close socket""" if self.streamSock: self.watch(enable=False) self.streamSock.close() self.streamSock = None
python
def close(self): """turn off stream and close socket""" if self.streamSock: self.watch(enable=False) self.streamSock.close() self.streamSock = None
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "streamSock", ":", "self", ".", "watch", "(", "enable", "=", "False", ")", "self", ".", "streamSock", ".", "close", "(", ")", "self", ".", "streamSock", "=", "None" ]
turn off stream and close socket
[ "turn", "off", "stream", "and", "close", "socket" ]
91adcd7073b891b135b2a46d039ce2125cf09a09
https://github.com/wadda/gps3/blob/91adcd7073b891b135b2a46d039ce2125cf09a09/gps3/gps3.py#L128-L133
train
31,185
wadda/gps3
examples/ahuman.py
show_nmea
def show_nmea(): """NMEA output in curses terminal""" data_window = curses.newwin(24, 79, 0, 0) for new_data in gpsd_socket: if new_data: screen.nodelay(1) key_press = screen.getch() if key_press == ord('q'): shut_down() elif key_press == ord('j'): # raw gpsd_socket.watch(enable=False, gpsd_protocol='nmea') gpsd_socket.watch(gpsd_protocol='json') show_human() data_window.border(0) data_window.addstr(0, 2, 'AGPS3 Python {}.{}.{} GPSD Interface Showing NMEA protocol'.format(*sys.version_info), curses.A_BOLD) data_window.addstr(2, 2, '{}'.format(gpsd_socket.response)) data_window.refresh() else: sleep(.1)
python
def show_nmea(): """NMEA output in curses terminal""" data_window = curses.newwin(24, 79, 0, 0) for new_data in gpsd_socket: if new_data: screen.nodelay(1) key_press = screen.getch() if key_press == ord('q'): shut_down() elif key_press == ord('j'): # raw gpsd_socket.watch(enable=False, gpsd_protocol='nmea') gpsd_socket.watch(gpsd_protocol='json') show_human() data_window.border(0) data_window.addstr(0, 2, 'AGPS3 Python {}.{}.{} GPSD Interface Showing NMEA protocol'.format(*sys.version_info), curses.A_BOLD) data_window.addstr(2, 2, '{}'.format(gpsd_socket.response)) data_window.refresh() else: sleep(.1)
[ "def", "show_nmea", "(", ")", ":", "data_window", "=", "curses", ".", "newwin", "(", "24", ",", "79", ",", "0", ",", "0", ")", "for", "new_data", "in", "gpsd_socket", ":", "if", "new_data", ":", "screen", ".", "nodelay", "(", "1", ")", "key_press", ...
NMEA output in curses terminal
[ "NMEA", "output", "in", "curses", "terminal" ]
91adcd7073b891b135b2a46d039ce2125cf09a09
https://github.com/wadda/gps3/blob/91adcd7073b891b135b2a46d039ce2125cf09a09/examples/ahuman.py#L270-L290
train
31,186
batiste/django-page-cms
pages/widgets_registry.py
register_widget
def register_widget(widget): """ Register the given widget as a candidate to use in placeholder. """ if widget in registry: raise WidgetAlreadyRegistered( _('The widget %s has already been registered.') % widget.__name__) registry.append(widget)
python
def register_widget(widget): """ Register the given widget as a candidate to use in placeholder. """ if widget in registry: raise WidgetAlreadyRegistered( _('The widget %s has already been registered.') % widget.__name__) registry.append(widget)
[ "def", "register_widget", "(", "widget", ")", ":", "if", "widget", "in", "registry", ":", "raise", "WidgetAlreadyRegistered", "(", "_", "(", "'The widget %s has already been registered.'", ")", "%", "widget", ".", "__name__", ")", "registry", ".", "append", "(", ...
Register the given widget as a candidate to use in placeholder.
[ "Register", "the", "given", "widget", "as", "a", "candidate", "to", "use", "in", "placeholder", "." ]
3c72111eb7c3997a63c462c1776ffd8ce8c50a5d
https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/widgets_registry.py#L24-L31
train
31,187
batiste/django-page-cms
pages/widgets_registry.py
get_widget
def get_widget(name): """ Give back a widget class according to his name. """ for widget in registry: if widget.__name__ == name: return widget raise WidgetNotFound( _('The widget %s has not been registered.') % name)
python
def get_widget(name): """ Give back a widget class according to his name. """ for widget in registry: if widget.__name__ == name: return widget raise WidgetNotFound( _('The widget %s has not been registered.') % name)
[ "def", "get_widget", "(", "name", ")", ":", "for", "widget", "in", "registry", ":", "if", "widget", ".", "__name__", "==", "name", ":", "return", "widget", "raise", "WidgetNotFound", "(", "_", "(", "'The widget %s has not been registered.'", ")", "%", "name", ...
Give back a widget class according to his name.
[ "Give", "back", "a", "widget", "class", "according", "to", "his", "name", "." ]
3c72111eb7c3997a63c462c1776ffd8ce8c50a5d
https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/widgets_registry.py#L34-L42
train
31,188
batiste/django-page-cms
pages/settings.py
get_setting
def get_setting(*args, **kwargs): """Get a setting and raise an appropriate user friendly error if the setting is not found.""" for name in args: if hasattr(settings, name): return getattr(settings, name) if kwargs.get('raise_error', False): setting_url = url % args[0].lower().replace('_', '-') raise ImproperlyConfigured('Please make sure you specified at ' 'least one of these settings: %s \r\nDocumentation: %s' % (args, setting_url)) return kwargs.get('default_value', None)
python
def get_setting(*args, **kwargs): """Get a setting and raise an appropriate user friendly error if the setting is not found.""" for name in args: if hasattr(settings, name): return getattr(settings, name) if kwargs.get('raise_error', False): setting_url = url % args[0].lower().replace('_', '-') raise ImproperlyConfigured('Please make sure you specified at ' 'least one of these settings: %s \r\nDocumentation: %s' % (args, setting_url)) return kwargs.get('default_value', None)
[ "def", "get_setting", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "name", "in", "args", ":", "if", "hasattr", "(", "settings", ",", "name", ")", ":", "return", "getattr", "(", "settings", ",", "name", ")", "if", "kwargs", ".", "get"...
Get a setting and raise an appropriate user friendly error if the setting is not found.
[ "Get", "a", "setting", "and", "raise", "an", "appropriate", "user", "friendly", "error", "if", "the", "setting", "is", "not", "found", "." ]
3c72111eb7c3997a63c462c1776ffd8ce8c50a5d
https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/settings.py#L12-L23
train
31,189
batiste/django-page-cms
pages/settings.py
get_page_templates
def get_page_templates(): """The callable that is used by the CMS.""" PAGE_TEMPLATES = get_setting('PAGE_TEMPLATES', default_value=()) if isinstance(PAGE_TEMPLATES, collections.Callable): return PAGE_TEMPLATES() else: return PAGE_TEMPLATES
python
def get_page_templates(): """The callable that is used by the CMS.""" PAGE_TEMPLATES = get_setting('PAGE_TEMPLATES', default_value=()) if isinstance(PAGE_TEMPLATES, collections.Callable): return PAGE_TEMPLATES() else: return PAGE_TEMPLATES
[ "def", "get_page_templates", "(", ")", ":", "PAGE_TEMPLATES", "=", "get_setting", "(", "'PAGE_TEMPLATES'", ",", "default_value", "=", "(", ")", ")", "if", "isinstance", "(", "PAGE_TEMPLATES", ",", "collections", ".", "Callable", ")", ":", "return", "PAGE_TEMPLAT...
The callable that is used by the CMS.
[ "The", "callable", "that", "is", "used", "by", "the", "CMS", "." ]
3c72111eb7c3997a63c462c1776ffd8ce8c50a5d
https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/settings.py#L51-L58
train
31,190
batiste/django-page-cms
pages/admin/views.py
change_status
def change_status(request, page_id): """ Switch the status of a page. """ perm = request.user.has_perm('pages.change_page') if perm and request.method == 'POST': page = Page.objects.get(pk=page_id) page.status = int(request.POST['status']) page.invalidate() page.save() return HttpResponse(str(page.status)) raise Http404
python
def change_status(request, page_id): """ Switch the status of a page. """ perm = request.user.has_perm('pages.change_page') if perm and request.method == 'POST': page = Page.objects.get(pk=page_id) page.status = int(request.POST['status']) page.invalidate() page.save() return HttpResponse(str(page.status)) raise Http404
[ "def", "change_status", "(", "request", ",", "page_id", ")", ":", "perm", "=", "request", ".", "user", ".", "has_perm", "(", "'pages.change_page'", ")", "if", "perm", "and", "request", ".", "method", "==", "'POST'", ":", "page", "=", "Page", ".", "object...
Switch the status of a page.
[ "Switch", "the", "status", "of", "a", "page", "." ]
3c72111eb7c3997a63c462c1776ffd8ce8c50a5d
https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/admin/views.py#L21-L32
train
31,191
batiste/django-page-cms
pages/admin/views.py
get_last_content
def get_last_content(request, page_id): """Get the latest content for a particular type""" content_type = request.GET.get('content_type') language_id = request.GET.get('language_id') page = get_object_or_404(Page, pk=page_id) placeholders = get_placeholders(page.get_template()) _template = template.loader.get_template(page.get_template()) for placeholder in placeholders: if placeholder.name == content_type: context = RequestContext(request, { 'current_page': page, 'lang': language_id }) with context.bind_template(_template.template): content = placeholder.render(context) return HttpResponse(content) raise Http404
python
def get_last_content(request, page_id): """Get the latest content for a particular type""" content_type = request.GET.get('content_type') language_id = request.GET.get('language_id') page = get_object_or_404(Page, pk=page_id) placeholders = get_placeholders(page.get_template()) _template = template.loader.get_template(page.get_template()) for placeholder in placeholders: if placeholder.name == content_type: context = RequestContext(request, { 'current_page': page, 'lang': language_id }) with context.bind_template(_template.template): content = placeholder.render(context) return HttpResponse(content) raise Http404
[ "def", "get_last_content", "(", "request", ",", "page_id", ")", ":", "content_type", "=", "request", ".", "GET", ".", "get", "(", "'content_type'", ")", "language_id", "=", "request", ".", "GET", ".", "get", "(", "'language_id'", ")", "page", "=", "get_obj...
Get the latest content for a particular type
[ "Get", "the", "latest", "content", "for", "a", "particular", "type" ]
3c72111eb7c3997a63c462c1776ffd8ce8c50a5d
https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/admin/views.py#L122-L138
train
31,192
batiste/django-page-cms
pages/admin/views.py
traduction
def traduction(request, page_id, language_id): """Traduction helper.""" page = Page.objects.get(pk=page_id) lang = language_id placeholders = get_placeholders(page.get_template()) language_error = ( Content.objects.get_content(page, language_id, "title") is None ) return render(request, 'pages/traduction_helper.html', { 'page': page, 'lang': lang, 'language_error': language_error, 'placeholders': placeholders, })
python
def traduction(request, page_id, language_id): """Traduction helper.""" page = Page.objects.get(pk=page_id) lang = language_id placeholders = get_placeholders(page.get_template()) language_error = ( Content.objects.get_content(page, language_id, "title") is None ) return render(request, 'pages/traduction_helper.html', { 'page': page, 'lang': lang, 'language_error': language_error, 'placeholders': placeholders, })
[ "def", "traduction", "(", "request", ",", "page_id", ",", "language_id", ")", ":", "page", "=", "Page", ".", "objects", ".", "get", "(", "pk", "=", "page_id", ")", "lang", "=", "language_id", "placeholders", "=", "get_placeholders", "(", "page", ".", "ge...
Traduction helper.
[ "Traduction", "helper", "." ]
3c72111eb7c3997a63c462c1776ffd8ce8c50a5d
https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/admin/views.py#L163-L177
train
31,193
batiste/django-page-cms
pages/admin/views.py
get_content
def get_content(request, page_id, content_id): """Get the content for a particular page""" content = Content.objects.get(pk=content_id) return HttpResponse(content.body)
python
def get_content(request, page_id, content_id): """Get the content for a particular page""" content = Content.objects.get(pk=content_id) return HttpResponse(content.body)
[ "def", "get_content", "(", "request", ",", "page_id", ",", "content_id", ")", ":", "content", "=", "Content", ".", "objects", ".", "get", "(", "pk", "=", "content_id", ")", "return", "HttpResponse", "(", "content", ".", "body", ")" ]
Get the content for a particular page
[ "Get", "the", "content", "for", "a", "particular", "page" ]
3c72111eb7c3997a63c462c1776ffd8ce8c50a5d
https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/admin/views.py#L181-L184
train
31,194
batiste/django-page-cms
pages/admin/views.py
get_media_url
def get_media_url(request, media_id): """Get media URL.""" media = Media.objects.get(id=media_id) return HttpResponse(media.url.name)
python
def get_media_url(request, media_id): """Get media URL.""" media = Media.objects.get(id=media_id) return HttpResponse(media.url.name)
[ "def", "get_media_url", "(", "request", ",", "media_id", ")", ":", "media", "=", "Media", ".", "objects", ".", "get", "(", "id", "=", "media_id", ")", "return", "HttpResponse", "(", "media", ".", "url", ".", "name", ")" ]
Get media URL.
[ "Get", "media", "URL", "." ]
3c72111eb7c3997a63c462c1776ffd8ce8c50a5d
https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/admin/views.py#L232-L235
train
31,195
batiste/django-page-cms
pages/context_processors.py
media
def media(request): """Adds media-related variables to the `context`.""" return { 'PAGES_MEDIA_URL': settings.PAGES_MEDIA_URL, 'PAGES_STATIC_URL': settings.PAGES_STATIC_URL, 'PAGE_USE_SITE_ID': settings.PAGE_USE_SITE_ID, 'PAGE_HIDE_SITES': settings.PAGE_HIDE_SITES, 'PAGE_LANGUAGES': settings.PAGE_LANGUAGES, }
python
def media(request): """Adds media-related variables to the `context`.""" return { 'PAGES_MEDIA_URL': settings.PAGES_MEDIA_URL, 'PAGES_STATIC_URL': settings.PAGES_STATIC_URL, 'PAGE_USE_SITE_ID': settings.PAGE_USE_SITE_ID, 'PAGE_HIDE_SITES': settings.PAGE_HIDE_SITES, 'PAGE_LANGUAGES': settings.PAGE_LANGUAGES, }
[ "def", "media", "(", "request", ")", ":", "return", "{", "'PAGES_MEDIA_URL'", ":", "settings", ".", "PAGES_MEDIA_URL", ",", "'PAGES_STATIC_URL'", ":", "settings", ".", "PAGES_STATIC_URL", ",", "'PAGE_USE_SITE_ID'", ":", "settings", ".", "PAGE_USE_SITE_ID", ",", "'...
Adds media-related variables to the `context`.
[ "Adds", "media", "-", "related", "variables", "to", "the", "context", "." ]
3c72111eb7c3997a63c462c1776ffd8ce8c50a5d
https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/context_processors.py#L5-L13
train
31,196
batiste/django-page-cms
pages/utils.py
normalize_url
def normalize_url(url): """Return a normalized url with trailing and without leading slash. >>> normalize_url(None) '/' >>> normalize_url('/') '/' >>> normalize_url('/foo/bar') '/foo/bar' >>> normalize_url('foo/bar') '/foo/bar' >>> normalize_url('/foo/bar/') '/foo/bar' """ if not url or len(url) == 0: return '/' if not url.startswith('/'): url = '/' + url if len(url) > 1 and url.endswith('/'): url = url[0:len(url) - 1] return url
python
def normalize_url(url): """Return a normalized url with trailing and without leading slash. >>> normalize_url(None) '/' >>> normalize_url('/') '/' >>> normalize_url('/foo/bar') '/foo/bar' >>> normalize_url('foo/bar') '/foo/bar' >>> normalize_url('/foo/bar/') '/foo/bar' """ if not url or len(url) == 0: return '/' if not url.startswith('/'): url = '/' + url if len(url) > 1 and url.endswith('/'): url = url[0:len(url) - 1] return url
[ "def", "normalize_url", "(", "url", ")", ":", "if", "not", "url", "or", "len", "(", "url", ")", "==", "0", ":", "return", "'/'", "if", "not", "url", ".", "startswith", "(", "'/'", ")", ":", "url", "=", "'/'", "+", "url", "if", "len", "(", "url"...
Return a normalized url with trailing and without leading slash. >>> normalize_url(None) '/' >>> normalize_url('/') '/' >>> normalize_url('/foo/bar') '/foo/bar' >>> normalize_url('foo/bar') '/foo/bar' >>> normalize_url('/foo/bar/') '/foo/bar'
[ "Return", "a", "normalized", "url", "with", "trailing", "and", "without", "leading", "slash", "." ]
3c72111eb7c3997a63c462c1776ffd8ce8c50a5d
https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/utils.py#L116-L136
train
31,197
batiste/django-page-cms
pages/checks.py
page_templates_loading_check
def page_templates_loading_check(app_configs, **kwargs): """ Check if any page template can't be loaded. """ errors = [] for page_template in settings.get_page_templates(): try: loader.get_template(page_template[0]) except template.TemplateDoesNotExist: errors.append(checks.Warning( 'Django cannot find template %s' % page_template[0], obj=page_template, id='pages.W001')) return errors
python
def page_templates_loading_check(app_configs, **kwargs): """ Check if any page template can't be loaded. """ errors = [] for page_template in settings.get_page_templates(): try: loader.get_template(page_template[0]) except template.TemplateDoesNotExist: errors.append(checks.Warning( 'Django cannot find template %s' % page_template[0], obj=page_template, id='pages.W001')) return errors
[ "def", "page_templates_loading_check", "(", "app_configs", ",", "*", "*", "kwargs", ")", ":", "errors", "=", "[", "]", "for", "page_template", "in", "settings", ".", "get_page_templates", "(", ")", ":", "try", ":", "loader", ".", "get_template", "(", "page_t...
Check if any page template can't be loaded.
[ "Check", "if", "any", "page", "template", "can", "t", "be", "loaded", "." ]
3c72111eb7c3997a63c462c1776ffd8ce8c50a5d
https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/checks.py#L9-L21
train
31,198
batiste/django-page-cms
pages/templatetags/pages_tags.py
_get_content
def _get_content(context, page, content_type, lang, fallback=True): """Helper function used by ``PlaceholderNode``.""" if not page: return '' if not lang and 'lang' in context: lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE) page = get_page_from_string_or_id(page, lang) if not page: return '' content = Content.objects.get_content(page, lang, content_type, fallback) return content
python
def _get_content(context, page, content_type, lang, fallback=True): """Helper function used by ``PlaceholderNode``.""" if not page: return '' if not lang and 'lang' in context: lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE) page = get_page_from_string_or_id(page, lang) if not page: return '' content = Content.objects.get_content(page, lang, content_type, fallback) return content
[ "def", "_get_content", "(", "context", ",", "page", ",", "content_type", ",", "lang", ",", "fallback", "=", "True", ")", ":", "if", "not", "page", ":", "return", "''", "if", "not", "lang", "and", "'lang'", "in", "context", ":", "lang", "=", "context", ...
Helper function used by ``PlaceholderNode``.
[ "Helper", "function", "used", "by", "PlaceholderNode", "." ]
3c72111eb7c3997a63c462c1776ffd8ce8c50a5d
https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/templatetags/pages_tags.py#L40-L54
train
31,199