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
raymontag/kppy
kppy/database.py
KPDBv1.move_entry
def move_entry(self, entry = None, group = None): """Move an entry to another group. A v1Group group and a v1Entry entry are needed. """ if entry is None or group is None or type(entry) is not v1Entry or \ type(group) is not v1Group: raise KPError("Need an entr...
python
def move_entry(self, entry = None, group = None): """Move an entry to another group. A v1Group group and a v1Entry entry are needed. """ if entry is None or group is None or type(entry) is not v1Entry or \ type(group) is not v1Group: raise KPError("Need an entr...
[ "def", "move_entry", "(", "self", ",", "entry", "=", "None", ",", "group", "=", "None", ")", ":", "if", "entry", "is", "None", "or", "group", "is", "None", "or", "type", "(", "entry", ")", "is", "not", "v1Entry", "or", "type", "(", "group", ")", ...
Move an entry to another group. A v1Group group and a v1Entry entry are needed.
[ "Move", "an", "entry", "to", "another", "group", "." ]
a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a
https://github.com/raymontag/kppy/blob/a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a/kppy/database.py#L742-L761
train
62,500
raymontag/kppy
kppy/database.py
KPDBv1.move_entry_in_group
def move_entry_in_group(self, entry = None, index = None): """Move entry to another position inside a group. An entry and a valid index to insert the entry in the entry list of the holding group is needed. 0 means that the entry is moved to the first position 1 to the second and...
python
def move_entry_in_group(self, entry = None, index = None): """Move entry to another position inside a group. An entry and a valid index to insert the entry in the entry list of the holding group is needed. 0 means that the entry is moved to the first position 1 to the second and...
[ "def", "move_entry_in_group", "(", "self", ",", "entry", "=", "None", ",", "index", "=", "None", ")", ":", "if", "entry", "is", "None", "or", "index", "is", "None", "or", "type", "(", "entry", ")", "is", "not", "v1Entry", "or", "type", "(", "index", ...
Move entry to another position inside a group. An entry and a valid index to insert the entry in the entry list of the holding group is needed. 0 means that the entry is moved to the first position 1 to the second and so on.
[ "Move", "entry", "to", "another", "position", "inside", "a", "group", "." ]
a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a
https://github.com/raymontag/kppy/blob/a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a/kppy/database.py#L763-L790
train
62,501
raymontag/kppy
kppy/database.py
KPDBv1._transform_key
def _transform_key(self, masterkey): """This method creates the key to decrypt the database""" aes = AES.new(self._transf_randomseed, AES.MODE_ECB) # Encrypt the created hash for _ in range(self._key_transf_rounds): masterkey = aes.encrypt(masterkey) # Finally, has...
python
def _transform_key(self, masterkey): """This method creates the key to decrypt the database""" aes = AES.new(self._transf_randomseed, AES.MODE_ECB) # Encrypt the created hash for _ in range(self._key_transf_rounds): masterkey = aes.encrypt(masterkey) # Finally, has...
[ "def", "_transform_key", "(", "self", ",", "masterkey", ")", ":", "aes", "=", "AES", ".", "new", "(", "self", ".", "_transf_randomseed", ",", "AES", ".", "MODE_ECB", ")", "# Encrypt the created hash", "for", "_", "in", "range", "(", "self", ".", "_key_tran...
This method creates the key to decrypt the database
[ "This", "method", "creates", "the", "key", "to", "decrypt", "the", "database" ]
a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a
https://github.com/raymontag/kppy/blob/a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a/kppy/database.py#L792-L808
train
62,502
raymontag/kppy
kppy/database.py
KPDBv1._get_filekey
def _get_filekey(self): """This method creates a key from a keyfile.""" if not os.path.exists(self.keyfile): raise KPError('Keyfile not exists.') try: with open(self.keyfile, 'rb') as handler: handler.seek(0, os.SEEK_END) size = handler.te...
python
def _get_filekey(self): """This method creates a key from a keyfile.""" if not os.path.exists(self.keyfile): raise KPError('Keyfile not exists.') try: with open(self.keyfile, 'rb') as handler: handler.seek(0, os.SEEK_END) size = handler.te...
[ "def", "_get_filekey", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "keyfile", ")", ":", "raise", "KPError", "(", "'Keyfile not exists.'", ")", "try", ":", "with", "open", "(", "self", ".", "keyfile", ",", "...
This method creates a key from a keyfile.
[ "This", "method", "creates", "a", "key", "from", "a", "keyfile", "." ]
a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a
https://github.com/raymontag/kppy/blob/a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a/kppy/database.py#L817-L844
train
62,503
raymontag/kppy
kppy/database.py
KPDBv1._cbc_decrypt
def _cbc_decrypt(self, final_key, crypted_content): """This method decrypts the database""" # Just decrypt the content with the created key aes = AES.new(final_key, AES.MODE_CBC, self._enc_iv) decrypted_content = aes.decrypt(crypted_content) padding = decrypted_content[-1] ...
python
def _cbc_decrypt(self, final_key, crypted_content): """This method decrypts the database""" # Just decrypt the content with the created key aes = AES.new(final_key, AES.MODE_CBC, self._enc_iv) decrypted_content = aes.decrypt(crypted_content) padding = decrypted_content[-1] ...
[ "def", "_cbc_decrypt", "(", "self", ",", "final_key", ",", "crypted_content", ")", ":", "# Just decrypt the content with the created key", "aes", "=", "AES", ".", "new", "(", "final_key", ",", "AES", ".", "MODE_CBC", ",", "self", ".", "_enc_iv", ")", "decrypted_...
This method decrypts the database
[ "This", "method", "decrypts", "the", "database" ]
a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a
https://github.com/raymontag/kppy/blob/a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a/kppy/database.py#L846-L859
train
62,504
raymontag/kppy
kppy/database.py
KPDBv1._cbc_encrypt
def _cbc_encrypt(self, content, final_key): """This method encrypts the content.""" aes = AES.new(final_key, AES.MODE_CBC, self._enc_iv) padding = (16 - len(content) % AES.block_size) for _ in range(padding): content += chr(padding).encode() temp = bytes(content) ...
python
def _cbc_encrypt(self, content, final_key): """This method encrypts the content.""" aes = AES.new(final_key, AES.MODE_CBC, self._enc_iv) padding = (16 - len(content) % AES.block_size) for _ in range(padding): content += chr(padding).encode() temp = bytes(content) ...
[ "def", "_cbc_encrypt", "(", "self", ",", "content", ",", "final_key", ")", ":", "aes", "=", "AES", ".", "new", "(", "final_key", ",", "AES", ".", "MODE_CBC", ",", "self", ".", "_enc_iv", ")", "padding", "=", "(", "16", "-", "len", "(", "content", "...
This method encrypts the content.
[ "This", "method", "encrypts", "the", "content", "." ]
a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a
https://github.com/raymontag/kppy/blob/a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a/kppy/database.py#L861-L871
train
62,505
raymontag/kppy
kppy/database.py
KPDBv1._read_group_field
def _read_group_field(self, group, levels, field_type, field_size, decrypted_content): """This method handles the different fields of a group""" if field_type == 0x0000: # Ignored (commentar block) pass elif field_type == 0x0001: g...
python
def _read_group_field(self, group, levels, field_type, field_size, decrypted_content): """This method handles the different fields of a group""" if field_type == 0x0000: # Ignored (commentar block) pass elif field_type == 0x0001: g...
[ "def", "_read_group_field", "(", "self", ",", "group", ",", "levels", ",", "field_type", ",", "field_size", ",", "decrypted_content", ")", ":", "if", "field_type", "==", "0x0000", ":", "# Ignored (commentar block)", "pass", "elif", "field_type", "==", "0x0001", ...
This method handles the different fields of a group
[ "This", "method", "handles", "the", "different", "fields", "of", "a", "group" ]
a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a
https://github.com/raymontag/kppy/blob/a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a/kppy/database.py#L873-L910
train
62,506
raymontag/kppy
kppy/database.py
KPDBv1._read_entry_field
def _read_entry_field(self, entry, field_type, field_size, decrypted_content): """This method handles the different fields of an entry""" if field_type == 0x0000: # Ignored pass elif field_type == 0x0001: entry.uuid = decrypted_conte...
python
def _read_entry_field(self, entry, field_type, field_size, decrypted_content): """This method handles the different fields of an entry""" if field_type == 0x0000: # Ignored pass elif field_type == 0x0001: entry.uuid = decrypted_conte...
[ "def", "_read_entry_field", "(", "self", ",", "entry", ",", "field_type", ",", "field_size", ",", "decrypted_content", ")", ":", "if", "field_type", "==", "0x0000", ":", "# Ignored", "pass", "elif", "field_type", "==", "0x0001", ":", "entry", ".", "uuid", "=...
This method handles the different fields of an entry
[ "This", "method", "handles", "the", "different", "fields", "of", "an", "entry" ]
a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a
https://github.com/raymontag/kppy/blob/a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a/kppy/database.py#L912-L960
train
62,507
raymontag/kppy
kppy/database.py
KPDBv1._get_date
def _get_date(self, decrypted_content): """This method is used to decode the packed dates of entries""" # Just copied from original KeePassX source date_field = struct.unpack('<5B', decrypted_content[:5]) dw1 = date_field[0] dw2 = date_field[1] dw3 = date_field[2...
python
def _get_date(self, decrypted_content): """This method is used to decode the packed dates of entries""" # Just copied from original KeePassX source date_field = struct.unpack('<5B', decrypted_content[:5]) dw1 = date_field[0] dw2 = date_field[1] dw3 = date_field[2...
[ "def", "_get_date", "(", "self", ",", "decrypted_content", ")", ":", "# Just copied from original KeePassX source", "date_field", "=", "struct", ".", "unpack", "(", "'<5B'", ",", "decrypted_content", "[", ":", "5", "]", ")", "dw1", "=", "date_field", "[", "0", ...
This method is used to decode the packed dates of entries
[ "This", "method", "is", "used", "to", "decode", "the", "packed", "dates", "of", "entries" ]
a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a
https://github.com/raymontag/kppy/blob/a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a/kppy/database.py#L962-L979
train
62,508
raymontag/kppy
kppy/database.py
KPDBv1._pack_date
def _pack_date(self, date): """This method is used to encode dates""" # Just copied from original KeePassX source y, mon, d, h, min_, s = date.timetuple()[:6] dw1 = 0x0000FFFF & ((y>>6) & 0x0000003F) dw2 = 0x0000FFFF & ((y & 0x0000003F)<<2 | ((mon>>2) & 0x00000003)) ...
python
def _pack_date(self, date): """This method is used to encode dates""" # Just copied from original KeePassX source y, mon, d, h, min_, s = date.timetuple()[:6] dw1 = 0x0000FFFF & ((y>>6) & 0x0000003F) dw2 = 0x0000FFFF & ((y & 0x0000003F)<<2 | ((mon>>2) & 0x00000003)) ...
[ "def", "_pack_date", "(", "self", ",", "date", ")", ":", "# Just copied from original KeePassX source", "y", ",", "mon", ",", "d", ",", "h", ",", "min_", ",", "s", "=", "date", ".", "timetuple", "(", ")", "[", ":", "6", "]", "dw1", "=", "0x0000FFFF", ...
This method is used to encode dates
[ "This", "method", "is", "used", "to", "encode", "dates" ]
a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a
https://github.com/raymontag/kppy/blob/a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a/kppy/database.py#L981-L994
train
62,509
raymontag/kppy
kppy/database.py
KPDBv1._create_group_tree
def _create_group_tree(self, levels): """This method creates a group tree""" if levels[0] != 0: raise KPError("Invalid group tree") for i in range(len(self.groups)): if(levels[i] == 0): self.groups[i].parent = self.root_group self...
python
def _create_group_tree(self, levels): """This method creates a group tree""" if levels[0] != 0: raise KPError("Invalid group tree") for i in range(len(self.groups)): if(levels[i] == 0): self.groups[i].parent = self.root_group self...
[ "def", "_create_group_tree", "(", "self", ",", "levels", ")", ":", "if", "levels", "[", "0", "]", "!=", "0", ":", "raise", "KPError", "(", "\"Invalid group tree\"", ")", "for", "i", "in", "range", "(", "len", "(", "self", ".", "groups", ")", ")", ":"...
This method creates a group tree
[ "This", "method", "creates", "a", "group", "tree" ]
a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a
https://github.com/raymontag/kppy/blob/a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a/kppy/database.py#L996-L1030
train
62,510
raymontag/kppy
kppy/database.py
KPDBv1._save_group_field
def _save_group_field(self, field_type, group): """This method packs a group field""" if field_type == 0x0000: # Ignored (commentar block) pass elif field_type == 0x0001: if group.id_ is not None: return (4, struct.pack('<I', group.id_...
python
def _save_group_field(self, field_type, group): """This method packs a group field""" if field_type == 0x0000: # Ignored (commentar block) pass elif field_type == 0x0001: if group.id_ is not None: return (4, struct.pack('<I', group.id_...
[ "def", "_save_group_field", "(", "self", ",", "field_type", ",", "group", ")", ":", "if", "field_type", "==", "0x0000", ":", "# Ignored (commentar block)", "pass", "elif", "field_type", "==", "0x0001", ":", "if", "group", ".", "id_", "is", "not", "None", ":"...
This method packs a group field
[ "This", "method", "packs", "a", "group", "field" ]
a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a
https://github.com/raymontag/kppy/blob/a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a/kppy/database.py#L1032-L1066
train
62,511
raymontag/kppy
kppy/database.py
KPDBv1._save_entry_field
def _save_entry_field(self, field_type, entry): """This group packs a entry field""" if field_type == 0x0000: # Ignored pass elif field_type == 0x0001: if entry.uuid is not None: return (16, entry.uuid) elif field_type == 0x0002: ...
python
def _save_entry_field(self, field_type, entry): """This group packs a entry field""" if field_type == 0x0000: # Ignored pass elif field_type == 0x0001: if entry.uuid is not None: return (16, entry.uuid) elif field_type == 0x0002: ...
[ "def", "_save_entry_field", "(", "self", ",", "field_type", ",", "entry", ")", ":", "if", "field_type", "==", "0x0000", ":", "# Ignored", "pass", "elif", "field_type", "==", "0x0001", ":", "if", "entry", ".", "uuid", "is", "not", "None", ":", "return", "...
This group packs a entry field
[ "This", "group", "packs", "a", "entry", "field" ]
a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a
https://github.com/raymontag/kppy/blob/a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a/kppy/database.py#L1068-L1121
train
62,512
latchset/custodia
docs/source/examples/cfgparser.py
CustodiaConfigParser.getsecret
def getsecret(self, section, option, **kwargs): """Get a secret from Custodia """ # keyword-only arguments, vars and fallback are directly passed through raw = kwargs.get('raw', False) value = self.get(section, option, **kwargs) if raw: return value re...
python
def getsecret(self, section, option, **kwargs): """Get a secret from Custodia """ # keyword-only arguments, vars and fallback are directly passed through raw = kwargs.get('raw', False) value = self.get(section, option, **kwargs) if raw: return value re...
[ "def", "getsecret", "(", "self", ",", "section", ",", "option", ",", "*", "*", "kwargs", ")", ":", "# keyword-only arguments, vars and fallback are directly passed through", "raw", "=", "kwargs", ".", "get", "(", "'raw'", ",", "False", ")", "value", "=", "self",...
Get a secret from Custodia
[ "Get", "a", "secret", "from", "Custodia" ]
5ad4cd7a2f40babc6b8b5d16215b7e27ca993b6d
https://github.com/latchset/custodia/blob/5ad4cd7a2f40babc6b8b5d16215b7e27ca993b6d/docs/source/examples/cfgparser.py#L109-L117
train
62,513
latchset/custodia
src/custodia/server/__init__.py
_load_plugin_class
def _load_plugin_class(menu, name): """Load Custodia plugin Entry points are preferred over dotted import path. """ group = 'custodia.{}'.format(menu) eps = list(pkg_resources.iter_entry_points(group, name)) if len(eps) > 1: raise ValueError( "Multiple entry points for {} {}...
python
def _load_plugin_class(menu, name): """Load Custodia plugin Entry points are preferred over dotted import path. """ group = 'custodia.{}'.format(menu) eps = list(pkg_resources.iter_entry_points(group, name)) if len(eps) > 1: raise ValueError( "Multiple entry points for {} {}...
[ "def", "_load_plugin_class", "(", "menu", ",", "name", ")", ":", "group", "=", "'custodia.{}'", ".", "format", "(", "menu", ")", "eps", "=", "list", "(", "pkg_resources", ".", "iter_entry_points", "(", "group", ",", "name", ")", ")", "if", "len", "(", ...
Load Custodia plugin Entry points are preferred over dotted import path.
[ "Load", "Custodia", "plugin" ]
5ad4cd7a2f40babc6b8b5d16215b7e27ca993b6d
https://github.com/latchset/custodia/blob/5ad4cd7a2f40babc6b8b5d16215b7e27ca993b6d/src/custodia/server/__init__.py#L34-L57
train
62,514
latchset/custodia
src/custodia/server/__init__.py
_load_plugins
def _load_plugins(config, cfgparser): """Load and initialize plugins """ # set umask before any plugin gets a chance to create a file os.umask(config['umask']) for s in cfgparser.sections(): if s in {'ENV', 'global'}: # ENV section is only used for interpolation cont...
python
def _load_plugins(config, cfgparser): """Load and initialize plugins """ # set umask before any plugin gets a chance to create a file os.umask(config['umask']) for s in cfgparser.sections(): if s in {'ENV', 'global'}: # ENV section is only used for interpolation cont...
[ "def", "_load_plugins", "(", "config", ",", "cfgparser", ")", ":", "# set umask before any plugin gets a chance to create a file", "os", ".", "umask", "(", "config", "[", "'umask'", "]", ")", "for", "s", "in", "cfgparser", ".", "sections", "(", ")", ":", "if", ...
Load and initialize plugins
[ "Load", "and", "initialize", "plugins" ]
5ad4cd7a2f40babc6b8b5d16215b7e27ca993b6d
https://github.com/latchset/custodia/blob/5ad4cd7a2f40babc6b8b5d16215b7e27ca993b6d/src/custodia/server/__init__.py#L86-L127
train
62,515
latchset/custodia
src/custodia/plugin.py
OptionHandler.get
def get(self, po): """Lookup value for a PluginOption instance Args: po: PluginOption Returns: converted value """ name = po.name typ = po.typ default = po.default handler = getattr(self, '_get_{}'.format(typ), None) if handler is No...
python
def get(self, po): """Lookup value for a PluginOption instance Args: po: PluginOption Returns: converted value """ name = po.name typ = po.typ default = po.default handler = getattr(self, '_get_{}'.format(typ), None) if handler is No...
[ "def", "get", "(", "self", ",", "po", ")", ":", "name", "=", "po", ".", "name", "typ", "=", "po", ".", "typ", "default", "=", "po", ".", "default", "handler", "=", "getattr", "(", "self", ",", "'_get_{}'", ".", "format", "(", "typ", ")", ",", "...
Lookup value for a PluginOption instance Args: po: PluginOption Returns: converted value
[ "Lookup", "value", "for", "a", "PluginOption", "instance" ]
5ad4cd7a2f40babc6b8b5d16215b7e27ca993b6d
https://github.com/latchset/custodia/blob/5ad4cd7a2f40babc6b8b5d16215b7e27ca993b6d/src/custodia/plugin.py#L80-L106
train
62,516
latchset/custodia
src/custodia/message/simple.py
SimpleKey.parse
def parse(self, msg, name): """Parses a simple message :param msg: the json-decoded value :param name: the requested name :raises UnknownMessageType: if the type is not 'simple' :raises InvalidMessage: if the message cannot be parsed or validated """ # On reque...
python
def parse(self, msg, name): """Parses a simple message :param msg: the json-decoded value :param name: the requested name :raises UnknownMessageType: if the type is not 'simple' :raises InvalidMessage: if the message cannot be parsed or validated """ # On reque...
[ "def", "parse", "(", "self", ",", "msg", ",", "name", ")", ":", "# On requests we imply 'simple' if there is no input message", "if", "msg", "is", "None", ":", "return", "if", "not", "isinstance", "(", "msg", ",", "string_types", ")", ":", "raise", "InvalidMessa...
Parses a simple message :param msg: the json-decoded value :param name: the requested name :raises UnknownMessageType: if the type is not 'simple' :raises InvalidMessage: if the message cannot be parsed or validated
[ "Parses", "a", "simple", "message" ]
5ad4cd7a2f40babc6b8b5d16215b7e27ca993b6d
https://github.com/latchset/custodia/blob/5ad4cd7a2f40babc6b8b5d16215b7e27ca993b6d/src/custodia/message/simple.py#L13-L32
train
62,517
latchset/custodia
src/custodia/ipa/vault.py
krb5_unparse_principal_name
def krb5_unparse_principal_name(name): """Split a Kerberos principal name into parts Returns: * ('host', hostname, realm) for a host principal * (servicename, hostname, realm) for a service principal * (None, username, realm) for a user principal :param text name: Kerberos principal n...
python
def krb5_unparse_principal_name(name): """Split a Kerberos principal name into parts Returns: * ('host', hostname, realm) for a host principal * (servicename, hostname, realm) for a service principal * (None, username, realm) for a user principal :param text name: Kerberos principal n...
[ "def", "krb5_unparse_principal_name", "(", "name", ")", ":", "prefix", ",", "realm", "=", "name", ".", "split", "(", "u'@'", ")", "if", "u'/'", "in", "prefix", ":", "service", ",", "host", "=", "prefix", ".", "rsplit", "(", "u'/'", ",", "1", ")", "re...
Split a Kerberos principal name into parts Returns: * ('host', hostname, realm) for a host principal * (servicename, hostname, realm) for a service principal * (None, username, realm) for a user principal :param text name: Kerberos principal name :return: (service, host, realm) or (No...
[ "Split", "a", "Kerberos", "principal", "name", "into", "parts" ]
5ad4cd7a2f40babc6b8b5d16215b7e27ca993b6d
https://github.com/latchset/custodia/blob/5ad4cd7a2f40babc6b8b5d16215b7e27ca993b6d/src/custodia/ipa/vault.py#L18-L34
train
62,518
latchset/custodia
src/custodia/message/kem.py
KEMHandler.parse
def parse(self, msg, name): """Parses the message. We check that the message is properly formatted. :param msg: a json-encoded value containing a JWS or JWE+JWS token :raises InvalidMessage: if the message cannot be parsed or validated :returns: A verified payload """...
python
def parse(self, msg, name): """Parses the message. We check that the message is properly formatted. :param msg: a json-encoded value containing a JWS or JWE+JWS token :raises InvalidMessage: if the message cannot be parsed or validated :returns: A verified payload """...
[ "def", "parse", "(", "self", ",", "msg", ",", "name", ")", ":", "try", ":", "jtok", "=", "JWT", "(", "jwt", "=", "msg", ")", "except", "Exception", "as", "e", ":", "raise", "InvalidMessage", "(", "'Failed to parse message: %s'", "%", "str", "(", "e", ...
Parses the message. We check that the message is properly formatted. :param msg: a json-encoded value containing a JWS or JWE+JWS token :raises InvalidMessage: if the message cannot be parsed or validated :returns: A verified payload
[ "Parses", "the", "message", "." ]
5ad4cd7a2f40babc6b8b5d16215b7e27ca993b6d
https://github.com/latchset/custodia/blob/5ad4cd7a2f40babc6b8b5d16215b7e27ca993b6d/src/custodia/message/kem.py#L133-L183
train
62,519
latchset/custodia
src/custodia/server/args.py
instance_name
def instance_name(string): """Check for valid instance name """ invalid = ':/@' if set(string).intersection(invalid): msg = 'Invalid instance name {}'.format(string) raise argparse.ArgumentTypeError(msg) return string
python
def instance_name(string): """Check for valid instance name """ invalid = ':/@' if set(string).intersection(invalid): msg = 'Invalid instance name {}'.format(string) raise argparse.ArgumentTypeError(msg) return string
[ "def", "instance_name", "(", "string", ")", ":", "invalid", "=", "':/@'", "if", "set", "(", "string", ")", ".", "intersection", "(", "invalid", ")", ":", "msg", "=", "'Invalid instance name {}'", ".", "format", "(", "string", ")", "raise", "argparse", ".",...
Check for valid instance name
[ "Check", "for", "valid", "instance", "name" ]
5ad4cd7a2f40babc6b8b5d16215b7e27ca993b6d
https://github.com/latchset/custodia/blob/5ad4cd7a2f40babc6b8b5d16215b7e27ca993b6d/src/custodia/server/args.py#L35-L42
train
62,520
rocky/python-xasm
xasm/pyc_convert.py
copy_magic_into_pyc
def copy_magic_into_pyc(input_pyc, output_pyc, src_version, dest_version): """Bytecodes are the same except the magic number, so just change that""" (version, timestamp, magic_int, co, is_pypy, source_size) = load_module(input_pyc) assert version == float(src_version), ( ...
python
def copy_magic_into_pyc(input_pyc, output_pyc, src_version, dest_version): """Bytecodes are the same except the magic number, so just change that""" (version, timestamp, magic_int, co, is_pypy, source_size) = load_module(input_pyc) assert version == float(src_version), ( ...
[ "def", "copy_magic_into_pyc", "(", "input_pyc", ",", "output_pyc", ",", "src_version", ",", "dest_version", ")", ":", "(", "version", ",", "timestamp", ",", "magic_int", ",", "co", ",", "is_pypy", ",", "source_size", ")", "=", "load_module", "(", "input_pyc", ...
Bytecodes are the same except the magic number, so just change that
[ "Bytecodes", "are", "the", "same", "except", "the", "magic", "number", "so", "just", "change", "that" ]
03e9576112934d00fbc70645b781ed7b3e3fcda1
https://github.com/rocky/python-xasm/blob/03e9576112934d00fbc70645b781ed7b3e3fcda1/xasm/pyc_convert.py#L27-L39
train
62,521
rocky/python-xasm
xasm/pyc_convert.py
transform_26_27
def transform_26_27(inst, new_inst, i, n, offset, instructions, new_asm): """Change JUMP_IF_FALSE and JUMP_IF_TRUE to POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE""" if inst.opname in ('JUMP_IF_FALSE', 'JUMP_IF_TRUE'): i += 1 assert i < n assert instructions[i].opname =...
python
def transform_26_27(inst, new_inst, i, n, offset, instructions, new_asm): """Change JUMP_IF_FALSE and JUMP_IF_TRUE to POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE""" if inst.opname in ('JUMP_IF_FALSE', 'JUMP_IF_TRUE'): i += 1 assert i < n assert instructions[i].opname =...
[ "def", "transform_26_27", "(", "inst", ",", "new_inst", ",", "i", ",", "n", ",", "offset", ",", "instructions", ",", "new_asm", ")", ":", "if", "inst", ".", "opname", "in", "(", "'JUMP_IF_FALSE'", ",", "'JUMP_IF_TRUE'", ")", ":", "i", "+=", "1", "asser...
Change JUMP_IF_FALSE and JUMP_IF_TRUE to POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE
[ "Change", "JUMP_IF_FALSE", "and", "JUMP_IF_TRUE", "to", "POP_JUMP_IF_FALSE", "and", "POP_JUMP_IF_TRUE" ]
03e9576112934d00fbc70645b781ed7b3e3fcda1
https://github.com/rocky/python-xasm/blob/03e9576112934d00fbc70645b781ed7b3e3fcda1/xasm/pyc_convert.py#L53-L70
train
62,522
rocky/python-xasm
xasm/pyc_convert.py
transform_32_33
def transform_32_33(inst, new_inst, i, n, offset, instructions, new_asm): """MAKEFUNCTION adds another const. probably MAKECLASS as well """ add_size = xdis.op_size(new_inst.opcode, opcode_33) if inst.opname in ('MAKE_FUNCTION','MAKE_CLOSURE'): # Previous instruction should b...
python
def transform_32_33(inst, new_inst, i, n, offset, instructions, new_asm): """MAKEFUNCTION adds another const. probably MAKECLASS as well """ add_size = xdis.op_size(new_inst.opcode, opcode_33) if inst.opname in ('MAKE_FUNCTION','MAKE_CLOSURE'): # Previous instruction should b...
[ "def", "transform_32_33", "(", "inst", ",", "new_inst", ",", "i", ",", "n", ",", "offset", ",", "instructions", ",", "new_asm", ")", ":", "add_size", "=", "xdis", ".", "op_size", "(", "new_inst", ".", "opcode", ",", "opcode_33", ")", "if", "inst", ".",...
MAKEFUNCTION adds another const. probably MAKECLASS as well
[ "MAKEFUNCTION", "adds", "another", "const", ".", "probably", "MAKECLASS", "as", "well" ]
03e9576112934d00fbc70645b781ed7b3e3fcda1
https://github.com/rocky/python-xasm/blob/03e9576112934d00fbc70645b781ed7b3e3fcda1/xasm/pyc_convert.py#L72-L106
train
62,523
rocky/python-xasm
xasm/pyc_convert.py
transform_33_32
def transform_33_32(inst, new_inst, i, n, offset, instructions, new_asm): """MAKE_FUNCTION, and MAKE_CLOSURE have an additional LOAD_CONST of a name that are not in Python 3.2. Remove these. """ add_size = xdis.op_size(new_inst.opcode, opcode_33) if inst.opname in ('MAKE_FUNCTION...
python
def transform_33_32(inst, new_inst, i, n, offset, instructions, new_asm): """MAKE_FUNCTION, and MAKE_CLOSURE have an additional LOAD_CONST of a name that are not in Python 3.2. Remove these. """ add_size = xdis.op_size(new_inst.opcode, opcode_33) if inst.opname in ('MAKE_FUNCTION...
[ "def", "transform_33_32", "(", "inst", ",", "new_inst", ",", "i", ",", "n", ",", "offset", ",", "instructions", ",", "new_asm", ")", ":", "add_size", "=", "xdis", ".", "op_size", "(", "new_inst", ".", "opcode", ",", "opcode_33", ")", "if", "inst", ".",...
MAKE_FUNCTION, and MAKE_CLOSURE have an additional LOAD_CONST of a name that are not in Python 3.2. Remove these.
[ "MAKE_FUNCTION", "and", "MAKE_CLOSURE", "have", "an", "additional", "LOAD_CONST", "of", "a", "name", "that", "are", "not", "in", "Python", "3", ".", "2", ".", "Remove", "these", "." ]
03e9576112934d00fbc70645b781ed7b3e3fcda1
https://github.com/rocky/python-xasm/blob/03e9576112934d00fbc70645b781ed7b3e3fcda1/xasm/pyc_convert.py#L108-L134
train
62,524
rocky/python-xasm
xasm/pyc_convert.py
main
def main(conversion_type, input_pyc, output_pyc): """Convert Python bytecode from one version to another. INPUT_PYC contains the input bytecode path name OUTPUT_PYC contians the output bytecode path name if supplied The --conversion type option specifies what conversion to do. Note: there are a v...
python
def main(conversion_type, input_pyc, output_pyc): """Convert Python bytecode from one version to another. INPUT_PYC contains the input bytecode path name OUTPUT_PYC contians the output bytecode path name if supplied The --conversion type option specifies what conversion to do. Note: there are a v...
[ "def", "main", "(", "conversion_type", ",", "input_pyc", ",", "output_pyc", ")", ":", "shortname", "=", "osp", ".", "basename", "(", "input_pyc", ")", "if", "shortname", ".", "endswith", "(", "'.pyc'", ")", ":", "shortname", "=", "shortname", "[", ":", "...
Convert Python bytecode from one version to another. INPUT_PYC contains the input bytecode path name OUTPUT_PYC contians the output bytecode path name if supplied The --conversion type option specifies what conversion to do. Note: there are a very limited set of conversions currently supported. H...
[ "Convert", "Python", "bytecode", "from", "one", "version", "to", "another", "." ]
03e9576112934d00fbc70645b781ed7b3e3fcda1
https://github.com/rocky/python-xasm/blob/03e9576112934d00fbc70645b781ed7b3e3fcda1/xasm/pyc_convert.py#L189-L220
train
62,525
kailashbuki/fingerprint
fingerprint/fingerprint.py
Fingerprint.generate
def generate(self, str=None, fpath=None): """generates fingerprints of the input. Either provide `str` to compute fingerprint directly from your string or `fpath` to compute fingerprint from the text of the file. Make sure to have your text decoded in `utf-8` format if you pass the input string. Args: ...
python
def generate(self, str=None, fpath=None): """generates fingerprints of the input. Either provide `str` to compute fingerprint directly from your string or `fpath` to compute fingerprint from the text of the file. Make sure to have your text decoded in `utf-8` format if you pass the input string. Args: ...
[ "def", "generate", "(", "self", ",", "str", "=", "None", ",", "fpath", "=", "None", ")", ":", "self", ".", "prepare_storage", "(", ")", "self", ".", "str", "=", "self", ".", "load_file", "(", "fpath", ")", "if", "fpath", "else", "self", ".", "sanit...
generates fingerprints of the input. Either provide `str` to compute fingerprint directly from your string or `fpath` to compute fingerprint from the text of the file. Make sure to have your text decoded in `utf-8` format if you pass the input string. Args: str (Optional(str)): string whose fingerp...
[ "generates", "fingerprints", "of", "the", "input", ".", "Either", "provide", "str", "to", "compute", "fingerprint", "directly", "from", "your", "string", "or", "fpath", "to", "compute", "fingerprint", "from", "the", "text", "of", "the", "file", ".", "Make", ...
674bf8615d81afa7657b003f8700590ff269de65
https://github.com/kailashbuki/fingerprint/blob/674bf8615d81afa7657b003f8700590ff269de65/fingerprint/fingerprint.py#L114-L133
train
62,526
rocky/python-xasm
xasm/xasm_cli.py
main
def main(pyc_file, asm_path): """ Create Python bytecode from a Python assembly file. ASM_PATH gives the input Python assembly file. We suggest ending the file in .pyc If --pyc-file is given, that indicates the path to write the Python bytecode. The path should end in '.pyc'. See https://...
python
def main(pyc_file, asm_path): """ Create Python bytecode from a Python assembly file. ASM_PATH gives the input Python assembly file. We suggest ending the file in .pyc If --pyc-file is given, that indicates the path to write the Python bytecode. The path should end in '.pyc'. See https://...
[ "def", "main", "(", "pyc_file", ",", "asm_path", ")", ":", "if", "os", ".", "stat", "(", "asm_path", ")", ".", "st_size", "==", "0", ":", "print", "(", "\"Size of assembly file %s is zero\"", "%", "asm_path", ")", "sys", ".", "exit", "(", "1", ")", "as...
Create Python bytecode from a Python assembly file. ASM_PATH gives the input Python assembly file. We suggest ending the file in .pyc If --pyc-file is given, that indicates the path to write the Python bytecode. The path should end in '.pyc'. See https://github.com/rocky/python-xasm/blob/master/H...
[ "Create", "Python", "bytecode", "from", "a", "Python", "assembly", "file", "." ]
03e9576112934d00fbc70645b781ed7b3e3fcda1
https://github.com/rocky/python-xasm/blob/03e9576112934d00fbc70645b781ed7b3e3fcda1/xasm/xasm_cli.py#L11-L32
train
62,527
tgs/requests-jwt
requests_jwt.py
JWTAuth.expire
def expire(self, secs): """ Adds the standard 'exp' field, used to prevent replay attacks. Adds the 'exp' field to the payload. When a request is made, the field says that it should expire at now + `secs` seconds. Of course, this provides no protection unless the server reads ...
python
def expire(self, secs): """ Adds the standard 'exp' field, used to prevent replay attacks. Adds the 'exp' field to the payload. When a request is made, the field says that it should expire at now + `secs` seconds. Of course, this provides no protection unless the server reads ...
[ "def", "expire", "(", "self", ",", "secs", ")", ":", "self", ".", "add_field", "(", "'exp'", ",", "lambda", "req", ":", "int", "(", "time", ".", "time", "(", ")", "+", "secs", ")", ")" ]
Adds the standard 'exp' field, used to prevent replay attacks. Adds the 'exp' field to the payload. When a request is made, the field says that it should expire at now + `secs` seconds. Of course, this provides no protection unless the server reads and interprets this field.
[ "Adds", "the", "standard", "exp", "field", "used", "to", "prevent", "replay", "attacks", "." ]
0806813c3da1d379e5ced09328cffa35bfbb73ad
https://github.com/tgs/requests-jwt/blob/0806813c3da1d379e5ced09328cffa35bfbb73ad/requests_jwt.py#L117-L128
train
62,528
tgs/requests-jwt
requests_jwt.py
JWTAuth._generate
def _generate(self, request): """ Generate a payload for the given request. """ payload = {} for field, gen in self._generators.items(): value = None if callable(gen): value = gen(request) else: value = gen ...
python
def _generate(self, request): """ Generate a payload for the given request. """ payload = {} for field, gen in self._generators.items(): value = None if callable(gen): value = gen(request) else: value = gen ...
[ "def", "_generate", "(", "self", ",", "request", ")", ":", "payload", "=", "{", "}", "for", "field", ",", "gen", "in", "self", ".", "_generators", ".", "items", "(", ")", ":", "value", "=", "None", "if", "callable", "(", "gen", ")", ":", "value", ...
Generate a payload for the given request.
[ "Generate", "a", "payload", "for", "the", "given", "request", "." ]
0806813c3da1d379e5ced09328cffa35bfbb73ad
https://github.com/tgs/requests-jwt/blob/0806813c3da1d379e5ced09328cffa35bfbb73ad/requests_jwt.py#L137-L151
train
62,529
mapnik/Cascadenik
cascadenik/compile.py
url2fs
def url2fs(url): """ encode a URL to be safe as a filename """ uri, extension = posixpath.splitext(url) return safe64.dir(uri) + extension
python
def url2fs(url): """ encode a URL to be safe as a filename """ uri, extension = posixpath.splitext(url) return safe64.dir(uri) + extension
[ "def", "url2fs", "(", "url", ")", ":", "uri", ",", "extension", "=", "posixpath", ".", "splitext", "(", "url", ")", "return", "safe64", ".", "dir", "(", "uri", ")", "+", "extension" ]
encode a URL to be safe as a filename
[ "encode", "a", "URL", "to", "be", "safe", "as", "a", "filename" ]
82f66859340a31dfcb24af127274f262d4f3ad85
https://github.com/mapnik/Cascadenik/blob/82f66859340a31dfcb24af127274f262d4f3ad85/cascadenik/compile.py#L104-L107
train
62,530
mapnik/Cascadenik
cascadenik/compile.py
is_merc_projection
def is_merc_projection(srs): """ Return true if the map projection matches that used by VEarth, Google, OSM, etc. Is currently necessary for zoom-level shorthand for scale-denominator. """ if srs.lower() == '+init=epsg:900913': return True # observed srs = dict([p.split('=') fo...
python
def is_merc_projection(srs): """ Return true if the map projection matches that used by VEarth, Google, OSM, etc. Is currently necessary for zoom-level shorthand for scale-denominator. """ if srs.lower() == '+init=epsg:900913': return True # observed srs = dict([p.split('=') fo...
[ "def", "is_merc_projection", "(", "srs", ")", ":", "if", "srs", ".", "lower", "(", ")", "==", "'+init=epsg:900913'", ":", "return", "True", "# observed", "srs", "=", "dict", "(", "[", "p", ".", "split", "(", "'='", ")", "for", "p", "in", "srs", ".", ...
Return true if the map projection matches that used by VEarth, Google, OSM, etc. Is currently necessary for zoom-level shorthand for scale-denominator.
[ "Return", "true", "if", "the", "map", "projection", "matches", "that", "used", "by", "VEarth", "Google", "OSM", "etc", ".", "Is", "currently", "necessary", "for", "zoom", "-", "level", "shorthand", "for", "scale", "-", "denominator", "." ]
82f66859340a31dfcb24af127274f262d4f3ad85
https://github.com/mapnik/Cascadenik/blob/82f66859340a31dfcb24af127274f262d4f3ad85/cascadenik/compile.py#L587-L608
train
62,531
mapnik/Cascadenik
cascadenik/compile.py
extract_declarations
def extract_declarations(map_el, dirs, scale=1, user_styles=[]): """ Given a Map element and directories object, remove and return a complete list of style declarations from any Stylesheet elements found within. """ styles = [] # # First, look at all the stylesheets defined in the map i...
python
def extract_declarations(map_el, dirs, scale=1, user_styles=[]): """ Given a Map element and directories object, remove and return a complete list of style declarations from any Stylesheet elements found within. """ styles = [] # # First, look at all the stylesheets defined in the map i...
[ "def", "extract_declarations", "(", "map_el", ",", "dirs", ",", "scale", "=", "1", ",", "user_styles", "=", "[", "]", ")", ":", "styles", "=", "[", "]", "#", "# First, look at all the stylesheets defined in the map itself.", "#", "for", "stylesheet", "in", "map_...
Given a Map element and directories object, remove and return a complete list of style declarations from any Stylesheet elements found within.
[ "Given", "a", "Map", "element", "and", "directories", "object", "remove", "and", "return", "a", "complete", "list", "of", "style", "declarations", "from", "any", "Stylesheet", "elements", "found", "within", "." ]
82f66859340a31dfcb24af127274f262d4f3ad85
https://github.com/mapnik/Cascadenik/blob/82f66859340a31dfcb24af127274f262d4f3ad85/cascadenik/compile.py#L610-L656
train
62,532
mapnik/Cascadenik
cascadenik/compile.py
is_applicable_selector
def is_applicable_selector(selector, filter): """ Given a Selector and Filter, return True if the Selector is compatible with the given Filter, and False if they contradict. """ for test in selector.allTests(): if not test.isCompatible(filter.tests): return False return ...
python
def is_applicable_selector(selector, filter): """ Given a Selector and Filter, return True if the Selector is compatible with the given Filter, and False if they contradict. """ for test in selector.allTests(): if not test.isCompatible(filter.tests): return False return ...
[ "def", "is_applicable_selector", "(", "selector", ",", "filter", ")", ":", "for", "test", "in", "selector", ".", "allTests", "(", ")", ":", "if", "not", "test", ".", "isCompatible", "(", "filter", ".", "tests", ")", ":", "return", "False", "return", "Tru...
Given a Selector and Filter, return True if the Selector is compatible with the given Filter, and False if they contradict.
[ "Given", "a", "Selector", "and", "Filter", "return", "True", "if", "the", "Selector", "is", "compatible", "with", "the", "given", "Filter", "and", "False", "if", "they", "contradict", "." ]
82f66859340a31dfcb24af127274f262d4f3ad85
https://github.com/mapnik/Cascadenik/blob/82f66859340a31dfcb24af127274f262d4f3ad85/cascadenik/compile.py#L787-L795
train
62,533
mapnik/Cascadenik
cascadenik/compile.py
get_polygon_rules
def get_polygon_rules(declarations): """ Given a Map element, a Layer element, and a list of declarations, create a new Style element with a PolygonSymbolizer, add it to Map and refer to it in Layer. """ property_map = {'polygon-fill': 'fill', 'polygon-opacity': 'fill-opacity', ...
python
def get_polygon_rules(declarations): """ Given a Map element, a Layer element, and a list of declarations, create a new Style element with a PolygonSymbolizer, add it to Map and refer to it in Layer. """ property_map = {'polygon-fill': 'fill', 'polygon-opacity': 'fill-opacity', ...
[ "def", "get_polygon_rules", "(", "declarations", ")", ":", "property_map", "=", "{", "'polygon-fill'", ":", "'fill'", ",", "'polygon-opacity'", ":", "'fill-opacity'", ",", "'polygon-gamma'", ":", "'gamma'", ",", "'polygon-meta-output'", ":", "'meta-output'", ",", "'...
Given a Map element, a Layer element, and a list of declarations, create a new Style element with a PolygonSymbolizer, add it to Map and refer to it in Layer.
[ "Given", "a", "Map", "element", "a", "Layer", "element", "and", "a", "list", "of", "declarations", "create", "a", "new", "Style", "element", "with", "a", "PolygonSymbolizer", "add", "it", "to", "Map", "and", "refer", "to", "it", "in", "Layer", "." ]
82f66859340a31dfcb24af127274f262d4f3ad85
https://github.com/mapnik/Cascadenik/blob/82f66859340a31dfcb24af127274f262d4f3ad85/cascadenik/compile.py#L844-L867
train
62,534
mapnik/Cascadenik
cascadenik/compile.py
get_raster_rules
def get_raster_rules(declarations): """ Given a Map element, a Layer element, and a list of declarations, create a new Style element with a RasterSymbolizer, add it to Map and refer to it in Layer. The RasterSymbolizer will always created, even if there are no applicable dec...
python
def get_raster_rules(declarations): """ Given a Map element, a Layer element, and a list of declarations, create a new Style element with a RasterSymbolizer, add it to Map and refer to it in Layer. The RasterSymbolizer will always created, even if there are no applicable dec...
[ "def", "get_raster_rules", "(", "declarations", ")", ":", "property_map", "=", "{", "'raster-opacity'", ":", "'opacity'", ",", "'raster-mode'", ":", "'mode'", ",", "'raster-scaling'", ":", "'scaling'", "}", "property_names", "=", "property_map", ".", "keys", "(", ...
Given a Map element, a Layer element, and a list of declarations, create a new Style element with a RasterSymbolizer, add it to Map and refer to it in Layer. The RasterSymbolizer will always created, even if there are no applicable declarations.
[ "Given", "a", "Map", "element", "a", "Layer", "element", "and", "a", "list", "of", "declarations", "create", "a", "new", "Style", "element", "with", "a", "RasterSymbolizer", "add", "it", "to", "Map", "and", "refer", "to", "it", "in", "Layer", ".", "The",...
82f66859340a31dfcb24af127274f262d4f3ad85
https://github.com/mapnik/Cascadenik/blob/82f66859340a31dfcb24af127274f262d4f3ad85/cascadenik/compile.py#L869-L900
train
62,535
mapnik/Cascadenik
cascadenik/compile.py
locally_cache_remote_file
def locally_cache_remote_file(href, dir): """ Locally cache a remote resource using a predictable file name and awareness of modification date. Assume that files are "normal" which is to say they have filenames with extensions. """ scheme, host, remote_path, params, query, fragment = urlpars...
python
def locally_cache_remote_file(href, dir): """ Locally cache a remote resource using a predictable file name and awareness of modification date. Assume that files are "normal" which is to say they have filenames with extensions. """ scheme, host, remote_path, params, query, fragment = urlpars...
[ "def", "locally_cache_remote_file", "(", "href", ",", "dir", ")", ":", "scheme", ",", "host", ",", "remote_path", ",", "params", ",", "query", ",", "fragment", "=", "urlparse", "(", "href", ")", "assert", "scheme", "in", "(", "'http'", ",", "'https'", ")...
Locally cache a remote resource using a predictable file name and awareness of modification date. Assume that files are "normal" which is to say they have filenames with extensions.
[ "Locally", "cache", "a", "remote", "resource", "using", "a", "predictable", "file", "name", "and", "awareness", "of", "modification", "date", ".", "Assume", "that", "files", "are", "normal", "which", "is", "to", "say", "they", "have", "filenames", "with", "e...
82f66859340a31dfcb24af127274f262d4f3ad85
https://github.com/mapnik/Cascadenik/blob/82f66859340a31dfcb24af127274f262d4f3ad85/cascadenik/compile.py#L1064-L1117
train
62,536
mapnik/Cascadenik
cascadenik/compile.py
post_process_symbolizer_image_file
def post_process_symbolizer_image_file(file_href, dirs): """ Given an image file href and a set of directories, modify the image file name so it's correct with respect to the output and cache directories. """ # support latest mapnik features of auto-detection # of image sizes and jpeg reading su...
python
def post_process_symbolizer_image_file(file_href, dirs): """ Given an image file href and a set of directories, modify the image file name so it's correct with respect to the output and cache directories. """ # support latest mapnik features of auto-detection # of image sizes and jpeg reading su...
[ "def", "post_process_symbolizer_image_file", "(", "file_href", ",", "dirs", ")", ":", "# support latest mapnik features of auto-detection", "# of image sizes and jpeg reading support...", "# http://trac.mapnik.org/ticket/508", "mapnik_auto_image_support", "=", "(", "MAPNIK_VERSION", ">...
Given an image file href and a set of directories, modify the image file name so it's correct with respect to the output and cache directories.
[ "Given", "an", "image", "file", "href", "and", "a", "set", "of", "directories", "modify", "the", "image", "file", "name", "so", "it", "s", "correct", "with", "respect", "to", "the", "output", "and", "cache", "directories", "." ]
82f66859340a31dfcb24af127274f262d4f3ad85
https://github.com/mapnik/Cascadenik/blob/82f66859340a31dfcb24af127274f262d4f3ad85/cascadenik/compile.py#L1119-L1165
train
62,537
mapnik/Cascadenik
cascadenik/compile.py
localize_shapefile
def localize_shapefile(shp_href, dirs): """ Given a shapefile href and a set of directories, modify the shapefile name so it's correct with respect to the output and cache directories. """ # support latest mapnik features of auto-detection # of image sizes and jpeg reading support... # http:...
python
def localize_shapefile(shp_href, dirs): """ Given a shapefile href and a set of directories, modify the shapefile name so it's correct with respect to the output and cache directories. """ # support latest mapnik features of auto-detection # of image sizes and jpeg reading support... # http:...
[ "def", "localize_shapefile", "(", "shp_href", ",", "dirs", ")", ":", "# support latest mapnik features of auto-detection", "# of image sizes and jpeg reading support...", "# http://trac.mapnik.org/ticket/508", "mapnik_requires_absolute_paths", "=", "(", "MAPNIK_VERSION", "<", "601", ...
Given a shapefile href and a set of directories, modify the shapefile name so it's correct with respect to the output and cache directories.
[ "Given", "a", "shapefile", "href", "and", "a", "set", "of", "directories", "modify", "the", "shapefile", "name", "so", "it", "s", "correct", "with", "respect", "to", "the", "output", "and", "cache", "directories", "." ]
82f66859340a31dfcb24af127274f262d4f3ad85
https://github.com/mapnik/Cascadenik/blob/82f66859340a31dfcb24af127274f262d4f3ad85/cascadenik/compile.py#L1385-L1421
train
62,538
mapnik/Cascadenik
cascadenik/compile.py
localize_file_datasource
def localize_file_datasource(file_href, dirs): """ Handle localizing file-based datasources other than shapefiles. This will only work for single-file based types. """ # support latest mapnik features of auto-detection # of image sizes and jpeg reading support... # http://trac.mapnik.or...
python
def localize_file_datasource(file_href, dirs): """ Handle localizing file-based datasources other than shapefiles. This will only work for single-file based types. """ # support latest mapnik features of auto-detection # of image sizes and jpeg reading support... # http://trac.mapnik.or...
[ "def", "localize_file_datasource", "(", "file_href", ",", "dirs", ")", ":", "# support latest mapnik features of auto-detection", "# of image sizes and jpeg reading support...", "# http://trac.mapnik.org/ticket/508", "mapnik_requires_absolute_paths", "=", "(", "MAPNIK_VERSION", "<", ...
Handle localizing file-based datasources other than shapefiles. This will only work for single-file based types.
[ "Handle", "localizing", "file", "-", "based", "datasources", "other", "than", "shapefiles", ".", "This", "will", "only", "work", "for", "single", "-", "file", "based", "types", "." ]
82f66859340a31dfcb24af127274f262d4f3ad85
https://github.com/mapnik/Cascadenik/blob/82f66859340a31dfcb24af127274f262d4f3ad85/cascadenik/compile.py#L1423-L1447
train
62,539
mapnik/Cascadenik
cascadenik/compile.py
Range.midpoint
def midpoint(self): """ Return a point guranteed to fall within this range, hopefully near the middle. """ minpoint = self.leftedge if self.leftop is gt: minpoint += 1 maxpoint = self.rightedge if self.rightop is lt: maxpoint -= 1 i...
python
def midpoint(self): """ Return a point guranteed to fall within this range, hopefully near the middle. """ minpoint = self.leftedge if self.leftop is gt: minpoint += 1 maxpoint = self.rightedge if self.rightop is lt: maxpoint -= 1 i...
[ "def", "midpoint", "(", "self", ")", ":", "minpoint", "=", "self", ".", "leftedge", "if", "self", ".", "leftop", "is", "gt", ":", "minpoint", "+=", "1", "maxpoint", "=", "self", ".", "rightedge", "if", "self", ".", "rightop", "is", "lt", ":", "maxpoi...
Return a point guranteed to fall within this range, hopefully near the middle.
[ "Return", "a", "point", "guranteed", "to", "fall", "within", "this", "range", "hopefully", "near", "the", "middle", "." ]
82f66859340a31dfcb24af127274f262d4f3ad85
https://github.com/mapnik/Cascadenik/blob/82f66859340a31dfcb24af127274f262d4f3ad85/cascadenik/compile.py#L186-L206
train
62,540
mapnik/Cascadenik
cascadenik/compile.py
Range.isOpen
def isOpen(self): """ Return true if this range has any room in it. """ if self.leftedge and self.rightedge and self.leftedge > self.rightedge: return False if self.leftedge == self.rightedge: if self.leftop is gt or self.rightop is lt: return...
python
def isOpen(self): """ Return true if this range has any room in it. """ if self.leftedge and self.rightedge and self.leftedge > self.rightedge: return False if self.leftedge == self.rightedge: if self.leftop is gt or self.rightop is lt: return...
[ "def", "isOpen", "(", "self", ")", ":", "if", "self", ".", "leftedge", "and", "self", ".", "rightedge", "and", "self", ".", "leftedge", ">", "self", ".", "rightedge", ":", "return", "False", "if", "self", ".", "leftedge", "==", "self", ".", "rightedge"...
Return true if this range has any room in it.
[ "Return", "true", "if", "this", "range", "has", "any", "room", "in", "it", "." ]
82f66859340a31dfcb24af127274f262d4f3ad85
https://github.com/mapnik/Cascadenik/blob/82f66859340a31dfcb24af127274f262d4f3ad85/cascadenik/compile.py#L208-L218
train
62,541
mapnik/Cascadenik
cascadenik/compile.py
Range.toFilter
def toFilter(self, property): """ Convert this range to a Filter with a tests having a given property. """ if self.leftedge == self.rightedge and self.leftop is ge and self.rightop is le: # equivalent to == return Filter(style.SelectorAttributeTest(property, '=', self.lef...
python
def toFilter(self, property): """ Convert this range to a Filter with a tests having a given property. """ if self.leftedge == self.rightedge and self.leftop is ge and self.rightop is le: # equivalent to == return Filter(style.SelectorAttributeTest(property, '=', self.lef...
[ "def", "toFilter", "(", "self", ",", "property", ")", ":", "if", "self", ".", "leftedge", "==", "self", ".", "rightedge", "and", "self", ".", "leftop", "is", "ge", "and", "self", ".", "rightop", "is", "le", ":", "# equivalent to ==", "return", "Filter", ...
Convert this range to a Filter with a tests having a given property.
[ "Convert", "this", "range", "to", "a", "Filter", "with", "a", "tests", "having", "a", "given", "property", "." ]
82f66859340a31dfcb24af127274f262d4f3ad85
https://github.com/mapnik/Cascadenik/blob/82f66859340a31dfcb24af127274f262d4f3ad85/cascadenik/compile.py#L220-L237
train
62,542
mapnik/Cascadenik
cascadenik/compile.py
Filter.isOpen
def isOpen(self): """ Return true if this filter is not trivially false, i.e. self-contradictory. """ equals = {} nequals = {} for test in self.tests: if test.op == '=': if equals.has_key(test.property) and test.value != equals[test.property]:...
python
def isOpen(self): """ Return true if this filter is not trivially false, i.e. self-contradictory. """ equals = {} nequals = {} for test in self.tests: if test.op == '=': if equals.has_key(test.property) and test.value != equals[test.property]:...
[ "def", "isOpen", "(", "self", ")", ":", "equals", "=", "{", "}", "nequals", "=", "{", "}", "for", "test", "in", "self", ".", "tests", ":", "if", "test", ".", "op", "==", "'='", ":", "if", "equals", ".", "has_key", "(", "test", ".", "property", ...
Return true if this filter is not trivially false, i.e. self-contradictory.
[ "Return", "true", "if", "this", "filter", "is", "not", "trivially", "false", "i", ".", "e", ".", "self", "-", "contradictory", "." ]
82f66859340a31dfcb24af127274f262d4f3ad85
https://github.com/mapnik/Cascadenik/blob/82f66859340a31dfcb24af127274f262d4f3ad85/cascadenik/compile.py#L265-L293
train
62,543
mapnik/Cascadenik
cascadenik/compile.py
Filter.minusExtras
def minusExtras(self): """ Return a new Filter that's equal to this one, without extra terms that don't add meaning. """ assert self.isOpen() trimmed = self.clone() equals = {} for test in trimmed.tests: if test.op == '='...
python
def minusExtras(self): """ Return a new Filter that's equal to this one, without extra terms that don't add meaning. """ assert self.isOpen() trimmed = self.clone() equals = {} for test in trimmed.tests: if test.op == '='...
[ "def", "minusExtras", "(", "self", ")", ":", "assert", "self", ".", "isOpen", "(", ")", "trimmed", "=", "self", ".", "clone", "(", ")", "equals", "=", "{", "}", "for", "test", "in", "trimmed", ".", "tests", ":", "if", "test", ".", "op", "==", "'=...
Return a new Filter that's equal to this one, without extra terms that don't add meaning.
[ "Return", "a", "new", "Filter", "that", "s", "equal", "to", "this", "one", "without", "extra", "terms", "that", "don", "t", "add", "meaning", "." ]
82f66859340a31dfcb24af127274f262d4f3ad85
https://github.com/mapnik/Cascadenik/blob/82f66859340a31dfcb24af127274f262d4f3ad85/cascadenik/compile.py#L300-L323
train
62,544
GGiecold/Concurrent_AP
Concurrent_AP.py
add_preference
def add_preference(hdf5_file, preference): """Assign the value 'preference' to the diagonal entries of the matrix of similarities stored in the HDF5 data structure at 'hdf5_file'. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.roo...
python
def add_preference(hdf5_file, preference): """Assign the value 'preference' to the diagonal entries of the matrix of similarities stored in the HDF5 data structure at 'hdf5_file'. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.roo...
[ "def", "add_preference", "(", "hdf5_file", ",", "preference", ")", ":", "Worker", ".", "hdf5_lock", ".", "acquire", "(", ")", "with", "tables", ".", "open_file", "(", "hdf5_file", ",", "'r+'", ")", "as", "fileh", ":", "S", "=", "fileh", ".", "root", "....
Assign the value 'preference' to the diagonal entries of the matrix of similarities stored in the HDF5 data structure at 'hdf5_file'.
[ "Assign", "the", "value", "preference", "to", "the", "diagonal", "entries", "of", "the", "matrix", "of", "similarities", "stored", "in", "the", "HDF5", "data", "structure", "at", "hdf5_file", "." ]
d4cebe06268b5d520352a83cadb2f7520650460c
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L565-L578
train
62,545
GGiecold/Concurrent_AP
Concurrent_AP.py
add_fluctuations
def add_fluctuations(hdf5_file, N_columns, N_processes): """This procedure organizes the addition of small fluctuations on top of a matrix of similarities at 'hdf5_file' across 'N_processes' different processes. Each of those processes is an instance of the class 'Fluctuations_Worker' def...
python
def add_fluctuations(hdf5_file, N_columns, N_processes): """This procedure organizes the addition of small fluctuations on top of a matrix of similarities at 'hdf5_file' across 'N_processes' different processes. Each of those processes is an instance of the class 'Fluctuations_Worker' def...
[ "def", "add_fluctuations", "(", "hdf5_file", ",", "N_columns", ",", "N_processes", ")", ":", "random_state", "=", "np", ".", "random", ".", "RandomState", "(", "0", ")", "slice_queue", "=", "multiprocessing", ".", "JoinableQueue", "(", ")", "pid_list", "=", ...
This procedure organizes the addition of small fluctuations on top of a matrix of similarities at 'hdf5_file' across 'N_processes' different processes. Each of those processes is an instance of the class 'Fluctuations_Worker' defined elsewhere in this module.
[ "This", "procedure", "organizes", "the", "addition", "of", "small", "fluctuations", "on", "top", "of", "a", "matrix", "of", "similarities", "at", "hdf5_file", "across", "N_processes", "different", "processes", ".", "Each", "of", "those", "processes", "is", "an",...
d4cebe06268b5d520352a83cadb2f7520650460c
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L581-L608
train
62,546
GGiecold/Concurrent_AP
Concurrent_AP.py
compute_responsibilities
def compute_responsibilities(hdf5_file, N_columns, damping, N_processes): """Organize the computation and update of the responsibility matrix for Affinity Propagation clustering with 'damping' as the eponymous damping parameter. Each of the processes concurrently involved in this task is a...
python
def compute_responsibilities(hdf5_file, N_columns, damping, N_processes): """Organize the computation and update of the responsibility matrix for Affinity Propagation clustering with 'damping' as the eponymous damping parameter. Each of the processes concurrently involved in this task is a...
[ "def", "compute_responsibilities", "(", "hdf5_file", ",", "N_columns", ",", "damping", ",", "N_processes", ")", ":", "slice_queue", "=", "multiprocessing", ".", "JoinableQueue", "(", ")", "pid_list", "=", "[", "]", "for", "i", "in", "range", "(", "N_processes"...
Organize the computation and update of the responsibility matrix for Affinity Propagation clustering with 'damping' as the eponymous damping parameter. Each of the processes concurrently involved in this task is an instance of the class 'Responsibilities_worker' defined above.
[ "Organize", "the", "computation", "and", "update", "of", "the", "responsibility", "matrix", "for", "Affinity", "Propagation", "clustering", "with", "damping", "as", "the", "eponymous", "damping", "parameter", ".", "Each", "of", "the", "processes", "concurrently", ...
d4cebe06268b5d520352a83cadb2f7520650460c
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L611-L634
train
62,547
GGiecold/Concurrent_AP
Concurrent_AP.py
to_numpy_array
def to_numpy_array(multiprocessing_array, shape, dtype): """Convert a share multiprocessing array to a numpy array. No data copying involved. """ return np.frombuffer(multiprocessing_array.get_obj(), dtype = dtype).reshape(shape)
python
def to_numpy_array(multiprocessing_array, shape, dtype): """Convert a share multiprocessing array to a numpy array. No data copying involved. """ return np.frombuffer(multiprocessing_array.get_obj(), dtype = dtype).reshape(shape)
[ "def", "to_numpy_array", "(", "multiprocessing_array", ",", "shape", ",", "dtype", ")", ":", "return", "np", ".", "frombuffer", "(", "multiprocessing_array", ".", "get_obj", "(", ")", ",", "dtype", "=", "dtype", ")", ".", "reshape", "(", "shape", ")" ]
Convert a share multiprocessing array to a numpy array. No data copying involved.
[ "Convert", "a", "share", "multiprocessing", "array", "to", "a", "numpy", "array", ".", "No", "data", "copying", "involved", "." ]
d4cebe06268b5d520352a83cadb2f7520650460c
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L655-L661
train
62,548
GGiecold/Concurrent_AP
Concurrent_AP.py
compute_rows_sum
def compute_rows_sum(hdf5_file, path, N_columns, N_processes, method = 'Process'): """Parallel computation of the sums across the rows of two-dimensional array accessible at the node specified by 'path' in the 'hdf5_file' hierarchical data format. """ assert isinstance(me...
python
def compute_rows_sum(hdf5_file, path, N_columns, N_processes, method = 'Process'): """Parallel computation of the sums across the rows of two-dimensional array accessible at the node specified by 'path' in the 'hdf5_file' hierarchical data format. """ assert isinstance(me...
[ "def", "compute_rows_sum", "(", "hdf5_file", ",", "path", ",", "N_columns", ",", "N_processes", ",", "method", "=", "'Process'", ")", ":", "assert", "isinstance", "(", "method", ",", "str", ")", ",", "\"parameter 'method' must consist in a string of characters\"", "...
Parallel computation of the sums across the rows of two-dimensional array accessible at the node specified by 'path' in the 'hdf5_file' hierarchical data format.
[ "Parallel", "computation", "of", "the", "sums", "across", "the", "rows", "of", "two", "-", "dimensional", "array", "accessible", "at", "the", "node", "specified", "by", "path", "in", "the", "hdf5_file", "hierarchical", "data", "format", "." ]
d4cebe06268b5d520352a83cadb2f7520650460c
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L664-L709
train
62,549
GGiecold/Concurrent_AP
Concurrent_AP.py
check_convergence
def check_convergence(hdf5_file, iteration, convergence_iter, max_iter): """If the estimated number of clusters has not changed for 'convergence_iter' consecutive iterations in a total of 'max_iter' rounds of message-passing, the procedure herewith returns 'True'. Otherwise, returns 'False'...
python
def check_convergence(hdf5_file, iteration, convergence_iter, max_iter): """If the estimated number of clusters has not changed for 'convergence_iter' consecutive iterations in a total of 'max_iter' rounds of message-passing, the procedure herewith returns 'True'. Otherwise, returns 'False'...
[ "def", "check_convergence", "(", "hdf5_file", ",", "iteration", ",", "convergence_iter", ",", "max_iter", ")", ":", "Worker", ".", "hdf5_lock", ".", "acquire", "(", ")", "with", "tables", ".", "open_file", "(", "hdf5_file", ",", "'r+'", ")", "as", "fileh", ...
If the estimated number of clusters has not changed for 'convergence_iter' consecutive iterations in a total of 'max_iter' rounds of message-passing, the procedure herewith returns 'True'. Otherwise, returns 'False'. Parameter 'iteration' identifies the run of message-passing t...
[ "If", "the", "estimated", "number", "of", "clusters", "has", "not", "changed", "for", "convergence_iter", "consecutive", "iterations", "in", "a", "total", "of", "max_iter", "rounds", "of", "message", "-", "passing", "the", "procedure", "herewith", "returns", "Tr...
d4cebe06268b5d520352a83cadb2f7520650460c
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L757-L790
train
62,550
GGiecold/Concurrent_AP
Concurrent_AP.py
cluster_labels_A
def cluster_labels_A(hdf5_file, c, lock, I, rows_slice): """One of the task to be performed by a pool of subprocesses, as the first step in identifying the cluster labels and indices of the cluster centers for Affinity Propagation clustering. """ with Worker.hdf5_lock: with tables.o...
python
def cluster_labels_A(hdf5_file, c, lock, I, rows_slice): """One of the task to be performed by a pool of subprocesses, as the first step in identifying the cluster labels and indices of the cluster centers for Affinity Propagation clustering. """ with Worker.hdf5_lock: with tables.o...
[ "def", "cluster_labels_A", "(", "hdf5_file", ",", "c", ",", "lock", ",", "I", ",", "rows_slice", ")", ":", "with", "Worker", ".", "hdf5_lock", ":", "with", "tables", ".", "open_file", "(", "hdf5_file", ",", "'r+'", ")", "as", "fileh", ":", "S", "=", ...
One of the task to be performed by a pool of subprocesses, as the first step in identifying the cluster labels and indices of the cluster centers for Affinity Propagation clustering.
[ "One", "of", "the", "task", "to", "be", "performed", "by", "a", "pool", "of", "subprocesses", "as", "the", "first", "step", "in", "identifying", "the", "cluster", "labels", "and", "indices", "of", "the", "cluster", "centers", "for", "Affinity", "Propagation"...
d4cebe06268b5d520352a83cadb2f7520650460c
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L827-L843
train
62,551
GGiecold/Concurrent_AP
Concurrent_AP.py
cluster_labels_B
def cluster_labels_B(hdf5_file, s_reduced, lock, I, ii, iix, rows_slice): """Second task to be performed by a pool of subprocesses before the cluster labels and cluster center indices can be identified. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: ...
python
def cluster_labels_B(hdf5_file, s_reduced, lock, I, ii, iix, rows_slice): """Second task to be performed by a pool of subprocesses before the cluster labels and cluster center indices can be identified. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: ...
[ "def", "cluster_labels_B", "(", "hdf5_file", ",", "s_reduced", ",", "lock", ",", "I", ",", "ii", ",", "iix", ",", "rows_slice", ")", ":", "with", "Worker", ".", "hdf5_lock", ":", "with", "tables", ".", "open_file", "(", "hdf5_file", ",", "'r+'", ")", "...
Second task to be performed by a pool of subprocesses before the cluster labels and cluster center indices can be identified.
[ "Second", "task", "to", "be", "performed", "by", "a", "pool", "of", "subprocesses", "before", "the", "cluster", "labels", "and", "cluster", "center", "indices", "can", "be", "identified", "." ]
d4cebe06268b5d520352a83cadb2f7520650460c
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L846-L862
train
62,552
GGiecold/Concurrent_AP
Concurrent_AP.py
output_clusters
def output_clusters(labels, cluster_centers_indices): """Write in tab-separated files the vectors of cluster identities and of indices of cluster centers. """ here = os.getcwd() try: output_directory = os.path.join(here, 'concurrent_AP_output') os.makedirs(output_dir...
python
def output_clusters(labels, cluster_centers_indices): """Write in tab-separated files the vectors of cluster identities and of indices of cluster centers. """ here = os.getcwd() try: output_directory = os.path.join(here, 'concurrent_AP_output') os.makedirs(output_dir...
[ "def", "output_clusters", "(", "labels", ",", "cluster_centers_indices", ")", ":", "here", "=", "os", ".", "getcwd", "(", ")", "try", ":", "output_directory", "=", "os", ".", "path", ".", "join", "(", "here", ",", "'concurrent_AP_output'", ")", "os", ".", ...
Write in tab-separated files the vectors of cluster identities and of indices of cluster centers.
[ "Write", "in", "tab", "-", "separated", "files", "the", "vectors", "of", "cluster", "identities", "and", "of", "indices", "of", "cluster", "centers", "." ]
d4cebe06268b5d520352a83cadb2f7520650460c
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L993-L1020
train
62,553
ttsteiger/cryptocompy
cryptocompy/coin.py
get_coin_snapshot
def get_coin_snapshot(fsym, tsym): """ Get blockchain information, aggregated data as well as data for the individual exchanges available for the specified currency pair. Args: fsym: FROM symbol. tsym: TO symbol. Returns: The function returns a dictionairy containing blockain as well as trading inform...
python
def get_coin_snapshot(fsym, tsym): """ Get blockchain information, aggregated data as well as data for the individual exchanges available for the specified currency pair. Args: fsym: FROM symbol. tsym: TO symbol. Returns: The function returns a dictionairy containing blockain as well as trading inform...
[ "def", "get_coin_snapshot", "(", "fsym", ",", "tsym", ")", ":", "# load data", "url", "=", "build_url", "(", "'coinsnapshot'", ",", "fsym", "=", "fsym", ",", "tsym", "=", "tsym", ")", "data", "=", "load_data", "(", "url", ")", "[", "'Data'", "]", "retu...
Get blockchain information, aggregated data as well as data for the individual exchanges available for the specified currency pair. Args: fsym: FROM symbol. tsym: TO symbol. Returns: The function returns a dictionairy containing blockain as well as trading information from the different exchanges were t...
[ "Get", "blockchain", "information", "aggregated", "data", "as", "well", "as", "data", "for", "the", "individual", "exchanges", "available", "for", "the", "specified", "currency", "pair", "." ]
b0514079202587a5bfb3a4f2c871196315b9302e
https://github.com/ttsteiger/cryptocompy/blob/b0514079202587a5bfb3a4f2c871196315b9302e/cryptocompy/coin.py#L56-L101
train
62,554
mapnik/Cascadenik
cascadenik/style.py
Selector.matches
def matches(self, tag, id, classes): """ Given an id and a list of classes, return True if this selector would match. """ element = self.elements[0] unmatched_ids = [name[1:] for name in element.names if name.startswith('#')] unmatched_classes = [name[1:] for name in element.name...
python
def matches(self, tag, id, classes): """ Given an id and a list of classes, return True if this selector would match. """ element = self.elements[0] unmatched_ids = [name[1:] for name in element.names if name.startswith('#')] unmatched_classes = [name[1:] for name in element.name...
[ "def", "matches", "(", "self", ",", "tag", ",", "id", ",", "classes", ")", ":", "element", "=", "self", ".", "elements", "[", "0", "]", "unmatched_ids", "=", "[", "name", "[", "1", ":", "]", "for", "name", "in", "element", ".", "names", "if", "na...
Given an id and a list of classes, return True if this selector would match.
[ "Given", "an", "id", "and", "a", "list", "of", "classes", "return", "True", "if", "this", "selector", "would", "match", "." ]
82f66859340a31dfcb24af127274f262d4f3ad85
https://github.com/mapnik/Cascadenik/blob/82f66859340a31dfcb24af127274f262d4f3ad85/cascadenik/style.py#L451-L473
train
62,555
mapnik/Cascadenik
cascadenik/style.py
Selector.scaledBy
def scaledBy(self, scale): """ Return a new Selector with scale denominators scaled by a number. """ scaled = deepcopy(self) for test in scaled.elements[0].tests: if type(test.value) in (int, float): if test.property == 'scale-denominator': ...
python
def scaledBy(self, scale): """ Return a new Selector with scale denominators scaled by a number. """ scaled = deepcopy(self) for test in scaled.elements[0].tests: if type(test.value) in (int, float): if test.property == 'scale-denominator': ...
[ "def", "scaledBy", "(", "self", ",", "scale", ")", ":", "scaled", "=", "deepcopy", "(", "self", ")", "for", "test", "in", "scaled", ".", "elements", "[", "0", "]", ".", "tests", ":", "if", "type", "(", "test", ".", "value", ")", "in", "(", "int",...
Return a new Selector with scale denominators scaled by a number.
[ "Return", "a", "new", "Selector", "with", "scale", "denominators", "scaled", "by", "a", "number", "." ]
82f66859340a31dfcb24af127274f262d4f3ad85
https://github.com/mapnik/Cascadenik/blob/82f66859340a31dfcb24af127274f262d4f3ad85/cascadenik/style.py#L514-L526
train
62,556
mapnik/Cascadenik
cascadenik/style.py
Value.scaledBy
def scaledBy(self, scale): """ Return a new Value scaled by a given number for ints and floats. """ scaled = deepcopy(self) if type(scaled.value) in (int, float): scaled.value *= scale elif isinstance(scaled.value, numbers): scaled.value.values = tupl...
python
def scaledBy(self, scale): """ Return a new Value scaled by a given number for ints and floats. """ scaled = deepcopy(self) if type(scaled.value) in (int, float): scaled.value *= scale elif isinstance(scaled.value, numbers): scaled.value.values = tupl...
[ "def", "scaledBy", "(", "self", ",", "scale", ")", ":", "scaled", "=", "deepcopy", "(", "self", ")", "if", "type", "(", "scaled", ".", "value", ")", "in", "(", "int", ",", "float", ")", ":", "scaled", ".", "value", "*=", "scale", "elif", "isinstanc...
Return a new Value scaled by a given number for ints and floats.
[ "Return", "a", "new", "Value", "scaled", "by", "a", "given", "number", "for", "ints", "and", "floats", "." ]
82f66859340a31dfcb24af127274f262d4f3ad85
https://github.com/mapnik/Cascadenik/blob/82f66859340a31dfcb24af127274f262d4f3ad85/cascadenik/style.py#L802-L812
train
62,557
ttsteiger/cryptocompy
cryptocompy/mining.py
get_mining_contracts
def get_mining_contracts(): """ Get all the mining contracts information available. Returns: This function returns two major dictionaries. The first one contains information about the coins for which mining contracts data is available: coin_data: {symbol1: {'BlockNumber': ..., '...
python
def get_mining_contracts(): """ Get all the mining contracts information available. Returns: This function returns two major dictionaries. The first one contains information about the coins for which mining contracts data is available: coin_data: {symbol1: {'BlockNumber': ..., '...
[ "def", "get_mining_contracts", "(", ")", ":", "# load data", "url", "=", "build_url", "(", "'miningcontracts'", ")", "data", "=", "load_data", "(", "url", ")", "coin_data", "=", "data", "[", "'CoinData'", "]", "mining_data", "=", "data", "[", "'MiningData'", ...
Get all the mining contracts information available. Returns: This function returns two major dictionaries. The first one contains information about the coins for which mining contracts data is available: coin_data: {symbol1: {'BlockNumber': ..., 'BlockReward': ..., 'B...
[ "Get", "all", "the", "mining", "contracts", "information", "available", "." ]
b0514079202587a5bfb3a4f2c871196315b9302e
https://github.com/ttsteiger/cryptocompy/blob/b0514079202587a5bfb3a4f2c871196315b9302e/cryptocompy/mining.py#L6-L65
train
62,558
ttsteiger/cryptocompy
cryptocompy/mining.py
get_mining_equipment
def get_mining_equipment(): """Get all the mining equipment information available. Returns: This function returns two major dictionaries. The first one contains information about the coins for which mining equipment data is available. coin_data: {symbol1: {'BlockNumber': ..., 'BlockReward': ....
python
def get_mining_equipment(): """Get all the mining equipment information available. Returns: This function returns two major dictionaries. The first one contains information about the coins for which mining equipment data is available. coin_data: {symbol1: {'BlockNumber': ..., 'BlockReward': ....
[ "def", "get_mining_equipment", "(", ")", ":", "# load data", "url", "=", "build_url", "(", "'miningequipment'", ")", "data", "=", "load_data", "(", "url", ")", "coin_data", "=", "data", "[", "'CoinData'", "]", "mining_data", "=", "data", "[", "'MiningData'", ...
Get all the mining equipment information available. Returns: This function returns two major dictionaries. The first one contains information about the coins for which mining equipment data is available. coin_data: {symbol1: {'BlockNumber': ..., 'BlockReward': ..., 'BlockRewardRe...
[ "Get", "all", "the", "mining", "equipment", "information", "available", "." ]
b0514079202587a5bfb3a4f2c871196315b9302e
https://github.com/ttsteiger/cryptocompy/blob/b0514079202587a5bfb3a4f2c871196315b9302e/cryptocompy/mining.py#L68-L120
train
62,559
mapnik/Cascadenik
cascadenik-compile.py
main
def main(src_file, dest_file, **kwargs): """ Given an input layers file and a directory, print the compiled XML file to stdout and save any encountered external image files to the named directory. """ mmap = mapnik.Map(1, 1) # allow [zoom] filters to work mmap.srs = '+proj=merc +a=63...
python
def main(src_file, dest_file, **kwargs): """ Given an input layers file and a directory, print the compiled XML file to stdout and save any encountered external image files to the named directory. """ mmap = mapnik.Map(1, 1) # allow [zoom] filters to work mmap.srs = '+proj=merc +a=63...
[ "def", "main", "(", "src_file", ",", "dest_file", ",", "*", "*", "kwargs", ")", ":", "mmap", "=", "mapnik", ".", "Map", "(", "1", ",", "1", ")", "# allow [zoom] filters to work", "mmap", ".", "srs", "=", "'+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 ...
Given an input layers file and a directory, print the compiled XML file to stdout and save any encountered external image files to the named directory.
[ "Given", "an", "input", "layers", "file", "and", "a", "directory", "print", "the", "compiled", "XML", "file", "to", "stdout", "and", "save", "any", "encountered", "external", "image", "files", "to", "the", "named", "directory", "." ]
82f66859340a31dfcb24af127274f262d4f3ad85
https://github.com/mapnik/Cascadenik/blob/82f66859340a31dfcb24af127274f262d4f3ad85/cascadenik-compile.py#L24-L52
train
62,560
mapnik/Cascadenik
cascadenik/safe64.py
chunk
def chunk(url): """ create filesystem-safe places for url-keyed data to be stored """ chunks = lambda l, n: [l[x: x+n] for x in xrange(0, len(l), n)] url_64 = base64.urlsafe_b64encode(url) return chunks(url_64, 255)
python
def chunk(url): """ create filesystem-safe places for url-keyed data to be stored """ chunks = lambda l, n: [l[x: x+n] for x in xrange(0, len(l), n)] url_64 = base64.urlsafe_b64encode(url) return chunks(url_64, 255)
[ "def", "chunk", "(", "url", ")", ":", "chunks", "=", "lambda", "l", ",", "n", ":", "[", "l", "[", "x", ":", "x", "+", "n", "]", "for", "x", "in", "xrange", "(", "0", ",", "len", "(", "l", ")", ",", "n", ")", "]", "url_64", "=", "base64", ...
create filesystem-safe places for url-keyed data to be stored
[ "create", "filesystem", "-", "safe", "places", "for", "url", "-", "keyed", "data", "to", "be", "stored" ]
82f66859340a31dfcb24af127274f262d4f3ad85
https://github.com/mapnik/Cascadenik/blob/82f66859340a31dfcb24af127274f262d4f3ad85/cascadenik/safe64.py#L15-L19
train
62,561
mapnik/Cascadenik
cascadenik-style.py
main
def main(filename): """ Given an input file containing nothing but styles, print out an unrolled list of declarations in cascade order. """ input = open(filename, 'r').read() declarations = cascadenik.stylesheet_declarations(input, is_merc=True) for dec in declarations: print de...
python
def main(filename): """ Given an input file containing nothing but styles, print out an unrolled list of declarations in cascade order. """ input = open(filename, 'r').read() declarations = cascadenik.stylesheet_declarations(input, is_merc=True) for dec in declarations: print de...
[ "def", "main", "(", "filename", ")", ":", "input", "=", "open", "(", "filename", ",", "'r'", ")", ".", "read", "(", ")", "declarations", "=", "cascadenik", ".", "stylesheet_declarations", "(", "input", ",", "is_merc", "=", "True", ")", "for", "dec", "i...
Given an input file containing nothing but styles, print out an unrolled list of declarations in cascade order.
[ "Given", "an", "input", "file", "containing", "nothing", "but", "styles", "print", "out", "an", "unrolled", "list", "of", "declarations", "in", "cascade", "order", "." ]
82f66859340a31dfcb24af127274f262d4f3ad85
https://github.com/mapnik/Cascadenik/blob/82f66859340a31dfcb24af127274f262d4f3ad85/cascadenik-style.py#L12-L38
train
62,562
theolind/pymysensors
mysensors/const_20.py
validate_gps
def validate_gps(value): """Validate GPS value.""" try: latitude, longitude, altitude = value.split(',') vol.Coerce(float)(latitude) vol.Coerce(float)(longitude) vol.Coerce(float)(altitude) except (TypeError, ValueError, vol.Invalid): raise vol.Invalid( 'G...
python
def validate_gps(value): """Validate GPS value.""" try: latitude, longitude, altitude = value.split(',') vol.Coerce(float)(latitude) vol.Coerce(float)(longitude) vol.Coerce(float)(altitude) except (TypeError, ValueError, vol.Invalid): raise vol.Invalid( 'G...
[ "def", "validate_gps", "(", "value", ")", ":", "try", ":", "latitude", ",", "longitude", ",", "altitude", "=", "value", ".", "split", "(", "','", ")", "vol", ".", "Coerce", "(", "float", ")", "(", "latitude", ")", "vol", ".", "Coerce", "(", "float", ...
Validate GPS value.
[ "Validate", "GPS", "value", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/const_20.py#L281-L291
train
62,563
theolind/pymysensors
mysensors/gateway_tcp.py
TCPGateway._connect
def _connect(self): """Connect to socket. This should be run in a new thread.""" while self.protocol: _LOGGER.info('Trying to connect to %s', self.server_address) try: sock = socket.create_connection( self.server_address, self.reconnect_timeout...
python
def _connect(self): """Connect to socket. This should be run in a new thread.""" while self.protocol: _LOGGER.info('Trying to connect to %s', self.server_address) try: sock = socket.create_connection( self.server_address, self.reconnect_timeout...
[ "def", "_connect", "(", "self", ")", ":", "while", "self", ".", "protocol", ":", "_LOGGER", ".", "info", "(", "'Trying to connect to %s'", ",", "self", ".", "server_address", ")", "try", ":", "sock", "=", "socket", ".", "create_connection", "(", "self", "....
Connect to socket. This should be run in a new thread.
[ "Connect", "to", "socket", ".", "This", "should", "be", "run", "in", "a", "new", "thread", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/gateway_tcp.py#L76-L108
train
62,564
theolind/pymysensors
mysensors/gateway_tcp.py
AsyncTCPGateway._connect
def _connect(self): """Connect to the socket.""" try: while True: _LOGGER.info('Trying to connect to %s', self.server_address) try: yield from asyncio.wait_for( self.loop.create_connection( ...
python
def _connect(self): """Connect to the socket.""" try: while True: _LOGGER.info('Trying to connect to %s', self.server_address) try: yield from asyncio.wait_for( self.loop.create_connection( ...
[ "def", "_connect", "(", "self", ")", ":", "try", ":", "while", "True", ":", "_LOGGER", ".", "info", "(", "'Trying to connect to %s'", ",", "self", ".", "server_address", ")", "try", ":", "yield", "from", "asyncio", ".", "wait_for", "(", "self", ".", "loo...
Connect to the socket.
[ "Connect", "to", "the", "socket", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/gateway_tcp.py#L127-L161
train
62,565
theolind/pymysensors
mysensors/gateway_tcp.py
TCPTransport.run
def run(self): """Transport thread loop.""" # pylint: disable=broad-except self.protocol = self.protocol_factory() try: self.protocol.connection_made(self) except Exception as exc: self.alive = False self.protocol.connection_lost(exc) ...
python
def run(self): """Transport thread loop.""" # pylint: disable=broad-except self.protocol = self.protocol_factory() try: self.protocol.connection_made(self) except Exception as exc: self.alive = False self.protocol.connection_lost(exc) ...
[ "def", "run", "(", "self", ")", ":", "# pylint: disable=broad-except", "self", ".", "protocol", "=", "self", ".", "protocol_factory", "(", ")", "try", ":", "self", ".", "protocol", ".", "connection_made", "(", "self", ")", "except", "Exception", "as", "exc",...
Transport thread loop.
[ "Transport", "thread", "loop", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/gateway_tcp.py#L223-L260
train
62,566
theolind/pymysensors
mysensors/util.py
Registry.register
def register(self, name): """Return decorator to register item with a specific name.""" def decorator(func): """Register decorated function.""" self[name] = func return func return decorator
python
def register(self, name): """Return decorator to register item with a specific name.""" def decorator(func): """Register decorated function.""" self[name] = func return func return decorator
[ "def", "register", "(", "self", ",", "name", ")", ":", "def", "decorator", "(", "func", ")", ":", "\"\"\"Register decorated function.\"\"\"", "self", "[", "name", "]", "=", "func", "return", "func", "return", "decorator" ]
Return decorator to register item with a specific name.
[ "Return", "decorator", "to", "register", "item", "with", "a", "specific", "name", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/util.py#L10-L17
train
62,567
theolind/pymysensors
mysensors/gateway_mqtt.py
BaseMQTTGateway._handle_subscription
def _handle_subscription(self, topics): """Handle subscription of topics.""" if not isinstance(topics, list): topics = [topics] for topic in topics: topic_levels = topic.split('/') try: qos = int(topic_levels[-2]) except ValueError:...
python
def _handle_subscription(self, topics): """Handle subscription of topics.""" if not isinstance(topics, list): topics = [topics] for topic in topics: topic_levels = topic.split('/') try: qos = int(topic_levels[-2]) except ValueError:...
[ "def", "_handle_subscription", "(", "self", ",", "topics", ")", ":", "if", "not", "isinstance", "(", "topics", ",", "list", ")", ":", "topics", "=", "[", "topics", "]", "for", "topic", "in", "topics", ":", "topic_levels", "=", "topic", ".", "split", "(...
Handle subscription of topics.
[ "Handle", "subscription", "of", "topics", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/gateway_mqtt.py#L34-L49
train
62,568
theolind/pymysensors
mysensors/gateway_mqtt.py
BaseMQTTGateway._init_topics
def _init_topics(self): """Set up initial subscription of mysensors topics.""" _LOGGER.info('Setting up initial MQTT topic subscription') init_topics = [ '{}/+/+/0/+/+'.format(self._in_prefix), '{}/+/+/3/+/+'.format(self._in_prefix), ] self._handle_subscri...
python
def _init_topics(self): """Set up initial subscription of mysensors topics.""" _LOGGER.info('Setting up initial MQTT topic subscription') init_topics = [ '{}/+/+/0/+/+'.format(self._in_prefix), '{}/+/+/3/+/+'.format(self._in_prefix), ] self._handle_subscri...
[ "def", "_init_topics", "(", "self", ")", ":", "_LOGGER", ".", "info", "(", "'Setting up initial MQTT topic subscription'", ")", "init_topics", "=", "[", "'{}/+/+/0/+/+'", ".", "format", "(", "self", ".", "_in_prefix", ")", ",", "'{}/+/+/3/+/+'", ".", "format", "...
Set up initial subscription of mysensors topics.
[ "Set", "up", "initial", "subscription", "of", "mysensors", "topics", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/gateway_mqtt.py#L51-L74
train
62,569
theolind/pymysensors
mysensors/gateway_mqtt.py
BaseMQTTGateway._parse_mqtt_to_message
def _parse_mqtt_to_message(self, topic, payload, qos): """Parse a MQTT topic and payload. Return a mysensors command string. """ topic_levels = topic.split('/') topic_levels = not_prefix = topic_levels[-5:] prefix_end_idx = topic.find('/'.join(not_prefix)) - 1 pr...
python
def _parse_mqtt_to_message(self, topic, payload, qos): """Parse a MQTT topic and payload. Return a mysensors command string. """ topic_levels = topic.split('/') topic_levels = not_prefix = topic_levels[-5:] prefix_end_idx = topic.find('/'.join(not_prefix)) - 1 pr...
[ "def", "_parse_mqtt_to_message", "(", "self", ",", "topic", ",", "payload", ",", "qos", ")", ":", "topic_levels", "=", "topic", ".", "split", "(", "'/'", ")", "topic_levels", "=", "not_prefix", "=", "topic_levels", "[", "-", "5", ":", "]", "prefix_end_idx"...
Parse a MQTT topic and payload. Return a mysensors command string.
[ "Parse", "a", "MQTT", "topic", "and", "payload", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/gateway_mqtt.py#L76-L93
train
62,570
theolind/pymysensors
mysensors/gateway_mqtt.py
BaseMQTTGateway._parse_message_to_mqtt
def _parse_message_to_mqtt(self, data): """Parse a mysensors command string. Return a MQTT topic, payload and qos-level as a tuple. """ msg = Message(data, self) payload = str(msg.payload) msg.payload = '' # prefix/node/child/type/ack/subtype : payload re...
python
def _parse_message_to_mqtt(self, data): """Parse a mysensors command string. Return a MQTT topic, payload and qos-level as a tuple. """ msg = Message(data, self) payload = str(msg.payload) msg.payload = '' # prefix/node/child/type/ack/subtype : payload re...
[ "def", "_parse_message_to_mqtt", "(", "self", ",", "data", ")", ":", "msg", "=", "Message", "(", "data", ",", "self", ")", "payload", "=", "str", "(", "msg", ".", "payload", ")", "msg", ".", "payload", "=", "''", "# prefix/node/child/type/ack/subtype : paylo...
Parse a mysensors command string. Return a MQTT topic, payload and qos-level as a tuple.
[ "Parse", "a", "mysensors", "command", "string", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/gateway_mqtt.py#L95-L105
train
62,571
theolind/pymysensors
mysensors/gateway_mqtt.py
BaseMQTTGateway._handle_presentation
def _handle_presentation(self, msg): """Process a MQTT presentation message.""" ret_msg = handle_presentation(msg) if msg.child_id == 255 or ret_msg is None: return # this is a presentation of a child sensor topics = [ '{}/{}/{}/{}/+/+'.format( ...
python
def _handle_presentation(self, msg): """Process a MQTT presentation message.""" ret_msg = handle_presentation(msg) if msg.child_id == 255 or ret_msg is None: return # this is a presentation of a child sensor topics = [ '{}/{}/{}/{}/+/+'.format( ...
[ "def", "_handle_presentation", "(", "self", ",", "msg", ")", ":", "ret_msg", "=", "handle_presentation", "(", "msg", ")", "if", "msg", ".", "child_id", "==", "255", "or", "ret_msg", "is", "None", ":", "return", "# this is a presentation of a child sensor", "topi...
Process a MQTT presentation message.
[ "Process", "a", "MQTT", "presentation", "message", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/gateway_mqtt.py#L107-L123
train
62,572
theolind/pymysensors
mysensors/gateway_mqtt.py
BaseMQTTGateway.recv
def recv(self, topic, payload, qos): """Receive a MQTT message. Call this method when a message is received from the MQTT broker. """ data = self._parse_mqtt_to_message(topic, payload, qos) if data is None: return _LOGGER.debug('Receiving %s', data) s...
python
def recv(self, topic, payload, qos): """Receive a MQTT message. Call this method when a message is received from the MQTT broker. """ data = self._parse_mqtt_to_message(topic, payload, qos) if data is None: return _LOGGER.debug('Receiving %s', data) s...
[ "def", "recv", "(", "self", ",", "topic", ",", "payload", ",", "qos", ")", ":", "data", "=", "self", ".", "_parse_mqtt_to_message", "(", "topic", ",", "payload", ",", "qos", ")", "if", "data", "is", "None", ":", "return", "_LOGGER", ".", "debug", "("...
Receive a MQTT message. Call this method when a message is received from the MQTT broker.
[ "Receive", "a", "MQTT", "message", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/gateway_mqtt.py#L129-L138
train
62,573
theolind/pymysensors
mysensors/gateway_mqtt.py
BaseMQTTGateway.send
def send(self, message): """Publish a command string to the gateway via MQTT.""" if not message: return topic, payload, qos = self._parse_message_to_mqtt(message) try: _LOGGER.debug('Publishing %s', message.strip()) self._pub_callback(topic, payload, q...
python
def send(self, message): """Publish a command string to the gateway via MQTT.""" if not message: return topic, payload, qos = self._parse_message_to_mqtt(message) try: _LOGGER.debug('Publishing %s', message.strip()) self._pub_callback(topic, payload, q...
[ "def", "send", "(", "self", ",", "message", ")", ":", "if", "not", "message", ":", "return", "topic", ",", "payload", ",", "qos", "=", "self", ".", "_parse_message_to_mqtt", "(", "message", ")", "try", ":", "_LOGGER", ".", "debug", "(", "'Publishing %s'"...
Publish a command string to the gateway via MQTT.
[ "Publish", "a", "command", "string", "to", "the", "gateway", "via", "MQTT", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/gateway_mqtt.py#L140-L149
train
62,574
ambitioninc/django-regex-field
regex_field/fields.py
RegexField.contribute_to_class
def contribute_to_class(self, cls, name, virtual_only=False): """ Cast to the correct value every """ super(RegexField, self).contribute_to_class(cls, name, virtual_only) setattr(cls, name, CastOnAssignDescriptor(self))
python
def contribute_to_class(self, cls, name, virtual_only=False): """ Cast to the correct value every """ super(RegexField, self).contribute_to_class(cls, name, virtual_only) setattr(cls, name, CastOnAssignDescriptor(self))
[ "def", "contribute_to_class", "(", "self", ",", "cls", ",", "name", ",", "virtual_only", "=", "False", ")", ":", "super", "(", "RegexField", ",", "self", ")", ".", "contribute_to_class", "(", "cls", ",", "name", ",", "virtual_only", ")", "setattr", "(", ...
Cast to the correct value every
[ "Cast", "to", "the", "correct", "value", "every" ]
0cf6f5f627002175e40474f75f76128830ae3cdf
https://github.com/ambitioninc/django-regex-field/blob/0cf6f5f627002175e40474f75f76128830ae3cdf/regex_field/fields.py#L60-L65
train
62,575
ambitioninc/django-regex-field
regex_field/fields.py
RegexField.run_validators
def run_validators(self, value): """ Make sure value is a string so it can run through django validators """ value = self.to_python(value) value = self.value_to_string(value) return super(RegexField, self).run_validators(value)
python
def run_validators(self, value): """ Make sure value is a string so it can run through django validators """ value = self.to_python(value) value = self.value_to_string(value) return super(RegexField, self).run_validators(value)
[ "def", "run_validators", "(", "self", ",", "value", ")", ":", "value", "=", "self", ".", "to_python", "(", "value", ")", "value", "=", "self", ".", "value_to_string", "(", "value", ")", "return", "super", "(", "RegexField", ",", "self", ")", ".", "run_...
Make sure value is a string so it can run through django validators
[ "Make", "sure", "value", "is", "a", "string", "so", "it", "can", "run", "through", "django", "validators" ]
0cf6f5f627002175e40474f75f76128830ae3cdf
https://github.com/ambitioninc/django-regex-field/blob/0cf6f5f627002175e40474f75f76128830ae3cdf/regex_field/fields.py#L102-L108
train
62,576
theolind/pymysensors
mysensors/const_15.py
validate_hex
def validate_hex(value): """Validate that value has hex format.""" try: binascii.unhexlify(value) except Exception: raise vol.Invalid( '{} is not of hex format'.format(value)) return value
python
def validate_hex(value): """Validate that value has hex format.""" try: binascii.unhexlify(value) except Exception: raise vol.Invalid( '{} is not of hex format'.format(value)) return value
[ "def", "validate_hex", "(", "value", ")", ":", "try", ":", "binascii", ".", "unhexlify", "(", "value", ")", "except", "Exception", ":", "raise", "vol", ".", "Invalid", "(", "'{} is not of hex format'", ".", "format", "(", "value", ")", ")", "return", "valu...
Validate that value has hex format.
[ "Validate", "that", "value", "has", "hex", "format", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/const_15.py#L261-L268
train
62,577
theolind/pymysensors
mysensors/const_15.py
validate_v_rgb
def validate_v_rgb(value): """Validate a V_RGB value.""" if len(value) != 6: raise vol.Invalid( '{} is not six characters long'.format(value)) return validate_hex(value)
python
def validate_v_rgb(value): """Validate a V_RGB value.""" if len(value) != 6: raise vol.Invalid( '{} is not six characters long'.format(value)) return validate_hex(value)
[ "def", "validate_v_rgb", "(", "value", ")", ":", "if", "len", "(", "value", ")", "!=", "6", ":", "raise", "vol", ".", "Invalid", "(", "'{} is not six characters long'", ".", "format", "(", "value", ")", ")", "return", "validate_hex", "(", "value", ")" ]
Validate a V_RGB value.
[ "Validate", "a", "V_RGB", "value", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/const_15.py#L271-L276
train
62,578
theolind/pymysensors
mysensors/const_15.py
validate_v_rgbw
def validate_v_rgbw(value): """Validate a V_RGBW value.""" if len(value) != 8: raise vol.Invalid( '{} is not eight characters long'.format(value)) return validate_hex(value)
python
def validate_v_rgbw(value): """Validate a V_RGBW value.""" if len(value) != 8: raise vol.Invalid( '{} is not eight characters long'.format(value)) return validate_hex(value)
[ "def", "validate_v_rgbw", "(", "value", ")", ":", "if", "len", "(", "value", ")", "!=", "8", ":", "raise", "vol", ".", "Invalid", "(", "'{} is not eight characters long'", ".", "format", "(", "value", ")", ")", "return", "validate_hex", "(", "value", ")" ]
Validate a V_RGBW value.
[ "Validate", "a", "V_RGBW", "value", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/const_15.py#L279-L284
train
62,579
theolind/pymysensors
mysensors/message.py
Message.copy
def copy(self, **kwargs): """Copy a message, optionally replace attributes with kwargs.""" msg = Message(self.encode(), self.gateway) for key, val in kwargs.items(): setattr(msg, key, val) return msg
python
def copy(self, **kwargs): """Copy a message, optionally replace attributes with kwargs.""" msg = Message(self.encode(), self.gateway) for key, val in kwargs.items(): setattr(msg, key, val) return msg
[ "def", "copy", "(", "self", ",", "*", "*", "kwargs", ")", ":", "msg", "=", "Message", "(", "self", ".", "encode", "(", ")", ",", "self", ".", "gateway", ")", "for", "key", ",", "val", "in", "kwargs", ".", "items", "(", ")", ":", "setattr", "(",...
Copy a message, optionally replace attributes with kwargs.
[ "Copy", "a", "message", "optionally", "replace", "attributes", "with", "kwargs", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/message.py#L34-L39
train
62,580
theolind/pymysensors
mysensors/message.py
Message.modify
def modify(self, **kwargs): """Modify and return message, replace attributes with kwargs.""" for key, val in kwargs.items(): setattr(self, key, val) return self
python
def modify(self, **kwargs): """Modify and return message, replace attributes with kwargs.""" for key, val in kwargs.items(): setattr(self, key, val) return self
[ "def", "modify", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "key", ",", "val", "in", "kwargs", ".", "items", "(", ")", ":", "setattr", "(", "self", ",", "key", ",", "val", ")", "return", "self" ]
Modify and return message, replace attributes with kwargs.
[ "Modify", "and", "return", "message", "replace", "attributes", "with", "kwargs", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/message.py#L41-L45
train
62,581
theolind/pymysensors
mysensors/message.py
Message.decode
def decode(self, data, delimiter=';'): """Decode a message from command string.""" try: list_data = data.rstrip().split(delimiter) self.payload = list_data.pop() (self.node_id, self.child_id, self.type, self.ack, sel...
python
def decode(self, data, delimiter=';'): """Decode a message from command string.""" try: list_data = data.rstrip().split(delimiter) self.payload = list_data.pop() (self.node_id, self.child_id, self.type, self.ack, sel...
[ "def", "decode", "(", "self", ",", "data", ",", "delimiter", "=", "';'", ")", ":", "try", ":", "list_data", "=", "data", ".", "rstrip", "(", ")", ".", "split", "(", "delimiter", ")", "self", ".", "payload", "=", "list_data", ".", "pop", "(", ")", ...
Decode a message from command string.
[ "Decode", "a", "message", "from", "command", "string", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/message.py#L47-L60
train
62,582
theolind/pymysensors
mysensors/message.py
Message.encode
def encode(self, delimiter=';'): """Encode a command string from message.""" try: return delimiter.join([str(f) for f in [ self.node_id, self.child_id, int(self.type), self.ack, int(self.sub_type), ...
python
def encode(self, delimiter=';'): """Encode a command string from message.""" try: return delimiter.join([str(f) for f in [ self.node_id, self.child_id, int(self.type), self.ack, int(self.sub_type), ...
[ "def", "encode", "(", "self", ",", "delimiter", "=", "';'", ")", ":", "try", ":", "return", "delimiter", ".", "join", "(", "[", "str", "(", "f", ")", "for", "f", "in", "[", "self", ".", "node_id", ",", "self", ".", "child_id", ",", "int", "(", ...
Encode a command string from message.
[ "Encode", "a", "command", "string", "from", "message", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/message.py#L62-L74
train
62,583
theolind/pymysensors
mysensors/message.py
Message.validate
def validate(self, protocol_version): """Validate message.""" const = get_const(protocol_version) valid_node_ids = vol.All(vol.Coerce(int), vol.Range( min=0, max=BROADCAST_ID, msg='Not valid node_id: {}'.format( self.node_id))) valid_child_ids = vol.All(vol.Co...
python
def validate(self, protocol_version): """Validate message.""" const = get_const(protocol_version) valid_node_ids = vol.All(vol.Coerce(int), vol.Range( min=0, max=BROADCAST_ID, msg='Not valid node_id: {}'.format( self.node_id))) valid_child_ids = vol.All(vol.Co...
[ "def", "validate", "(", "self", ",", "protocol_version", ")", ":", "const", "=", "get_const", "(", "protocol_version", ")", "valid_node_ids", "=", "vol", ".", "All", "(", "vol", ".", "Coerce", "(", "int", ")", ",", "vol", ".", "Range", "(", "min", "=",...
Validate message.
[ "Validate", "message", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/message.py#L76-L119
train
62,584
theolind/pymysensors
mysensors/persistence.py
Persistence._save_pickle
def _save_pickle(self, filename): """Save sensors to pickle file.""" with open(filename, 'wb') as file_handle: pickle.dump(self._sensors, file_handle, pickle.HIGHEST_PROTOCOL) file_handle.flush() os.fsync(file_handle.fileno())
python
def _save_pickle(self, filename): """Save sensors to pickle file.""" with open(filename, 'wb') as file_handle: pickle.dump(self._sensors, file_handle, pickle.HIGHEST_PROTOCOL) file_handle.flush() os.fsync(file_handle.fileno())
[ "def", "_save_pickle", "(", "self", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'wb'", ")", "as", "file_handle", ":", "pickle", ".", "dump", "(", "self", ".", "_sensors", ",", "file_handle", ",", "pickle", ".", "HIGHEST_PROTOCOL", "...
Save sensors to pickle file.
[ "Save", "sensors", "to", "pickle", "file", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/persistence.py#L25-L30
train
62,585
theolind/pymysensors
mysensors/persistence.py
Persistence._load_pickle
def _load_pickle(self, filename): """Load sensors from pickle file.""" with open(filename, 'rb') as file_handle: self._sensors.update(pickle.load(file_handle))
python
def _load_pickle(self, filename): """Load sensors from pickle file.""" with open(filename, 'rb') as file_handle: self._sensors.update(pickle.load(file_handle))
[ "def", "_load_pickle", "(", "self", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "file_handle", ":", "self", ".", "_sensors", ".", "update", "(", "pickle", ".", "load", "(", "file_handle", ")", ")" ]
Load sensors from pickle file.
[ "Load", "sensors", "from", "pickle", "file", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/persistence.py#L32-L35
train
62,586
theolind/pymysensors
mysensors/persistence.py
Persistence._save_json
def _save_json(self, filename): """Save sensors to json file.""" with open(filename, 'w') as file_handle: json.dump(self._sensors, file_handle, cls=MySensorsJSONEncoder, indent=4) file_handle.flush() os.fsync(file_handle.fileno())
python
def _save_json(self, filename): """Save sensors to json file.""" with open(filename, 'w') as file_handle: json.dump(self._sensors, file_handle, cls=MySensorsJSONEncoder, indent=4) file_handle.flush() os.fsync(file_handle.fileno())
[ "def", "_save_json", "(", "self", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "file_handle", ":", "json", ".", "dump", "(", "self", ".", "_sensors", ",", "file_handle", ",", "cls", "=", "MySensorsJSONEncoder", ",", ...
Save sensors to json file.
[ "Save", "sensors", "to", "json", "file", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/persistence.py#L37-L43
train
62,587
theolind/pymysensors
mysensors/persistence.py
Persistence._load_json
def _load_json(self, filename): """Load sensors from json file.""" with open(filename, 'r') as file_handle: self._sensors.update(json.load( file_handle, cls=MySensorsJSONDecoder))
python
def _load_json(self, filename): """Load sensors from json file.""" with open(filename, 'r') as file_handle: self._sensors.update(json.load( file_handle, cls=MySensorsJSONDecoder))
[ "def", "_load_json", "(", "self", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "file_handle", ":", "self", ".", "_sensors", ".", "update", "(", "json", ".", "load", "(", "file_handle", ",", "cls", "=", "MySensorsJS...
Load sensors from json file.
[ "Load", "sensors", "from", "json", "file", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/persistence.py#L45-L49
train
62,588
theolind/pymysensors
mysensors/persistence.py
Persistence.save_sensors
def save_sensors(self): """Save sensors to file.""" if not self.need_save: return fname = os.path.realpath(self.persistence_file) exists = os.path.isfile(fname) dirname = os.path.dirname(fname) if (not os.access(dirname, os.W_OK) or exists and ...
python
def save_sensors(self): """Save sensors to file.""" if not self.need_save: return fname = os.path.realpath(self.persistence_file) exists = os.path.isfile(fname) dirname = os.path.dirname(fname) if (not os.access(dirname, os.W_OK) or exists and ...
[ "def", "save_sensors", "(", "self", ")", ":", "if", "not", "self", ".", "need_save", ":", "return", "fname", "=", "os", ".", "path", ".", "realpath", "(", "self", ".", "persistence_file", ")", "exists", "=", "os", ".", "path", ".", "isfile", "(", "fn...
Save sensors to file.
[ "Save", "sensors", "to", "file", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/persistence.py#L51-L71
train
62,589
theolind/pymysensors
mysensors/persistence.py
Persistence._load_sensors
def _load_sensors(self, path=None): """Load sensors from file.""" if path is None: path = self.persistence_file exists = os.path.isfile(path) if exists and os.access(path, os.R_OK): if path == self.persistence_bak: os.rename(path, self.persistence_...
python
def _load_sensors(self, path=None): """Load sensors from file.""" if path is None: path = self.persistence_file exists = os.path.isfile(path) if exists and os.access(path, os.R_OK): if path == self.persistence_bak: os.rename(path, self.persistence_...
[ "def", "_load_sensors", "(", "self", ",", "path", "=", "None", ")", ":", "if", "path", "is", "None", ":", "path", "=", "self", ".", "persistence_file", "exists", "=", "os", ".", "path", ".", "isfile", "(", "path", ")", "if", "exists", "and", "os", ...
Load sensors from file.
[ "Load", "sensors", "from", "file", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/persistence.py#L73-L86
train
62,590
theolind/pymysensors
mysensors/persistence.py
Persistence.safe_load_sensors
def safe_load_sensors(self): """Load sensors safely from file.""" try: loaded = self._load_sensors() except (EOFError, ValueError): _LOGGER.error('Bad file contents: %s', self.persistence_file) loaded = False if not loaded: _LOGGER.warning(...
python
def safe_load_sensors(self): """Load sensors safely from file.""" try: loaded = self._load_sensors() except (EOFError, ValueError): _LOGGER.error('Bad file contents: %s', self.persistence_file) loaded = False if not loaded: _LOGGER.warning(...
[ "def", "safe_load_sensors", "(", "self", ")", ":", "try", ":", "loaded", "=", "self", ".", "_load_sensors", "(", ")", "except", "(", "EOFError", ",", "ValueError", ")", ":", "_LOGGER", ".", "error", "(", "'Bad file contents: %s'", ",", "self", ".", "persis...
Load sensors safely from file.
[ "Load", "sensors", "safely", "from", "file", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/persistence.py#L88-L104
train
62,591
theolind/pymysensors
mysensors/persistence.py
Persistence._perform_file_action
def _perform_file_action(self, filename, action): """Perform action on specific file types. Dynamic dispatch function for performing actions on specific file types. """ ext = os.path.splitext(filename)[1] try: func = getattr(self, '_{}_{}'.format(action, ext[...
python
def _perform_file_action(self, filename, action): """Perform action on specific file types. Dynamic dispatch function for performing actions on specific file types. """ ext = os.path.splitext(filename)[1] try: func = getattr(self, '_{}_{}'.format(action, ext[...
[ "def", "_perform_file_action", "(", "self", ",", "filename", ",", "action", ")", ":", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "1", "]", "try", ":", "func", "=", "getattr", "(", "self", ",", "'_{}_{}'", ".", "format"...
Perform action on specific file types. Dynamic dispatch function for performing actions on specific file types.
[ "Perform", "action", "on", "specific", "file", "types", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/persistence.py#L106-L117
train
62,592
theolind/pymysensors
mysensors/persistence.py
MySensorsJSONEncoder.default
def default(self, obj): """Serialize obj into JSON.""" # pylint: disable=method-hidden, protected-access, arguments-differ if isinstance(obj, Sensor): return { 'sensor_id': obj.sensor_id, 'children': obj.children, 'type': obj.type, ...
python
def default(self, obj): """Serialize obj into JSON.""" # pylint: disable=method-hidden, protected-access, arguments-differ if isinstance(obj, Sensor): return { 'sensor_id': obj.sensor_id, 'children': obj.children, 'type': obj.type, ...
[ "def", "default", "(", "self", ",", "obj", ")", ":", "# pylint: disable=method-hidden, protected-access, arguments-differ", "if", "isinstance", "(", "obj", ",", "Sensor", ")", ":", "return", "{", "'sensor_id'", ":", "obj", ".", "sensor_id", ",", "'children'", ":",...
Serialize obj into JSON.
[ "Serialize", "obj", "into", "JSON", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/persistence.py#L123-L144
train
62,593
theolind/pymysensors
mysensors/persistence.py
MySensorsJSONDecoder.dict_to_object
def dict_to_object(self, obj): # pylint: disable=no-self-use """Return object from dict.""" if not isinstance(obj, dict): return obj if 'sensor_id' in obj: sensor = Sensor(obj['sensor_id']) for key, val in obj.items(): setattr(sensor, key, val...
python
def dict_to_object(self, obj): # pylint: disable=no-self-use """Return object from dict.""" if not isinstance(obj, dict): return obj if 'sensor_id' in obj: sensor = Sensor(obj['sensor_id']) for key, val in obj.items(): setattr(sensor, key, val...
[ "def", "dict_to_object", "(", "self", ",", "obj", ")", ":", "# pylint: disable=no-self-use", "if", "not", "isinstance", "(", "obj", ",", "dict", ")", ":", "return", "obj", "if", "'sensor_id'", "in", "obj", ":", "sensor", "=", "Sensor", "(", "obj", "[", "...
Return object from dict.
[ "Return", "object", "from", "dict", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/persistence.py#L154-L170
train
62,594
theolind/pymysensors
mysensors/const.py
get_const
def get_const(protocol_version): """Return the const module for the protocol_version.""" path = next(( CONST_VERSIONS[const_version] for const_version in sorted(CONST_VERSIONS, reverse=True) if parse_ver(protocol_version) >= parse_ver(const_version) ), 'mysensors.const_14') if pa...
python
def get_const(protocol_version): """Return the const module for the protocol_version.""" path = next(( CONST_VERSIONS[const_version] for const_version in sorted(CONST_VERSIONS, reverse=True) if parse_ver(protocol_version) >= parse_ver(const_version) ), 'mysensors.const_14') if pa...
[ "def", "get_const", "(", "protocol_version", ")", ":", "path", "=", "next", "(", "(", "CONST_VERSIONS", "[", "const_version", "]", "for", "const_version", "in", "sorted", "(", "CONST_VERSIONS", ",", "reverse", "=", "True", ")", "if", "parse_ver", "(", "proto...
Return the const module for the protocol_version.
[ "Return", "the", "const", "module", "for", "the", "protocol_version", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/const.py#L19-L30
train
62,595
theolind/pymysensors
mysensors/ota.py
fw_hex_to_int
def fw_hex_to_int(hex_str, words): """Unpack hex string into integers. Use little-endian and unsigned int format. Specify number of words to unpack with argument words. """ return struct.unpack('<{}H'.format(words), binascii.unhexlify(hex_str))
python
def fw_hex_to_int(hex_str, words): """Unpack hex string into integers. Use little-endian and unsigned int format. Specify number of words to unpack with argument words. """ return struct.unpack('<{}H'.format(words), binascii.unhexlify(hex_str))
[ "def", "fw_hex_to_int", "(", "hex_str", ",", "words", ")", ":", "return", "struct", ".", "unpack", "(", "'<{}H'", ".", "format", "(", "words", ")", ",", "binascii", ".", "unhexlify", "(", "hex_str", ")", ")" ]
Unpack hex string into integers. Use little-endian and unsigned int format. Specify number of words to unpack with argument words.
[ "Unpack", "hex", "string", "into", "integers", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/ota.py#L14-L20
train
62,596
theolind/pymysensors
mysensors/ota.py
fw_int_to_hex
def fw_int_to_hex(*args): """Pack integers into hex string. Use little-endian and unsigned int format. """ return binascii.hexlify( struct.pack('<{}H'.format(len(args)), *args)).decode('utf-8')
python
def fw_int_to_hex(*args): """Pack integers into hex string. Use little-endian and unsigned int format. """ return binascii.hexlify( struct.pack('<{}H'.format(len(args)), *args)).decode('utf-8')
[ "def", "fw_int_to_hex", "(", "*", "args", ")", ":", "return", "binascii", ".", "hexlify", "(", "struct", ".", "pack", "(", "'<{}H'", ".", "format", "(", "len", "(", "args", ")", ")", ",", "*", "args", ")", ")", ".", "decode", "(", "'utf-8'", ")" ]
Pack integers into hex string. Use little-endian and unsigned int format.
[ "Pack", "integers", "into", "hex", "string", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/ota.py#L23-L29
train
62,597
theolind/pymysensors
mysensors/ota.py
compute_crc
def compute_crc(data): """Compute CRC16 of data and return an int.""" crc16 = crcmod.predefined.Crc('modbus') crc16.update(data) return int(crc16.hexdigest(), 16)
python
def compute_crc(data): """Compute CRC16 of data and return an int.""" crc16 = crcmod.predefined.Crc('modbus') crc16.update(data) return int(crc16.hexdigest(), 16)
[ "def", "compute_crc", "(", "data", ")", ":", "crc16", "=", "crcmod", ".", "predefined", ".", "Crc", "(", "'modbus'", ")", "crc16", ".", "update", "(", "data", ")", "return", "int", "(", "crc16", ".", "hexdigest", "(", ")", ",", "16", ")" ]
Compute CRC16 of data and return an int.
[ "Compute", "CRC16", "of", "data", "and", "return", "an", "int", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/ota.py#L32-L36
train
62,598
theolind/pymysensors
mysensors/ota.py
load_fw
def load_fw(path): """Open firmware file and return a binary string.""" fname = os.path.realpath(path) exists = os.path.isfile(fname) if not exists or not os.access(fname, os.R_OK): _LOGGER.error( 'Firmware path %s does not exist or is not readable', path) return ...
python
def load_fw(path): """Open firmware file and return a binary string.""" fname = os.path.realpath(path) exists = os.path.isfile(fname) if not exists or not os.access(fname, os.R_OK): _LOGGER.error( 'Firmware path %s does not exist or is not readable', path) return ...
[ "def", "load_fw", "(", "path", ")", ":", "fname", "=", "os", ".", "path", ".", "realpath", "(", "path", ")", "exists", "=", "os", ".", "path", ".", "isfile", "(", "fname", ")", "if", "not", "exists", "or", "not", "os", ".", "access", "(", "fname"...
Open firmware file and return a binary string.
[ "Open", "firmware", "file", "and", "return", "a", "binary", "string", "." ]
a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/ota.py#L39-L56
train
62,599