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
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
mattlong/hermes
hermes/chatroom.py
Chatroom.on_presence
def on_presence(self, session, presence): """Handles presence stanzas""" from_jid = presence.getFrom() is_member = self.is_member(from_jid.getStripped()) if is_member: member = self.get_member(from_jid.getStripped()) else: member = None logger.info('presence: from=%s is_member=%s type=%s' % (from_jid, is_member, presence.getType())) if presence.getType() == 'subscribed': if is_member: logger.info('[%s] accepted their invitation' % (from_jid,)) member['STATUS'] = 'ACTIVE' else: #TODO: user accepted, but is no longer be on the roster, unsubscribe? pass elif presence.getType() == 'subscribe': if is_member: logger.info('Acknowledging subscription request from [%s]' % (from_jid,)) self.client.sendPresence(jid=from_jid, typ='subscribed') member['STATUS'] = 'ACTIVE' self.broadcast('%s has accepted their invitation!' % (from_jid,)) else: #TODO: show that a user has requested membership? pass elif presence.getType() == None: if is_member: member['ONLINE'] += 1 elif presence.getType() == 'unavailable': if is_member: member['ONLINE'] -= 1 else: logger.info('Unhandled presence stanza of type [%s] from [%s]' % (presence.getType(), from_jid))
python
def on_presence(self, session, presence): """Handles presence stanzas""" from_jid = presence.getFrom() is_member = self.is_member(from_jid.getStripped()) if is_member: member = self.get_member(from_jid.getStripped()) else: member = None logger.info('presence: from=%s is_member=%s type=%s' % (from_jid, is_member, presence.getType())) if presence.getType() == 'subscribed': if is_member: logger.info('[%s] accepted their invitation' % (from_jid,)) member['STATUS'] = 'ACTIVE' else: #TODO: user accepted, but is no longer be on the roster, unsubscribe? pass elif presence.getType() == 'subscribe': if is_member: logger.info('Acknowledging subscription request from [%s]' % (from_jid,)) self.client.sendPresence(jid=from_jid, typ='subscribed') member['STATUS'] = 'ACTIVE' self.broadcast('%s has accepted their invitation!' % (from_jid,)) else: #TODO: show that a user has requested membership? pass elif presence.getType() == None: if is_member: member['ONLINE'] += 1 elif presence.getType() == 'unavailable': if is_member: member['ONLINE'] -= 1 else: logger.info('Unhandled presence stanza of type [%s] from [%s]' % (presence.getType(), from_jid))
[ "def", "on_presence", "(", "self", ",", "session", ",", "presence", ")", ":", "from_jid", "=", "presence", ".", "getFrom", "(", ")", "is_member", "=", "self", ".", "is_member", "(", "from_jid", ".", "getStripped", "(", ")", ")", "if", "is_member", ":", "member", "=", "self", ".", "get_member", "(", "from_jid", ".", "getStripped", "(", ")", ")", "else", ":", "member", "=", "None", "logger", ".", "info", "(", "'presence: from=%s is_member=%s type=%s'", "%", "(", "from_jid", ",", "is_member", ",", "presence", ".", "getType", "(", ")", ")", ")", "if", "presence", ".", "getType", "(", ")", "==", "'subscribed'", ":", "if", "is_member", ":", "logger", ".", "info", "(", "'[%s] accepted their invitation'", "%", "(", "from_jid", ",", ")", ")", "member", "[", "'STATUS'", "]", "=", "'ACTIVE'", "else", ":", "#TODO: user accepted, but is no longer be on the roster, unsubscribe?", "pass", "elif", "presence", ".", "getType", "(", ")", "==", "'subscribe'", ":", "if", "is_member", ":", "logger", ".", "info", "(", "'Acknowledging subscription request from [%s]'", "%", "(", "from_jid", ",", ")", ")", "self", ".", "client", ".", "sendPresence", "(", "jid", "=", "from_jid", ",", "typ", "=", "'subscribed'", ")", "member", "[", "'STATUS'", "]", "=", "'ACTIVE'", "self", ".", "broadcast", "(", "'%s has accepted their invitation!'", "%", "(", "from_jid", ",", ")", ")", "else", ":", "#TODO: show that a user has requested membership?", "pass", "elif", "presence", ".", "getType", "(", ")", "==", "None", ":", "if", "is_member", ":", "member", "[", "'ONLINE'", "]", "+=", "1", "elif", "presence", ".", "getType", "(", ")", "==", "'unavailable'", ":", "if", "is_member", ":", "member", "[", "'ONLINE'", "]", "-=", "1", "else", ":", "logger", ".", "info", "(", "'Unhandled presence stanza of type [%s] from [%s]'", "%", "(", "presence", ".", "getType", "(", ")", ",", "from_jid", ")", ")" ]
Handles presence stanzas
[ "Handles", "presence", "stanzas" ]
63a5afcafe90ca99aeb44edeee9ed6f90baae431
https://github.com/mattlong/hermes/blob/63a5afcafe90ca99aeb44edeee9ed6f90baae431/hermes/chatroom.py#L179-L213
train
mattlong/hermes
hermes/chatroom.py
Chatroom.on_message
def on_message(self, con, event): """Handles messge stanzas""" msg_type = event.getType() nick = event.getFrom().getResource() from_jid = event.getFrom().getStripped() body = event.getBody() if msg_type == 'chat' and body is None: return logger.debug('msg_type[%s] from[%s] nick[%s] body[%s]' % (msg_type, from_jid, nick, body,)) sender = filter(lambda m: m['JID'] == from_jid, self.params['MEMBERS']) should_process = msg_type in ['message', 'chat', None] and body is not None and len(sender) == 1 if not should_process: return sender = sender[0] try: for p in self.command_patterns: reg, cmd = p m = reg.match(body) if m: logger.info('pattern matched for bot command \'%s\'' % (cmd,)) function = getattr(self, str(cmd), None) if function: return function(sender, body, m) words = body.split(' ') cmd, args = words[0], words[1:] if cmd and cmd[0] == '/': cmd = cmd[1:] command_handler = getattr(self, 'do_'+cmd, None) if command_handler: return command_handler(sender, body, args) broadcast_body = '[%s] %s' % (sender['NICK'], body,) return self.broadcast(broadcast_body, exclude=(sender,)) except: logger.exception('Error handling message [%s] from [%s]' % (body, sender['JID']))
python
def on_message(self, con, event): """Handles messge stanzas""" msg_type = event.getType() nick = event.getFrom().getResource() from_jid = event.getFrom().getStripped() body = event.getBody() if msg_type == 'chat' and body is None: return logger.debug('msg_type[%s] from[%s] nick[%s] body[%s]' % (msg_type, from_jid, nick, body,)) sender = filter(lambda m: m['JID'] == from_jid, self.params['MEMBERS']) should_process = msg_type in ['message', 'chat', None] and body is not None and len(sender) == 1 if not should_process: return sender = sender[0] try: for p in self.command_patterns: reg, cmd = p m = reg.match(body) if m: logger.info('pattern matched for bot command \'%s\'' % (cmd,)) function = getattr(self, str(cmd), None) if function: return function(sender, body, m) words = body.split(' ') cmd, args = words[0], words[1:] if cmd and cmd[0] == '/': cmd = cmd[1:] command_handler = getattr(self, 'do_'+cmd, None) if command_handler: return command_handler(sender, body, args) broadcast_body = '[%s] %s' % (sender['NICK'], body,) return self.broadcast(broadcast_body, exclude=(sender,)) except: logger.exception('Error handling message [%s] from [%s]' % (body, sender['JID']))
[ "def", "on_message", "(", "self", ",", "con", ",", "event", ")", ":", "msg_type", "=", "event", ".", "getType", "(", ")", "nick", "=", "event", ".", "getFrom", "(", ")", ".", "getResource", "(", ")", "from_jid", "=", "event", ".", "getFrom", "(", ")", ".", "getStripped", "(", ")", "body", "=", "event", ".", "getBody", "(", ")", "if", "msg_type", "==", "'chat'", "and", "body", "is", "None", ":", "return", "logger", ".", "debug", "(", "'msg_type[%s] from[%s] nick[%s] body[%s]'", "%", "(", "msg_type", ",", "from_jid", ",", "nick", ",", "body", ",", ")", ")", "sender", "=", "filter", "(", "lambda", "m", ":", "m", "[", "'JID'", "]", "==", "from_jid", ",", "self", ".", "params", "[", "'MEMBERS'", "]", ")", "should_process", "=", "msg_type", "in", "[", "'message'", ",", "'chat'", ",", "None", "]", "and", "body", "is", "not", "None", "and", "len", "(", "sender", ")", "==", "1", "if", "not", "should_process", ":", "return", "sender", "=", "sender", "[", "0", "]", "try", ":", "for", "p", "in", "self", ".", "command_patterns", ":", "reg", ",", "cmd", "=", "p", "m", "=", "reg", ".", "match", "(", "body", ")", "if", "m", ":", "logger", ".", "info", "(", "'pattern matched for bot command \\'%s\\''", "%", "(", "cmd", ",", ")", ")", "function", "=", "getattr", "(", "self", ",", "str", "(", "cmd", ")", ",", "None", ")", "if", "function", ":", "return", "function", "(", "sender", ",", "body", ",", "m", ")", "words", "=", "body", ".", "split", "(", "' '", ")", "cmd", ",", "args", "=", "words", "[", "0", "]", ",", "words", "[", "1", ":", "]", "if", "cmd", "and", "cmd", "[", "0", "]", "==", "'/'", ":", "cmd", "=", "cmd", "[", "1", ":", "]", "command_handler", "=", "getattr", "(", "self", ",", "'do_'", "+", "cmd", ",", "None", ")", "if", "command_handler", ":", "return", "command_handler", "(", "sender", ",", "body", ",", "args", ")", "broadcast_body", "=", "'[%s] %s'", "%", "(", "sender", "[", "'NICK'", "]", ",", "body", ",", ")", "return", "self", ".", "broadcast", "(", "broadcast_body", ",", "exclude", "=", "(", "sender", ",", ")", ")", "except", ":", "logger", ".", "exception", "(", "'Error handling message [%s] from [%s]'", "%", "(", "body", ",", "sender", "[", "'JID'", "]", ")", ")" ]
Handles messge stanzas
[ "Handles", "messge", "stanzas" ]
63a5afcafe90ca99aeb44edeee9ed6f90baae431
https://github.com/mattlong/hermes/blob/63a5afcafe90ca99aeb44edeee9ed6f90baae431/hermes/chatroom.py#L215-L254
train
cloudmesh-cmd3/cmd3
cmd3/plugins/activate.py
activate.activate
def activate(self): """method to activate all activation methods in the shell and its plugins. """ d = dir(self) self.plugins = [] for key in d: if key.startswith("shell_activate_"): if self.echo: Console.ok("Shell Activate: {0}".format(key)) self.plugins.append(key) for key in d: if key.startswith("activate_"): if self.echo: Console.ok("Activate: {0}".format(key)) self.plugins.append(key) for key in self.plugins: if self.echo: Console.ok("> {0}".format(key.replace("_", " ", 1))) exec ("self.%s()" % key)
python
def activate(self): """method to activate all activation methods in the shell and its plugins. """ d = dir(self) self.plugins = [] for key in d: if key.startswith("shell_activate_"): if self.echo: Console.ok("Shell Activate: {0}".format(key)) self.plugins.append(key) for key in d: if key.startswith("activate_"): if self.echo: Console.ok("Activate: {0}".format(key)) self.plugins.append(key) for key in self.plugins: if self.echo: Console.ok("> {0}".format(key.replace("_", " ", 1))) exec ("self.%s()" % key)
[ "def", "activate", "(", "self", ")", ":", "d", "=", "dir", "(", "self", ")", "self", ".", "plugins", "=", "[", "]", "for", "key", "in", "d", ":", "if", "key", ".", "startswith", "(", "\"shell_activate_\"", ")", ":", "if", "self", ".", "echo", ":", "Console", ".", "ok", "(", "\"Shell Activate: {0}\"", ".", "format", "(", "key", ")", ")", "self", ".", "plugins", ".", "append", "(", "key", ")", "for", "key", "in", "d", ":", "if", "key", ".", "startswith", "(", "\"activate_\"", ")", ":", "if", "self", ".", "echo", ":", "Console", ".", "ok", "(", "\"Activate: {0}\"", ".", "format", "(", "key", ")", ")", "self", ".", "plugins", ".", "append", "(", "key", ")", "for", "key", "in", "self", ".", "plugins", ":", "if", "self", ".", "echo", ":", "Console", ".", "ok", "(", "\"> {0}\"", ".", "format", "(", "key", ".", "replace", "(", "\"_\"", ",", "\" \"", ",", "1", ")", ")", ")", "exec", "(", "\"self.%s()\"", "%", "key", ")" ]
method to activate all activation methods in the shell and its plugins.
[ "method", "to", "activate", "all", "activation", "methods", "in", "the", "shell", "and", "its", "plugins", "." ]
92e33c96032fd3921f159198a0e57917c4dc34ed
https://github.com/cloudmesh-cmd3/cmd3/blob/92e33c96032fd3921f159198a0e57917c4dc34ed/cmd3/plugins/activate.py#L20-L40
train
cloudmesh-cmd3/cmd3
cmd3/plugins/activate.py
activate.do_help
def do_help(self, arg): """List available commands with "help" or detailed help with "help cmd".""" if arg: # XXX check arg syntax try: func = getattr(self, 'help_' + arg) except AttributeError: try: doc = getattr(self, 'do_' + arg).__doc__ if doc: self.stdout.write("%s\n" % str(doc)) return except AttributeError: pass self.stdout.write("%s\n" % str(self.nohelp % (arg,))) return func() else: names = self.get_names() cmds_doc = [] cmds_undoc = [] help_page = {} for name in names: if name[:5] == 'help_': help_page[name[5:]] = 1 names.sort() # There can be duplicates if routines overridden prevname = '' for name in names: if name[:3] == 'do_': if name == prevname: continue prevname = name cmd = name[3:] if cmd in help_page: cmds_doc.append(cmd) del help_page[cmd] elif getattr(self, name).__doc__: cmds_doc.append(cmd) else: cmds_undoc.append(cmd) self.stdout.write("%s\n" % str(self.doc_leader)) self.print_topics(self.doc_header, cmds_doc, 15, 80) self.print_topics(self.misc_header, list(help_page.keys()), 15, 80) self.print_topics(self.undoc_header, cmds_undoc, 15, 80) for topic in self.command_topics: topic_cmds = self.command_topics[topic] self.print_topics(string.capwords(topic + " commands"), topic_cmds, 15, 80)
python
def do_help(self, arg): """List available commands with "help" or detailed help with "help cmd".""" if arg: # XXX check arg syntax try: func = getattr(self, 'help_' + arg) except AttributeError: try: doc = getattr(self, 'do_' + arg).__doc__ if doc: self.stdout.write("%s\n" % str(doc)) return except AttributeError: pass self.stdout.write("%s\n" % str(self.nohelp % (arg,))) return func() else: names = self.get_names() cmds_doc = [] cmds_undoc = [] help_page = {} for name in names: if name[:5] == 'help_': help_page[name[5:]] = 1 names.sort() # There can be duplicates if routines overridden prevname = '' for name in names: if name[:3] == 'do_': if name == prevname: continue prevname = name cmd = name[3:] if cmd in help_page: cmds_doc.append(cmd) del help_page[cmd] elif getattr(self, name).__doc__: cmds_doc.append(cmd) else: cmds_undoc.append(cmd) self.stdout.write("%s\n" % str(self.doc_leader)) self.print_topics(self.doc_header, cmds_doc, 15, 80) self.print_topics(self.misc_header, list(help_page.keys()), 15, 80) self.print_topics(self.undoc_header, cmds_undoc, 15, 80) for topic in self.command_topics: topic_cmds = self.command_topics[topic] self.print_topics(string.capwords(topic + " commands"), topic_cmds, 15, 80)
[ "def", "do_help", "(", "self", ",", "arg", ")", ":", "if", "arg", ":", "# XXX check arg syntax", "try", ":", "func", "=", "getattr", "(", "self", ",", "'help_'", "+", "arg", ")", "except", "AttributeError", ":", "try", ":", "doc", "=", "getattr", "(", "self", ",", "'do_'", "+", "arg", ")", ".", "__doc__", "if", "doc", ":", "self", ".", "stdout", ".", "write", "(", "\"%s\\n\"", "%", "str", "(", "doc", ")", ")", "return", "except", "AttributeError", ":", "pass", "self", ".", "stdout", ".", "write", "(", "\"%s\\n\"", "%", "str", "(", "self", ".", "nohelp", "%", "(", "arg", ",", ")", ")", ")", "return", "func", "(", ")", "else", ":", "names", "=", "self", ".", "get_names", "(", ")", "cmds_doc", "=", "[", "]", "cmds_undoc", "=", "[", "]", "help_page", "=", "{", "}", "for", "name", "in", "names", ":", "if", "name", "[", ":", "5", "]", "==", "'help_'", ":", "help_page", "[", "name", "[", "5", ":", "]", "]", "=", "1", "names", ".", "sort", "(", ")", "# There can be duplicates if routines overridden", "prevname", "=", "''", "for", "name", "in", "names", ":", "if", "name", "[", ":", "3", "]", "==", "'do_'", ":", "if", "name", "==", "prevname", ":", "continue", "prevname", "=", "name", "cmd", "=", "name", "[", "3", ":", "]", "if", "cmd", "in", "help_page", ":", "cmds_doc", ".", "append", "(", "cmd", ")", "del", "help_page", "[", "cmd", "]", "elif", "getattr", "(", "self", ",", "name", ")", ".", "__doc__", ":", "cmds_doc", ".", "append", "(", "cmd", ")", "else", ":", "cmds_undoc", ".", "append", "(", "cmd", ")", "self", ".", "stdout", ".", "write", "(", "\"%s\\n\"", "%", "str", "(", "self", ".", "doc_leader", ")", ")", "self", ".", "print_topics", "(", "self", ".", "doc_header", ",", "cmds_doc", ",", "15", ",", "80", ")", "self", ".", "print_topics", "(", "self", ".", "misc_header", ",", "list", "(", "help_page", ".", "keys", "(", ")", ")", ",", "15", ",", "80", ")", "self", ".", "print_topics", "(", "self", ".", "undoc_header", ",", "cmds_undoc", ",", "15", ",", "80", ")", "for", "topic", "in", "self", ".", "command_topics", ":", "topic_cmds", "=", "self", ".", "command_topics", "[", "topic", "]", "self", ".", "print_topics", "(", "string", ".", "capwords", "(", "topic", "+", "\" commands\"", ")", ",", "topic_cmds", ",", "15", ",", "80", ")" ]
List available commands with "help" or detailed help with "help cmd".
[ "List", "available", "commands", "with", "help", "or", "detailed", "help", "with", "help", "cmd", "." ]
92e33c96032fd3921f159198a0e57917c4dc34ed
https://github.com/cloudmesh-cmd3/cmd3/blob/92e33c96032fd3921f159198a0e57917c4dc34ed/cmd3/plugins/activate.py#L42-L92
train
b10m/ziggo_mediabox_xl
ziggo_mediabox_xl.py
ZiggoMediaboxXL._fetch_channels
def _fetch_channels(self): """Retrieve Ziggo channel information.""" json = requests.get(self._channels_url).json() self._channels = {c['channel']['code']: c['channel']['name'] for c in json['channels']}
python
def _fetch_channels(self): """Retrieve Ziggo channel information.""" json = requests.get(self._channels_url).json() self._channels = {c['channel']['code']: c['channel']['name'] for c in json['channels']}
[ "def", "_fetch_channels", "(", "self", ")", ":", "json", "=", "requests", ".", "get", "(", "self", ".", "_channels_url", ")", ".", "json", "(", ")", "self", ".", "_channels", "=", "{", "c", "[", "'channel'", "]", "[", "'code'", "]", ":", "c", "[", "'channel'", "]", "[", "'name'", "]", "for", "c", "in", "json", "[", "'channels'", "]", "}" ]
Retrieve Ziggo channel information.
[ "Retrieve", "Ziggo", "channel", "information", "." ]
49520ec3e2e3d09339cea667723914b10399249d
https://github.com/b10m/ziggo_mediabox_xl/blob/49520ec3e2e3d09339cea667723914b10399249d/ziggo_mediabox_xl.py#L33-L37
train
b10m/ziggo_mediabox_xl
ziggo_mediabox_xl.py
ZiggoMediaboxXL.send_keys
def send_keys(self, keys): """Send keys to the device.""" try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(self._timeout) sock.connect((self._ip, self._port['cmd'])) # mandatory dance version_info = sock.recv(15) sock.send(version_info) sock.recv(2) sock.send(bytes.fromhex('01')) sock.recv(4) sock.recv(24) # send our command now! for key in keys: if key in self._keys: sock.send(bytes.fromhex("04 01 00 00 00 00 " + self._keys[key])) sock.send(bytes.fromhex("04 00 00 00 00 00 " + self._keys[key])) sock.close() except socket.error: raise
python
def send_keys(self, keys): """Send keys to the device.""" try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(self._timeout) sock.connect((self._ip, self._port['cmd'])) # mandatory dance version_info = sock.recv(15) sock.send(version_info) sock.recv(2) sock.send(bytes.fromhex('01')) sock.recv(4) sock.recv(24) # send our command now! for key in keys: if key in self._keys: sock.send(bytes.fromhex("04 01 00 00 00 00 " + self._keys[key])) sock.send(bytes.fromhex("04 00 00 00 00 00 " + self._keys[key])) sock.close() except socket.error: raise
[ "def", "send_keys", "(", "self", ",", "keys", ")", ":", "try", ":", "sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "sock", ".", "settimeout", "(", "self", ".", "_timeout", ")", "sock", ".", "connect", "(", "(", "self", ".", "_ip", ",", "self", ".", "_port", "[", "'cmd'", "]", ")", ")", "# mandatory dance", "version_info", "=", "sock", ".", "recv", "(", "15", ")", "sock", ".", "send", "(", "version_info", ")", "sock", ".", "recv", "(", "2", ")", "sock", ".", "send", "(", "bytes", ".", "fromhex", "(", "'01'", ")", ")", "sock", ".", "recv", "(", "4", ")", "sock", ".", "recv", "(", "24", ")", "# send our command now!", "for", "key", "in", "keys", ":", "if", "key", "in", "self", ".", "_keys", ":", "sock", ".", "send", "(", "bytes", ".", "fromhex", "(", "\"04 01 00 00 00 00 \"", "+", "self", ".", "_keys", "[", "key", "]", ")", ")", "sock", ".", "send", "(", "bytes", ".", "fromhex", "(", "\"04 00 00 00 00 00 \"", "+", "self", ".", "_keys", "[", "key", "]", ")", ")", "sock", ".", "close", "(", ")", "except", "socket", ".", "error", ":", "raise" ]
Send keys to the device.
[ "Send", "keys", "to", "the", "device", "." ]
49520ec3e2e3d09339cea667723914b10399249d
https://github.com/b10m/ziggo_mediabox_xl/blob/49520ec3e2e3d09339cea667723914b10399249d/ziggo_mediabox_xl.py#L72-L94
train
mbourqui/django-echoices
echoices/fields/fields.py
make_echoicefield
def make_echoicefield(echoices, *args, klass_name=None, **kwargs): """ Construct a subclass of a derived `models.Field` specific to the type of the `EChoice` values. Parameters ---------- echoices : subclass of EChoice args Passed to the derived `models.Field` klass_name : str Give a specific name to the returned class. By default for Django < 1.9, the name will be 'EChoiceField'. By default for Django >= 1.9, the name will be the name of the enum appended with 'Field'. kwargs Passed to the derived `models.Field` Returns ------- EChoiceField For Django>=1.9, the exact name of the returned Field is based on the name of the `echoices` with a suffixed 'Field'. For older Django, the returned name of the class is `EChoiceField`. """ assert issubclass(echoices, EChoice) value_type = echoices.__getvaluetype__() if value_type is str: cls_ = models.CharField elif value_type is int: cls_ = models.IntegerField elif value_type is float: cls_ = models.FloatField elif value_type is bool: cls_ = models.BooleanField else: raise NotImplementedError("Please open an issue if you wish your value type to be supported: " "https://github.com/mbourqui/django-echoices/issues/new") if klass_name and StrictVersion(django_version()) < StrictVersion('1.9.0'): warnings.warn("Django < 1.9 throws an 'ImportError' if the class name is not defined in the module. " "The provided klass_name will be replaced by {}".format(EChoiceField.__name__), RuntimeWarning) klass_name = EChoiceField.__name__ if StrictVersion(django_version()) < StrictVersion('1.9.0') else \ klass_name if klass_name else "{}Field".format(echoices.__name__) d = dict(cls_.__dict__) d.update(dict(EChoiceField.__dict__)) return type(klass_name, (cls_,), d)(echoices, *args, **kwargs)
python
def make_echoicefield(echoices, *args, klass_name=None, **kwargs): """ Construct a subclass of a derived `models.Field` specific to the type of the `EChoice` values. Parameters ---------- echoices : subclass of EChoice args Passed to the derived `models.Field` klass_name : str Give a specific name to the returned class. By default for Django < 1.9, the name will be 'EChoiceField'. By default for Django >= 1.9, the name will be the name of the enum appended with 'Field'. kwargs Passed to the derived `models.Field` Returns ------- EChoiceField For Django>=1.9, the exact name of the returned Field is based on the name of the `echoices` with a suffixed 'Field'. For older Django, the returned name of the class is `EChoiceField`. """ assert issubclass(echoices, EChoice) value_type = echoices.__getvaluetype__() if value_type is str: cls_ = models.CharField elif value_type is int: cls_ = models.IntegerField elif value_type is float: cls_ = models.FloatField elif value_type is bool: cls_ = models.BooleanField else: raise NotImplementedError("Please open an issue if you wish your value type to be supported: " "https://github.com/mbourqui/django-echoices/issues/new") if klass_name and StrictVersion(django_version()) < StrictVersion('1.9.0'): warnings.warn("Django < 1.9 throws an 'ImportError' if the class name is not defined in the module. " "The provided klass_name will be replaced by {}".format(EChoiceField.__name__), RuntimeWarning) klass_name = EChoiceField.__name__ if StrictVersion(django_version()) < StrictVersion('1.9.0') else \ klass_name if klass_name else "{}Field".format(echoices.__name__) d = dict(cls_.__dict__) d.update(dict(EChoiceField.__dict__)) return type(klass_name, (cls_,), d)(echoices, *args, **kwargs)
[ "def", "make_echoicefield", "(", "echoices", ",", "*", "args", ",", "klass_name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "assert", "issubclass", "(", "echoices", ",", "EChoice", ")", "value_type", "=", "echoices", ".", "__getvaluetype__", "(", ")", "if", "value_type", "is", "str", ":", "cls_", "=", "models", ".", "CharField", "elif", "value_type", "is", "int", ":", "cls_", "=", "models", ".", "IntegerField", "elif", "value_type", "is", "float", ":", "cls_", "=", "models", ".", "FloatField", "elif", "value_type", "is", "bool", ":", "cls_", "=", "models", ".", "BooleanField", "else", ":", "raise", "NotImplementedError", "(", "\"Please open an issue if you wish your value type to be supported: \"", "\"https://github.com/mbourqui/django-echoices/issues/new\"", ")", "if", "klass_name", "and", "StrictVersion", "(", "django_version", "(", ")", ")", "<", "StrictVersion", "(", "'1.9.0'", ")", ":", "warnings", ".", "warn", "(", "\"Django < 1.9 throws an 'ImportError' if the class name is not defined in the module. \"", "\"The provided klass_name will be replaced by {}\"", ".", "format", "(", "EChoiceField", ".", "__name__", ")", ",", "RuntimeWarning", ")", "klass_name", "=", "EChoiceField", ".", "__name__", "if", "StrictVersion", "(", "django_version", "(", ")", ")", "<", "StrictVersion", "(", "'1.9.0'", ")", "else", "klass_name", "if", "klass_name", "else", "\"{}Field\"", ".", "format", "(", "echoices", ".", "__name__", ")", "d", "=", "dict", "(", "cls_", ".", "__dict__", ")", "d", ".", "update", "(", "dict", "(", "EChoiceField", ".", "__dict__", ")", ")", "return", "type", "(", "klass_name", ",", "(", "cls_", ",", ")", ",", "d", ")", "(", "echoices", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Construct a subclass of a derived `models.Field` specific to the type of the `EChoice` values. Parameters ---------- echoices : subclass of EChoice args Passed to the derived `models.Field` klass_name : str Give a specific name to the returned class. By default for Django < 1.9, the name will be 'EChoiceField'. By default for Django >= 1.9, the name will be the name of the enum appended with 'Field'. kwargs Passed to the derived `models.Field` Returns ------- EChoiceField For Django>=1.9, the exact name of the returned Field is based on the name of the `echoices` with a suffixed 'Field'. For older Django, the returned name of the class is `EChoiceField`.
[ "Construct", "a", "subclass", "of", "a", "derived", "models", ".", "Field", "specific", "to", "the", "type", "of", "the", "EChoice", "values", "." ]
c57405005ec368ac602bb38a71091a1e03c723bb
https://github.com/mbourqui/django-echoices/blob/c57405005ec368ac602bb38a71091a1e03c723bb/echoices/fields/fields.py#L120-L163
train
jstitch/MambuPy
MambuPy/orm/schema_dummies.py
make_dummy
def make_dummy(instance, relations = {}, datetime_default = dt.strptime('1901-01-01','%Y-%m-%d'), varchar_default = "", integer_default = 0, numeric_default = 0.0, *args, **kwargs ): """Make an instance to look like an empty dummy. Every field of the table is set with zeroes/empty strings. Date fields are set to 01/01/1901. * relations is a dictionary to set properties for relationships on the instance. The keys of the relations dictionary are the name of the fields to be set at the instance. The values of the relations dictionary must be 2 dimension tuples: - first element will be the element to be related. - second element will be the name of the backref set on the previous first element of the tuple, as a list containing the instance. If you wish that no backref to be set you may use any invalid value for a property name, anything other than a string, for example a number. Preferably, use None. * datetime_default is the datetime object to use for init datetime fields. Defaults to 01-01-1901 * varchar_default is the string object to use for init varchar fields. Defaults to "" * integer_default is the int object to use for init integer fields. Defaults to 0 * numeric_default is the float object to use for init numeric fields. Defaults to 0.0 * kwargs may have the name of a certain field you wish to initialize with a value other than the given by the init_data dicionary. If you give an unexistent name on the columns of the table, they are safely ignored. .. todo:: further field types may be set at the init_data dictionary. """ # init_data knows how to put an init value depending on data type init_data = { 'DATETIME' : datetime_default, 'VARCHAR' : varchar_default, 'INTEGER' : integer_default, 'NUMERIC(50, 10)' : numeric_default, 'TEXT' : varchar_default, } # the type of the instance is the SQLAlchemy Table table = type(instance) for col in table.__table__.columns: # declarative base tables have a columns property useful for reflection try: setattr(instance, col.name, kwargs[col.name]) except KeyError: setattr(instance, col.name, init_data[str(col.type)]) for k,v in relations.iteritems(): # set the relationship property with the first element of the tuple setattr(instance, k, v[0]) # try: # # set the relationship backref on the first element of the tuple # # with a property named according to the second element of the # # tuple, pointing to a list with the instance itself (assumes a # # one-to-many relationship) # # in case you don't want a backref, just send a None as v[1] # try: # getattr(v[0], v[1]).append(instance) # except: # setattr(v[0], v[1], [ instance ]) # except: # pass return instance
python
def make_dummy(instance, relations = {}, datetime_default = dt.strptime('1901-01-01','%Y-%m-%d'), varchar_default = "", integer_default = 0, numeric_default = 0.0, *args, **kwargs ): """Make an instance to look like an empty dummy. Every field of the table is set with zeroes/empty strings. Date fields are set to 01/01/1901. * relations is a dictionary to set properties for relationships on the instance. The keys of the relations dictionary are the name of the fields to be set at the instance. The values of the relations dictionary must be 2 dimension tuples: - first element will be the element to be related. - second element will be the name of the backref set on the previous first element of the tuple, as a list containing the instance. If you wish that no backref to be set you may use any invalid value for a property name, anything other than a string, for example a number. Preferably, use None. * datetime_default is the datetime object to use for init datetime fields. Defaults to 01-01-1901 * varchar_default is the string object to use for init varchar fields. Defaults to "" * integer_default is the int object to use for init integer fields. Defaults to 0 * numeric_default is the float object to use for init numeric fields. Defaults to 0.0 * kwargs may have the name of a certain field you wish to initialize with a value other than the given by the init_data dicionary. If you give an unexistent name on the columns of the table, they are safely ignored. .. todo:: further field types may be set at the init_data dictionary. """ # init_data knows how to put an init value depending on data type init_data = { 'DATETIME' : datetime_default, 'VARCHAR' : varchar_default, 'INTEGER' : integer_default, 'NUMERIC(50, 10)' : numeric_default, 'TEXT' : varchar_default, } # the type of the instance is the SQLAlchemy Table table = type(instance) for col in table.__table__.columns: # declarative base tables have a columns property useful for reflection try: setattr(instance, col.name, kwargs[col.name]) except KeyError: setattr(instance, col.name, init_data[str(col.type)]) for k,v in relations.iteritems(): # set the relationship property with the first element of the tuple setattr(instance, k, v[0]) # try: # # set the relationship backref on the first element of the tuple # # with a property named according to the second element of the # # tuple, pointing to a list with the instance itself (assumes a # # one-to-many relationship) # # in case you don't want a backref, just send a None as v[1] # try: # getattr(v[0], v[1]).append(instance) # except: # setattr(v[0], v[1], [ instance ]) # except: # pass return instance
[ "def", "make_dummy", "(", "instance", ",", "relations", "=", "{", "}", ",", "datetime_default", "=", "dt", ".", "strptime", "(", "'1901-01-01'", ",", "'%Y-%m-%d'", ")", ",", "varchar_default", "=", "\"\"", ",", "integer_default", "=", "0", ",", "numeric_default", "=", "0.0", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# init_data knows how to put an init value depending on data type", "init_data", "=", "{", "'DATETIME'", ":", "datetime_default", ",", "'VARCHAR'", ":", "varchar_default", ",", "'INTEGER'", ":", "integer_default", ",", "'NUMERIC(50, 10)'", ":", "numeric_default", ",", "'TEXT'", ":", "varchar_default", ",", "}", "# the type of the instance is the SQLAlchemy Table", "table", "=", "type", "(", "instance", ")", "for", "col", "in", "table", ".", "__table__", ".", "columns", ":", "# declarative base tables have a columns property useful for reflection", "try", ":", "setattr", "(", "instance", ",", "col", ".", "name", ",", "kwargs", "[", "col", ".", "name", "]", ")", "except", "KeyError", ":", "setattr", "(", "instance", ",", "col", ".", "name", ",", "init_data", "[", "str", "(", "col", ".", "type", ")", "]", ")", "for", "k", ",", "v", "in", "relations", ".", "iteritems", "(", ")", ":", "# set the relationship property with the first element of the tuple", "setattr", "(", "instance", ",", "k", ",", "v", "[", "0", "]", ")", "# try:", "# # set the relationship backref on the first element of the tuple", "# # with a property named according to the second element of the", "# # tuple, pointing to a list with the instance itself (assumes a", "# # one-to-many relationship)", "# # in case you don't want a backref, just send a None as v[1]", "# try:", "# getattr(v[0], v[1]).append(instance)", "# except:", "# setattr(v[0], v[1], [ instance ])", "# except:", "# pass", "return", "instance" ]
Make an instance to look like an empty dummy. Every field of the table is set with zeroes/empty strings. Date fields are set to 01/01/1901. * relations is a dictionary to set properties for relationships on the instance. The keys of the relations dictionary are the name of the fields to be set at the instance. The values of the relations dictionary must be 2 dimension tuples: - first element will be the element to be related. - second element will be the name of the backref set on the previous first element of the tuple, as a list containing the instance. If you wish that no backref to be set you may use any invalid value for a property name, anything other than a string, for example a number. Preferably, use None. * datetime_default is the datetime object to use for init datetime fields. Defaults to 01-01-1901 * varchar_default is the string object to use for init varchar fields. Defaults to "" * integer_default is the int object to use for init integer fields. Defaults to 0 * numeric_default is the float object to use for init numeric fields. Defaults to 0.0 * kwargs may have the name of a certain field you wish to initialize with a value other than the given by the init_data dicionary. If you give an unexistent name on the columns of the table, they are safely ignored. .. todo:: further field types may be set at the init_data dictionary.
[ "Make", "an", "instance", "to", "look", "like", "an", "empty", "dummy", "." ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/orm/schema_dummies.py#L14-L99
train
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/model/network.py
Network.set_up_network
def set_up_network( self, genes: List[Gene], gene_filter: bool = False, disease_associations: Optional[Dict] = None ) -> None: """Set up the network. Filter genes out if requested and add attributes to the vertices. :param genes: A list of Gene objects. :param gene_filter: Removes all genes that are not in list <genes> if True. :param disease_associations: Diseases associated with genes. """ if gene_filter: self.filter_genes([gene.entrez_id for gene in genes]) self._add_vertex_attributes(genes, disease_associations) self.print_summary("Graph of all genes")
python
def set_up_network( self, genes: List[Gene], gene_filter: bool = False, disease_associations: Optional[Dict] = None ) -> None: """Set up the network. Filter genes out if requested and add attributes to the vertices. :param genes: A list of Gene objects. :param gene_filter: Removes all genes that are not in list <genes> if True. :param disease_associations: Diseases associated with genes. """ if gene_filter: self.filter_genes([gene.entrez_id for gene in genes]) self._add_vertex_attributes(genes, disease_associations) self.print_summary("Graph of all genes")
[ "def", "set_up_network", "(", "self", ",", "genes", ":", "List", "[", "Gene", "]", ",", "gene_filter", ":", "bool", "=", "False", ",", "disease_associations", ":", "Optional", "[", "Dict", "]", "=", "None", ")", "->", "None", ":", "if", "gene_filter", ":", "self", ".", "filter_genes", "(", "[", "gene", ".", "entrez_id", "for", "gene", "in", "genes", "]", ")", "self", ".", "_add_vertex_attributes", "(", "genes", ",", "disease_associations", ")", "self", ".", "print_summary", "(", "\"Graph of all genes\"", ")" ]
Set up the network. Filter genes out if requested and add attributes to the vertices. :param genes: A list of Gene objects. :param gene_filter: Removes all genes that are not in list <genes> if True. :param disease_associations: Diseases associated with genes.
[ "Set", "up", "the", "network", "." ]
4d7b6713485f2d0a0957e6457edc1b1b5a237460
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/model/network.py#L38-L55
train
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/model/network.py
Network.filter_genes
def filter_genes(self, relevant_entrez: list) -> None: """Filter out the genes that are not in list relevant_entrez. :param list relevant_entrez: Entrez IDs of genes which are to be kept. """ logger.info("In filter_genes()") irrelevant_genes = self.graph.vs.select(name_notin=relevant_entrez) self.graph.delete_vertices(irrelevant_genes)
python
def filter_genes(self, relevant_entrez: list) -> None: """Filter out the genes that are not in list relevant_entrez. :param list relevant_entrez: Entrez IDs of genes which are to be kept. """ logger.info("In filter_genes()") irrelevant_genes = self.graph.vs.select(name_notin=relevant_entrez) self.graph.delete_vertices(irrelevant_genes)
[ "def", "filter_genes", "(", "self", ",", "relevant_entrez", ":", "list", ")", "->", "None", ":", "logger", ".", "info", "(", "\"In filter_genes()\"", ")", "irrelevant_genes", "=", "self", ".", "graph", ".", "vs", ".", "select", "(", "name_notin", "=", "relevant_entrez", ")", "self", ".", "graph", ".", "delete_vertices", "(", "irrelevant_genes", ")" ]
Filter out the genes that are not in list relevant_entrez. :param list relevant_entrez: Entrez IDs of genes which are to be kept.
[ "Filter", "out", "the", "genes", "that", "are", "not", "in", "list", "relevant_entrez", "." ]
4d7b6713485f2d0a0957e6457edc1b1b5a237460
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/model/network.py#L57-L64
train
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/model/network.py
Network._add_vertex_attributes
def _add_vertex_attributes(self, genes: List[Gene], disease_associations: Optional[dict] = None) -> None: """Add attributes to vertices. :param genes: A list of genes containing attribute information. """ self._set_default_vertex_attributes() self._add_vertex_attributes_by_genes(genes) # compute up-regulated and down-regulated genes up_regulated = self.get_upregulated_genes() down_regulated = self.get_downregulated_genes() # set the attributes for up-regulated and down-regulated genes self.graph.vs(up_regulated.indices)["diff_expressed"] = True self.graph.vs(up_regulated.indices)["up_regulated"] = True self.graph.vs(down_regulated.indices)["diff_expressed"] = True self.graph.vs(down_regulated.indices)["down_regulated"] = True # add disease associations self._add_disease_associations(disease_associations) logger.info("Number of all differentially expressed genes is: {}". format(len(up_regulated) + len(down_regulated)))
python
def _add_vertex_attributes(self, genes: List[Gene], disease_associations: Optional[dict] = None) -> None: """Add attributes to vertices. :param genes: A list of genes containing attribute information. """ self._set_default_vertex_attributes() self._add_vertex_attributes_by_genes(genes) # compute up-regulated and down-regulated genes up_regulated = self.get_upregulated_genes() down_regulated = self.get_downregulated_genes() # set the attributes for up-regulated and down-regulated genes self.graph.vs(up_regulated.indices)["diff_expressed"] = True self.graph.vs(up_regulated.indices)["up_regulated"] = True self.graph.vs(down_regulated.indices)["diff_expressed"] = True self.graph.vs(down_regulated.indices)["down_regulated"] = True # add disease associations self._add_disease_associations(disease_associations) logger.info("Number of all differentially expressed genes is: {}". format(len(up_regulated) + len(down_regulated)))
[ "def", "_add_vertex_attributes", "(", "self", ",", "genes", ":", "List", "[", "Gene", "]", ",", "disease_associations", ":", "Optional", "[", "dict", "]", "=", "None", ")", "->", "None", ":", "self", ".", "_set_default_vertex_attributes", "(", ")", "self", ".", "_add_vertex_attributes_by_genes", "(", "genes", ")", "# compute up-regulated and down-regulated genes", "up_regulated", "=", "self", ".", "get_upregulated_genes", "(", ")", "down_regulated", "=", "self", ".", "get_downregulated_genes", "(", ")", "# set the attributes for up-regulated and down-regulated genes", "self", ".", "graph", ".", "vs", "(", "up_regulated", ".", "indices", ")", "[", "\"diff_expressed\"", "]", "=", "True", "self", ".", "graph", ".", "vs", "(", "up_regulated", ".", "indices", ")", "[", "\"up_regulated\"", "]", "=", "True", "self", ".", "graph", ".", "vs", "(", "down_regulated", ".", "indices", ")", "[", "\"diff_expressed\"", "]", "=", "True", "self", ".", "graph", ".", "vs", "(", "down_regulated", ".", "indices", ")", "[", "\"down_regulated\"", "]", "=", "True", "# add disease associations", "self", ".", "_add_disease_associations", "(", "disease_associations", ")", "logger", ".", "info", "(", "\"Number of all differentially expressed genes is: {}\"", ".", "format", "(", "len", "(", "up_regulated", ")", "+", "len", "(", "down_regulated", ")", ")", ")" ]
Add attributes to vertices. :param genes: A list of genes containing attribute information.
[ "Add", "attributes", "to", "vertices", "." ]
4d7b6713485f2d0a0957e6457edc1b1b5a237460
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/model/network.py#L66-L89
train
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/model/network.py
Network._set_default_vertex_attributes
def _set_default_vertex_attributes(self) -> None: """Assign default values on attributes to all vertices.""" self.graph.vs["l2fc"] = 0 self.graph.vs["padj"] = 0.5 self.graph.vs["symbol"] = self.graph.vs["name"] self.graph.vs["diff_expressed"] = False self.graph.vs["up_regulated"] = False self.graph.vs["down_regulated"] = False
python
def _set_default_vertex_attributes(self) -> None: """Assign default values on attributes to all vertices.""" self.graph.vs["l2fc"] = 0 self.graph.vs["padj"] = 0.5 self.graph.vs["symbol"] = self.graph.vs["name"] self.graph.vs["diff_expressed"] = False self.graph.vs["up_regulated"] = False self.graph.vs["down_regulated"] = False
[ "def", "_set_default_vertex_attributes", "(", "self", ")", "->", "None", ":", "self", ".", "graph", ".", "vs", "[", "\"l2fc\"", "]", "=", "0", "self", ".", "graph", ".", "vs", "[", "\"padj\"", "]", "=", "0.5", "self", ".", "graph", ".", "vs", "[", "\"symbol\"", "]", "=", "self", ".", "graph", ".", "vs", "[", "\"name\"", "]", "self", ".", "graph", ".", "vs", "[", "\"diff_expressed\"", "]", "=", "False", "self", ".", "graph", ".", "vs", "[", "\"up_regulated\"", "]", "=", "False", "self", ".", "graph", ".", "vs", "[", "\"down_regulated\"", "]", "=", "False" ]
Assign default values on attributes to all vertices.
[ "Assign", "default", "values", "on", "attributes", "to", "all", "vertices", "." ]
4d7b6713485f2d0a0957e6457edc1b1b5a237460
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/model/network.py#L91-L98
train
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/model/network.py
Network._add_vertex_attributes_by_genes
def _add_vertex_attributes_by_genes(self, genes: List[Gene]) -> None: """Assign values to attributes on vertices. :param genes: A list of Gene objects from which values will be extracted. """ for gene in genes: try: vertex = self.graph.vs.find(name=str(gene.entrez_id)).index self.graph.vs[vertex]['l2fc'] = gene.log2_fold_change self.graph.vs[vertex]['symbol'] = gene.symbol self.graph.vs[vertex]['padj'] = gene.padj except ValueError: pass
python
def _add_vertex_attributes_by_genes(self, genes: List[Gene]) -> None: """Assign values to attributes on vertices. :param genes: A list of Gene objects from which values will be extracted. """ for gene in genes: try: vertex = self.graph.vs.find(name=str(gene.entrez_id)).index self.graph.vs[vertex]['l2fc'] = gene.log2_fold_change self.graph.vs[vertex]['symbol'] = gene.symbol self.graph.vs[vertex]['padj'] = gene.padj except ValueError: pass
[ "def", "_add_vertex_attributes_by_genes", "(", "self", ",", "genes", ":", "List", "[", "Gene", "]", ")", "->", "None", ":", "for", "gene", "in", "genes", ":", "try", ":", "vertex", "=", "self", ".", "graph", ".", "vs", ".", "find", "(", "name", "=", "str", "(", "gene", ".", "entrez_id", ")", ")", ".", "index", "self", ".", "graph", ".", "vs", "[", "vertex", "]", "[", "'l2fc'", "]", "=", "gene", ".", "log2_fold_change", "self", ".", "graph", ".", "vs", "[", "vertex", "]", "[", "'symbol'", "]", "=", "gene", ".", "symbol", "self", ".", "graph", ".", "vs", "[", "vertex", "]", "[", "'padj'", "]", "=", "gene", ".", "padj", "except", "ValueError", ":", "pass" ]
Assign values to attributes on vertices. :param genes: A list of Gene objects from which values will be extracted.
[ "Assign", "values", "to", "attributes", "on", "vertices", "." ]
4d7b6713485f2d0a0957e6457edc1b1b5a237460
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/model/network.py#L100-L112
train
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/model/network.py
Network._add_disease_associations
def _add_disease_associations(self, disease_associations: dict) -> None: """Add disease association annotation to the network. :param disease_associations: Dictionary of disease-gene associations. """ if disease_associations is not None: for target_id, disease_id_list in disease_associations.items(): if target_id in self.graph.vs["name"]: self.graph.vs.find(name=target_id)["associated_diseases"] = disease_id_list
python
def _add_disease_associations(self, disease_associations: dict) -> None: """Add disease association annotation to the network. :param disease_associations: Dictionary of disease-gene associations. """ if disease_associations is not None: for target_id, disease_id_list in disease_associations.items(): if target_id in self.graph.vs["name"]: self.graph.vs.find(name=target_id)["associated_diseases"] = disease_id_list
[ "def", "_add_disease_associations", "(", "self", ",", "disease_associations", ":", "dict", ")", "->", "None", ":", "if", "disease_associations", "is", "not", "None", ":", "for", "target_id", ",", "disease_id_list", "in", "disease_associations", ".", "items", "(", ")", ":", "if", "target_id", "in", "self", ".", "graph", ".", "vs", "[", "\"name\"", "]", ":", "self", ".", "graph", ".", "vs", ".", "find", "(", "name", "=", "target_id", ")", "[", "\"associated_diseases\"", "]", "=", "disease_id_list" ]
Add disease association annotation to the network. :param disease_associations: Dictionary of disease-gene associations.
[ "Add", "disease", "association", "annotation", "to", "the", "network", "." ]
4d7b6713485f2d0a0957e6457edc1b1b5a237460
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/model/network.py#L114-L122
train
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/model/network.py
Network.get_upregulated_genes
def get_upregulated_genes(self) -> VertexSeq: """Get genes that are up-regulated. :return: Up-regulated genes. """ up_regulated = self.graph.vs.select(self._is_upregulated_gene) logger.info(f"No. of up-regulated genes after laying on network: {len(up_regulated)}") return up_regulated
python
def get_upregulated_genes(self) -> VertexSeq: """Get genes that are up-regulated. :return: Up-regulated genes. """ up_regulated = self.graph.vs.select(self._is_upregulated_gene) logger.info(f"No. of up-regulated genes after laying on network: {len(up_regulated)}") return up_regulated
[ "def", "get_upregulated_genes", "(", "self", ")", "->", "VertexSeq", ":", "up_regulated", "=", "self", ".", "graph", ".", "vs", ".", "select", "(", "self", ".", "_is_upregulated_gene", ")", "logger", ".", "info", "(", "f\"No. of up-regulated genes after laying on network: {len(up_regulated)}\"", ")", "return", "up_regulated" ]
Get genes that are up-regulated. :return: Up-regulated genes.
[ "Get", "genes", "that", "are", "up", "-", "regulated", "." ]
4d7b6713485f2d0a0957e6457edc1b1b5a237460
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/model/network.py#L124-L131
train
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/model/network.py
Network.get_downregulated_genes
def get_downregulated_genes(self) -> VertexSeq: """Get genes that are down-regulated. :return: Down-regulated genes. """ down_regulated = self.graph.vs.select(self._is_downregulated_gene) logger.info(f"No. of down-regulated genes after laying on network: {len(down_regulated)}") return down_regulated
python
def get_downregulated_genes(self) -> VertexSeq: """Get genes that are down-regulated. :return: Down-regulated genes. """ down_regulated = self.graph.vs.select(self._is_downregulated_gene) logger.info(f"No. of down-regulated genes after laying on network: {len(down_regulated)}") return down_regulated
[ "def", "get_downregulated_genes", "(", "self", ")", "->", "VertexSeq", ":", "down_regulated", "=", "self", ".", "graph", ".", "vs", ".", "select", "(", "self", ".", "_is_downregulated_gene", ")", "logger", ".", "info", "(", "f\"No. of down-regulated genes after laying on network: {len(down_regulated)}\"", ")", "return", "down_regulated" ]
Get genes that are down-regulated. :return: Down-regulated genes.
[ "Get", "genes", "that", "are", "down", "-", "regulated", "." ]
4d7b6713485f2d0a0957e6457edc1b1b5a237460
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/model/network.py#L133-L140
train
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/model/network.py
Network.print_summary
def print_summary(self, heading: str) -> None: """Print the summary of a graph. :param str heading: Title of the graph. """ logger.info(heading) logger.info("Number of nodes: {}".format(len(self.graph.vs))) logger.info("Number of edges: {}".format(len(self.graph.es)))
python
def print_summary(self, heading: str) -> None: """Print the summary of a graph. :param str heading: Title of the graph. """ logger.info(heading) logger.info("Number of nodes: {}".format(len(self.graph.vs))) logger.info("Number of edges: {}".format(len(self.graph.es)))
[ "def", "print_summary", "(", "self", ",", "heading", ":", "str", ")", "->", "None", ":", "logger", ".", "info", "(", "heading", ")", "logger", ".", "info", "(", "\"Number of nodes: {}\"", ".", "format", "(", "len", "(", "self", ".", "graph", ".", "vs", ")", ")", ")", "logger", ".", "info", "(", "\"Number of edges: {}\"", ".", "format", "(", "len", "(", "self", ".", "graph", ".", "es", ")", ")", ")" ]
Print the summary of a graph. :param str heading: Title of the graph.
[ "Print", "the", "summary", "of", "a", "graph", "." ]
4d7b6713485f2d0a0957e6457edc1b1b5a237460
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/model/network.py#L151-L158
train
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/model/network.py
Network.get_differentially_expressed_genes
def get_differentially_expressed_genes(self, diff_type: str) -> VertexSeq: """Get the differentially expressed genes based on diff_type. :param str diff_type: Differential expression type chosen by the user; all, down, or up. :return list: A list of differentially expressed genes. """ if diff_type == "up": diff_expr = self.graph.vs.select(up_regulated_eq=True) elif diff_type == "down": diff_expr = self.graph.vs.select(down_regulated_eq=True) else: diff_expr = self.graph.vs.select(diff_expressed_eq=True) return diff_expr
python
def get_differentially_expressed_genes(self, diff_type: str) -> VertexSeq: """Get the differentially expressed genes based on diff_type. :param str diff_type: Differential expression type chosen by the user; all, down, or up. :return list: A list of differentially expressed genes. """ if diff_type == "up": diff_expr = self.graph.vs.select(up_regulated_eq=True) elif diff_type == "down": diff_expr = self.graph.vs.select(down_regulated_eq=True) else: diff_expr = self.graph.vs.select(diff_expressed_eq=True) return diff_expr
[ "def", "get_differentially_expressed_genes", "(", "self", ",", "diff_type", ":", "str", ")", "->", "VertexSeq", ":", "if", "diff_type", "==", "\"up\"", ":", "diff_expr", "=", "self", ".", "graph", ".", "vs", ".", "select", "(", "up_regulated_eq", "=", "True", ")", "elif", "diff_type", "==", "\"down\"", ":", "diff_expr", "=", "self", ".", "graph", ".", "vs", ".", "select", "(", "down_regulated_eq", "=", "True", ")", "else", ":", "diff_expr", "=", "self", ".", "graph", ".", "vs", ".", "select", "(", "diff_expressed_eq", "=", "True", ")", "return", "diff_expr" ]
Get the differentially expressed genes based on diff_type. :param str diff_type: Differential expression type chosen by the user; all, down, or up. :return list: A list of differentially expressed genes.
[ "Get", "the", "differentially", "expressed", "genes", "based", "on", "diff_type", "." ]
4d7b6713485f2d0a0957e6457edc1b1b5a237460
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/model/network.py#L160-L172
train
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/model/network.py
Network.write_adj_list
def write_adj_list(self, path: str) -> None: """Write the network as an adjacency list to a file. :param path: File path to write the adjacency list. """ adj_list = self.get_adjlist() with open(path, mode="w") as file: for i, line in enumerate(adj_list): print(i, *line, file=file)
python
def write_adj_list(self, path: str) -> None: """Write the network as an adjacency list to a file. :param path: File path to write the adjacency list. """ adj_list = self.get_adjlist() with open(path, mode="w") as file: for i, line in enumerate(adj_list): print(i, *line, file=file)
[ "def", "write_adj_list", "(", "self", ",", "path", ":", "str", ")", "->", "None", ":", "adj_list", "=", "self", ".", "get_adjlist", "(", ")", "with", "open", "(", "path", ",", "mode", "=", "\"w\"", ")", "as", "file", ":", "for", "i", ",", "line", "in", "enumerate", "(", "adj_list", ")", ":", "print", "(", "i", ",", "*", "line", ",", "file", "=", "file", ")" ]
Write the network as an adjacency list to a file. :param path: File path to write the adjacency list.
[ "Write", "the", "network", "as", "an", "adjacency", "list", "to", "a", "file", "." ]
4d7b6713485f2d0a0957e6457edc1b1b5a237460
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/model/network.py#L174-L183
train
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/model/network.py
Network.get_attribute_from_indices
def get_attribute_from_indices(self, indices: list, attribute_name: str): """Get attribute values for the requested indices. :param indices: Indices of vertices for which the attribute values are requested. :param attribute_name: The name of the attribute. :return: A list of attribute values for the requested indices. """ return list(np.array(self.graph.vs[attribute_name])[indices])
python
def get_attribute_from_indices(self, indices: list, attribute_name: str): """Get attribute values for the requested indices. :param indices: Indices of vertices for which the attribute values are requested. :param attribute_name: The name of the attribute. :return: A list of attribute values for the requested indices. """ return list(np.array(self.graph.vs[attribute_name])[indices])
[ "def", "get_attribute_from_indices", "(", "self", ",", "indices", ":", "list", ",", "attribute_name", ":", "str", ")", ":", "return", "list", "(", "np", ".", "array", "(", "self", ".", "graph", ".", "vs", "[", "attribute_name", "]", ")", "[", "indices", "]", ")" ]
Get attribute values for the requested indices. :param indices: Indices of vertices for which the attribute values are requested. :param attribute_name: The name of the attribute. :return: A list of attribute values for the requested indices.
[ "Get", "attribute", "values", "for", "the", "requested", "indices", "." ]
4d7b6713485f2d0a0957e6457edc1b1b5a237460
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/model/network.py#L192-L199
train
rsgalloway/grit
grit/server/cherrypy/__init__.py
read_headers
def read_headers(rfile, hdict=None): """Read headers from the given stream into the given header dict. If hdict is None, a new header dict is created. Returns the populated header dict. Headers which are repeated are folded together using a comma if their specification so dictates. This function raises ValueError when the read bytes violate the HTTP spec. You should probably return "400 Bad Request" if this happens. """ if hdict is None: hdict = {} while True: line = rfile.readline() if not line: # No more data--illegal end of headers raise ValueError("Illegal end of headers.") if line == CRLF: # Normal end of headers break if not line.endswith(CRLF): raise ValueError("HTTP requires CRLF terminators") if line[0] in ' \t': # It's a continuation line. v = line.strip() else: try: k, v = line.split(":", 1) except ValueError: raise ValueError("Illegal header line.") # TODO: what about TE and WWW-Authenticate? k = k.strip().title() v = v.strip() hname = k if k in comma_separated_headers: existing = hdict.get(hname) if existing: v = ", ".join((existing, v)) hdict[hname] = v return hdict
python
def read_headers(rfile, hdict=None): """Read headers from the given stream into the given header dict. If hdict is None, a new header dict is created. Returns the populated header dict. Headers which are repeated are folded together using a comma if their specification so dictates. This function raises ValueError when the read bytes violate the HTTP spec. You should probably return "400 Bad Request" if this happens. """ if hdict is None: hdict = {} while True: line = rfile.readline() if not line: # No more data--illegal end of headers raise ValueError("Illegal end of headers.") if line == CRLF: # Normal end of headers break if not line.endswith(CRLF): raise ValueError("HTTP requires CRLF terminators") if line[0] in ' \t': # It's a continuation line. v = line.strip() else: try: k, v = line.split(":", 1) except ValueError: raise ValueError("Illegal header line.") # TODO: what about TE and WWW-Authenticate? k = k.strip().title() v = v.strip() hname = k if k in comma_separated_headers: existing = hdict.get(hname) if existing: v = ", ".join((existing, v)) hdict[hname] = v return hdict
[ "def", "read_headers", "(", "rfile", ",", "hdict", "=", "None", ")", ":", "if", "hdict", "is", "None", ":", "hdict", "=", "{", "}", "while", "True", ":", "line", "=", "rfile", ".", "readline", "(", ")", "if", "not", "line", ":", "# No more data--illegal end of headers", "raise", "ValueError", "(", "\"Illegal end of headers.\"", ")", "if", "line", "==", "CRLF", ":", "# Normal end of headers", "break", "if", "not", "line", ".", "endswith", "(", "CRLF", ")", ":", "raise", "ValueError", "(", "\"HTTP requires CRLF terminators\"", ")", "if", "line", "[", "0", "]", "in", "' \\t'", ":", "# It's a continuation line.", "v", "=", "line", ".", "strip", "(", ")", "else", ":", "try", ":", "k", ",", "v", "=", "line", ".", "split", "(", "\":\"", ",", "1", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"Illegal header line.\"", ")", "# TODO: what about TE and WWW-Authenticate?", "k", "=", "k", ".", "strip", "(", ")", ".", "title", "(", ")", "v", "=", "v", ".", "strip", "(", ")", "hname", "=", "k", "if", "k", "in", "comma_separated_headers", ":", "existing", "=", "hdict", ".", "get", "(", "hname", ")", "if", "existing", ":", "v", "=", "\", \"", ".", "join", "(", "(", "existing", ",", "v", ")", ")", "hdict", "[", "hname", "]", "=", "v", "return", "hdict" ]
Read headers from the given stream into the given header dict. If hdict is None, a new header dict is created. Returns the populated header dict. Headers which are repeated are folded together using a comma if their specification so dictates. This function raises ValueError when the read bytes violate the HTTP spec. You should probably return "400 Bad Request" if this happens.
[ "Read", "headers", "from", "the", "given", "stream", "into", "the", "given", "header", "dict", ".", "If", "hdict", "is", "None", "a", "new", "header", "dict", "is", "created", ".", "Returns", "the", "populated", "header", "dict", ".", "Headers", "which", "are", "repeated", "are", "folded", "together", "using", "a", "comma", "if", "their", "specification", "so", "dictates", ".", "This", "function", "raises", "ValueError", "when", "the", "read", "bytes", "violate", "the", "HTTP", "spec", ".", "You", "should", "probably", "return", "400", "Bad", "Request", "if", "this", "happens", "." ]
e6434ad8a1f4ac5d0903ebad630c81f8a5164d78
https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/server/cherrypy/__init__.py#L137-L183
train
rsgalloway/grit
grit/server/cherrypy/__init__.py
HTTPRequest.parse_request
def parse_request(self): """Parse the next HTTP request start-line and message-headers.""" self.rfile = SizeCheckWrapper(self.conn.rfile, self.server.max_request_header_size) try: self.read_request_line() except MaxSizeExceeded: self.simple_response("414 Request-URI Too Long", "The Request-URI sent with the request exceeds the maximum " "allowed bytes.") return try: success = self.read_request_headers() except MaxSizeExceeded: self.simple_response("413 Request Entity Too Large", "The headers sent with the request exceed the maximum " "allowed bytes.") return else: if not success: return self.ready = True
python
def parse_request(self): """Parse the next HTTP request start-line and message-headers.""" self.rfile = SizeCheckWrapper(self.conn.rfile, self.server.max_request_header_size) try: self.read_request_line() except MaxSizeExceeded: self.simple_response("414 Request-URI Too Long", "The Request-URI sent with the request exceeds the maximum " "allowed bytes.") return try: success = self.read_request_headers() except MaxSizeExceeded: self.simple_response("413 Request Entity Too Large", "The headers sent with the request exceed the maximum " "allowed bytes.") return else: if not success: return self.ready = True
[ "def", "parse_request", "(", "self", ")", ":", "self", ".", "rfile", "=", "SizeCheckWrapper", "(", "self", ".", "conn", ".", "rfile", ",", "self", ".", "server", ".", "max_request_header_size", ")", "try", ":", "self", ".", "read_request_line", "(", ")", "except", "MaxSizeExceeded", ":", "self", ".", "simple_response", "(", "\"414 Request-URI Too Long\"", ",", "\"The Request-URI sent with the request exceeds the maximum \"", "\"allowed bytes.\"", ")", "return", "try", ":", "success", "=", "self", ".", "read_request_headers", "(", ")", "except", "MaxSizeExceeded", ":", "self", ".", "simple_response", "(", "\"413 Request Entity Too Large\"", ",", "\"The headers sent with the request exceed the maximum \"", "\"allowed bytes.\"", ")", "return", "else", ":", "if", "not", "success", ":", "return", "self", ".", "ready", "=", "True" ]
Parse the next HTTP request start-line and message-headers.
[ "Parse", "the", "next", "HTTP", "request", "start", "-", "line", "and", "message", "-", "headers", "." ]
e6434ad8a1f4ac5d0903ebad630c81f8a5164d78
https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/server/cherrypy/__init__.py#L513-L536
train
rsgalloway/grit
grit/server/cherrypy/__init__.py
HTTPRequest.send_headers
def send_headers(self): """Assert, process, and send the HTTP response message-headers. You must set self.status, and self.outheaders before calling this. """ hkeys = [key.lower() for key, value in self.outheaders] status = int(self.status[:3]) if status == 413: # Request Entity Too Large. Close conn to avoid garbage. self.close_connection = True elif "content-length" not in hkeys: # "All 1xx (informational), 204 (no content), # and 304 (not modified) responses MUST NOT # include a message-body." So no point chunking. if status < 200 or status in (204, 205, 304): pass else: if (self.response_protocol == 'HTTP/1.1' and self.method != 'HEAD'): # Use the chunked transfer-coding self.chunked_write = True self.outheaders.append(("Transfer-Encoding", "chunked")) else: # Closing the conn is the only way to determine len. self.close_connection = True if "connection" not in hkeys: if self.response_protocol == 'HTTP/1.1': # Both server and client are HTTP/1.1 or better if self.close_connection: self.outheaders.append(("Connection", "close")) else: # Server and/or client are HTTP/1.0 if not self.close_connection: self.outheaders.append(("Connection", "Keep-Alive")) if (not self.close_connection) and (not self.chunked_read): # Read any remaining request body data on the socket. # "If an origin server receives a request that does not include an # Expect request-header field with the "100-continue" expectation, # the request includes a request body, and the server responds # with a final status code before reading the entire request body # from the transport connection, then the server SHOULD NOT close # the transport connection until it has read the entire request, # or until the client closes the connection. Otherwise, the client # might not reliably receive the response message. However, this # requirement is not be construed as preventing a server from # defending itself against denial-of-service attacks, or from # badly broken client implementations." remaining = getattr(self.rfile, 'remaining', 0) if remaining > 0: self.rfile.read(remaining) if "date" not in hkeys: self.outheaders.append(("Date", rfc822.formatdate())) if "server" not in hkeys: self.outheaders.append(("Server", self.server.server_name)) buf = [self.server.protocol + " " + self.status + CRLF] for k, v in self.outheaders: buf.append(k + ": " + v + CRLF) buf.append(CRLF) self.conn.wfile.sendall("".join(buf))
python
def send_headers(self): """Assert, process, and send the HTTP response message-headers. You must set self.status, and self.outheaders before calling this. """ hkeys = [key.lower() for key, value in self.outheaders] status = int(self.status[:3]) if status == 413: # Request Entity Too Large. Close conn to avoid garbage. self.close_connection = True elif "content-length" not in hkeys: # "All 1xx (informational), 204 (no content), # and 304 (not modified) responses MUST NOT # include a message-body." So no point chunking. if status < 200 or status in (204, 205, 304): pass else: if (self.response_protocol == 'HTTP/1.1' and self.method != 'HEAD'): # Use the chunked transfer-coding self.chunked_write = True self.outheaders.append(("Transfer-Encoding", "chunked")) else: # Closing the conn is the only way to determine len. self.close_connection = True if "connection" not in hkeys: if self.response_protocol == 'HTTP/1.1': # Both server and client are HTTP/1.1 or better if self.close_connection: self.outheaders.append(("Connection", "close")) else: # Server and/or client are HTTP/1.0 if not self.close_connection: self.outheaders.append(("Connection", "Keep-Alive")) if (not self.close_connection) and (not self.chunked_read): # Read any remaining request body data on the socket. # "If an origin server receives a request that does not include an # Expect request-header field with the "100-continue" expectation, # the request includes a request body, and the server responds # with a final status code before reading the entire request body # from the transport connection, then the server SHOULD NOT close # the transport connection until it has read the entire request, # or until the client closes the connection. Otherwise, the client # might not reliably receive the response message. However, this # requirement is not be construed as preventing a server from # defending itself against denial-of-service attacks, or from # badly broken client implementations." remaining = getattr(self.rfile, 'remaining', 0) if remaining > 0: self.rfile.read(remaining) if "date" not in hkeys: self.outheaders.append(("Date", rfc822.formatdate())) if "server" not in hkeys: self.outheaders.append(("Server", self.server.server_name)) buf = [self.server.protocol + " " + self.status + CRLF] for k, v in self.outheaders: buf.append(k + ": " + v + CRLF) buf.append(CRLF) self.conn.wfile.sendall("".join(buf))
[ "def", "send_headers", "(", "self", ")", ":", "hkeys", "=", "[", "key", ".", "lower", "(", ")", "for", "key", ",", "value", "in", "self", ".", "outheaders", "]", "status", "=", "int", "(", "self", ".", "status", "[", ":", "3", "]", ")", "if", "status", "==", "413", ":", "# Request Entity Too Large. Close conn to avoid garbage.", "self", ".", "close_connection", "=", "True", "elif", "\"content-length\"", "not", "in", "hkeys", ":", "# \"All 1xx (informational), 204 (no content),", "# and 304 (not modified) responses MUST NOT", "# include a message-body.\" So no point chunking.", "if", "status", "<", "200", "or", "status", "in", "(", "204", ",", "205", ",", "304", ")", ":", "pass", "else", ":", "if", "(", "self", ".", "response_protocol", "==", "'HTTP/1.1'", "and", "self", ".", "method", "!=", "'HEAD'", ")", ":", "# Use the chunked transfer-coding", "self", ".", "chunked_write", "=", "True", "self", ".", "outheaders", ".", "append", "(", "(", "\"Transfer-Encoding\"", ",", "\"chunked\"", ")", ")", "else", ":", "# Closing the conn is the only way to determine len.", "self", ".", "close_connection", "=", "True", "if", "\"connection\"", "not", "in", "hkeys", ":", "if", "self", ".", "response_protocol", "==", "'HTTP/1.1'", ":", "# Both server and client are HTTP/1.1 or better", "if", "self", ".", "close_connection", ":", "self", ".", "outheaders", ".", "append", "(", "(", "\"Connection\"", ",", "\"close\"", ")", ")", "else", ":", "# Server and/or client are HTTP/1.0", "if", "not", "self", ".", "close_connection", ":", "self", ".", "outheaders", ".", "append", "(", "(", "\"Connection\"", ",", "\"Keep-Alive\"", ")", ")", "if", "(", "not", "self", ".", "close_connection", ")", "and", "(", "not", "self", ".", "chunked_read", ")", ":", "# Read any remaining request body data on the socket.", "# \"If an origin server receives a request that does not include an", "# Expect request-header field with the \"100-continue\" expectation,", "# the request includes a request body, and the server responds", "# with a final status code before reading the entire request body", "# from the transport connection, then the server SHOULD NOT close", "# the transport connection until it has read the entire request,", "# or until the client closes the connection. Otherwise, the client", "# might not reliably receive the response message. However, this", "# requirement is not be construed as preventing a server from", "# defending itself against denial-of-service attacks, or from", "# badly broken client implementations.\"", "remaining", "=", "getattr", "(", "self", ".", "rfile", ",", "'remaining'", ",", "0", ")", "if", "remaining", ">", "0", ":", "self", ".", "rfile", ".", "read", "(", "remaining", ")", "if", "\"date\"", "not", "in", "hkeys", ":", "self", ".", "outheaders", ".", "append", "(", "(", "\"Date\"", ",", "rfc822", ".", "formatdate", "(", ")", ")", ")", "if", "\"server\"", "not", "in", "hkeys", ":", "self", ".", "outheaders", ".", "append", "(", "(", "\"Server\"", ",", "self", ".", "server", ".", "server_name", ")", ")", "buf", "=", "[", "self", ".", "server", ".", "protocol", "+", "\" \"", "+", "self", ".", "status", "+", "CRLF", "]", "for", "k", ",", "v", "in", "self", ".", "outheaders", ":", "buf", ".", "append", "(", "k", "+", "\": \"", "+", "v", "+", "CRLF", ")", "buf", ".", "append", "(", "CRLF", ")", "self", ".", "conn", ".", "wfile", ".", "sendall", "(", "\"\"", ".", "join", "(", "buf", ")", ")" ]
Assert, process, and send the HTTP response message-headers. You must set self.status, and self.outheaders before calling this.
[ "Assert", "process", "and", "send", "the", "HTTP", "response", "message", "-", "headers", ".", "You", "must", "set", "self", ".", "status", "and", "self", ".", "outheaders", "before", "calling", "this", "." ]
e6434ad8a1f4ac5d0903ebad630c81f8a5164d78
https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/server/cherrypy/__init__.py#L811-L875
train
rsgalloway/grit
grit/server/cherrypy/__init__.py
ThreadPool.start
def start(self): """Start the pool of threads.""" for i in range(self.min): self._threads.append(WorkerThread(self.server)) for worker in self._threads: worker.setName("CP Server " + worker.getName()) worker.start() for worker in self._threads: while not worker.ready: time.sleep(.1)
python
def start(self): """Start the pool of threads.""" for i in range(self.min): self._threads.append(WorkerThread(self.server)) for worker in self._threads: worker.setName("CP Server " + worker.getName()) worker.start() for worker in self._threads: while not worker.ready: time.sleep(.1)
[ "def", "start", "(", "self", ")", ":", "for", "i", "in", "range", "(", "self", ".", "min", ")", ":", "self", ".", "_threads", ".", "append", "(", "WorkerThread", "(", "self", ".", "server", ")", ")", "for", "worker", "in", "self", ".", "_threads", ":", "worker", ".", "setName", "(", "\"CP Server \"", "+", "worker", ".", "getName", "(", ")", ")", "worker", ".", "start", "(", ")", "for", "worker", "in", "self", ".", "_threads", ":", "while", "not", "worker", ".", "ready", ":", "time", ".", "sleep", "(", ".1", ")" ]
Start the pool of threads.
[ "Start", "the", "pool", "of", "threads", "." ]
e6434ad8a1f4ac5d0903ebad630c81f8a5164d78
https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/server/cherrypy/__init__.py#L1397-L1406
train
openvax/varlens
varlens/read_evidence/pileup_element.py
PileupElement.fields
def fields(self): ''' Fields that should be considered for our notion of object equality. ''' return ( self.locus, self.offset_start, self.offset_end, self.alignment_key)
python
def fields(self): ''' Fields that should be considered for our notion of object equality. ''' return ( self.locus, self.offset_start, self.offset_end, self.alignment_key)
[ "def", "fields", "(", "self", ")", ":", "return", "(", "self", ".", "locus", ",", "self", ".", "offset_start", ",", "self", ".", "offset_end", ",", "self", ".", "alignment_key", ")" ]
Fields that should be considered for our notion of object equality.
[ "Fields", "that", "should", "be", "considered", "for", "our", "notion", "of", "object", "equality", "." ]
715d3ede5893757b2fcba4117515621bca7b1e5d
https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup_element.py#L57-L62
train
openvax/varlens
varlens/read_evidence/pileup_element.py
PileupElement.bases
def bases(self): ''' The sequenced bases in the alignment that align to this locus in the genome, as a string. Empty string in the case of a deletion. String of length > 1 if there is an insertion here. ''' sequence = self.alignment.query_sequence assert self.offset_end <= len(sequence), \ "End offset=%d > sequence length=%d. CIGAR=%s. SEQUENCE=%s" % ( self.offset_end, len(sequence), self.alignment.cigarstring, sequence) return sequence[self.offset_start:self.offset_end]
python
def bases(self): ''' The sequenced bases in the alignment that align to this locus in the genome, as a string. Empty string in the case of a deletion. String of length > 1 if there is an insertion here. ''' sequence = self.alignment.query_sequence assert self.offset_end <= len(sequence), \ "End offset=%d > sequence length=%d. CIGAR=%s. SEQUENCE=%s" % ( self.offset_end, len(sequence), self.alignment.cigarstring, sequence) return sequence[self.offset_start:self.offset_end]
[ "def", "bases", "(", "self", ")", ":", "sequence", "=", "self", ".", "alignment", ".", "query_sequence", "assert", "self", ".", "offset_end", "<=", "len", "(", "sequence", ")", ",", "\"End offset=%d > sequence length=%d. CIGAR=%s. SEQUENCE=%s\"", "%", "(", "self", ".", "offset_end", ",", "len", "(", "sequence", ")", ",", "self", ".", "alignment", ".", "cigarstring", ",", "sequence", ")", "return", "sequence", "[", "self", ".", "offset_start", ":", "self", ".", "offset_end", "]" ]
The sequenced bases in the alignment that align to this locus in the genome, as a string. Empty string in the case of a deletion. String of length > 1 if there is an insertion here.
[ "The", "sequenced", "bases", "in", "the", "alignment", "that", "align", "to", "this", "locus", "in", "the", "genome", "as", "a", "string", "." ]
715d3ede5893757b2fcba4117515621bca7b1e5d
https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup_element.py#L71-L86
train
openvax/varlens
varlens/read_evidence/pileup_element.py
PileupElement.min_base_quality
def min_base_quality(self): ''' The minimum of the base qualities. In the case of a deletion, in which case there are no bases in this PileupElement, the minimum is taken over the sequenced bases immediately before and after the deletion. ''' try: return min(self.base_qualities) except ValueError: # We are mid-deletion. We return the minimum of the adjacent bases. assert self.offset_start == self.offset_end adjacent_qualities = [ self.alignment.query_qualities[offset] for offset in [self.offset_start - 1, self.offset_start] if 0 <= offset < len(self.alignment.query_qualities) ] return min(adjacent_qualities)
python
def min_base_quality(self): ''' The minimum of the base qualities. In the case of a deletion, in which case there are no bases in this PileupElement, the minimum is taken over the sequenced bases immediately before and after the deletion. ''' try: return min(self.base_qualities) except ValueError: # We are mid-deletion. We return the minimum of the adjacent bases. assert self.offset_start == self.offset_end adjacent_qualities = [ self.alignment.query_qualities[offset] for offset in [self.offset_start - 1, self.offset_start] if 0 <= offset < len(self.alignment.query_qualities) ] return min(adjacent_qualities)
[ "def", "min_base_quality", "(", "self", ")", ":", "try", ":", "return", "min", "(", "self", ".", "base_qualities", ")", "except", "ValueError", ":", "# We are mid-deletion. We return the minimum of the adjacent bases.", "assert", "self", ".", "offset_start", "==", "self", ".", "offset_end", "adjacent_qualities", "=", "[", "self", ".", "alignment", ".", "query_qualities", "[", "offset", "]", "for", "offset", "in", "[", "self", ".", "offset_start", "-", "1", ",", "self", ".", "offset_start", "]", "if", "0", "<=", "offset", "<", "len", "(", "self", ".", "alignment", ".", "query_qualities", ")", "]", "return", "min", "(", "adjacent_qualities", ")" ]
The minimum of the base qualities. In the case of a deletion, in which case there are no bases in this PileupElement, the minimum is taken over the sequenced bases immediately before and after the deletion.
[ "The", "minimum", "of", "the", "base", "qualities", ".", "In", "the", "case", "of", "a", "deletion", "in", "which", "case", "there", "are", "no", "bases", "in", "this", "PileupElement", "the", "minimum", "is", "taken", "over", "the", "sequenced", "bases", "immediately", "before", "and", "after", "the", "deletion", "." ]
715d3ede5893757b2fcba4117515621bca7b1e5d
https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup_element.py#L98-L114
train
openvax/varlens
varlens/read_evidence/pileup_element.py
PileupElement.from_pysam_alignment
def from_pysam_alignment(locus, pileup_read): ''' Factory function to create a new PileupElement from a pysam `PileupRead`. Parameters ---------- locus : varcode.Locus Reference locus for which to construct a PileupElement. Must include exactly one base. pileup_read : pysam.calignmentfile.PileupRead pysam PileupRead instance. Its alignment must overlap the locus. Returns ---------- PileupElement ''' assert not pileup_read.is_refskip, ( "Can't create a PileupElement in a refskip (typically an intronic " "gap in an RNA alignment)") # Pysam has an `aligned_pairs` method that gives a list of # (offset, locus) pairs indicating the correspondence between bases in # the alignment and reference loci. Here we use that to compute # offset_start and offset_end. # # This is slightly tricky in the case of insertions and deletions. # Here are examples of the desired logic. # # Target locus = 1000 # # (1) Simple case: matching bases. # # OFFSET LOCUS # 0 999 # 1 1000 # 2 1001 # # DESIRED RESULT: offset_start=1, offset_end=2. # # # (2) A 1 base insertion at offset 2. # # OFFSET LOCUS # 0 999 # 1 1000 # 2 None # 3 1001 # # DESIRED RESULT: offset_start = 1, offset_end=3. # # # (3) A 2 base deletion at loci 1000 and 1001. # # OFFSET LOCUS # 0 999 # None 1000 # None 1001 # 1 1002 # # DESIRED RESULT: offset_start = 1, offset_end=1. # offset_start = None offset_end = len(pileup_read.alignment.query_sequence) # TODO: doing this with get_blocks() may be faster. for (offset, position) in pileup_read.alignment.aligned_pairs: if offset is not None and position is not None: if position == locus.position: offset_start = offset elif position > locus.position: offset_end = offset break if offset_start is None: offset_start = offset_end assert pileup_read.is_del == (offset_end - offset_start == 0), \ "Deletion=%s but | [%d,%d) |=%d for locus %d in: \n%s" % ( pileup_read.is_del, offset_start, offset_end, offset_end - offset_start, locus.position, pileup_read.alignment.aligned_pairs) assert offset_end >= offset_start result = PileupElement( locus, offset_start, offset_end, pileup_read.alignment) return result
python
def from_pysam_alignment(locus, pileup_read): ''' Factory function to create a new PileupElement from a pysam `PileupRead`. Parameters ---------- locus : varcode.Locus Reference locus for which to construct a PileupElement. Must include exactly one base. pileup_read : pysam.calignmentfile.PileupRead pysam PileupRead instance. Its alignment must overlap the locus. Returns ---------- PileupElement ''' assert not pileup_read.is_refskip, ( "Can't create a PileupElement in a refskip (typically an intronic " "gap in an RNA alignment)") # Pysam has an `aligned_pairs` method that gives a list of # (offset, locus) pairs indicating the correspondence between bases in # the alignment and reference loci. Here we use that to compute # offset_start and offset_end. # # This is slightly tricky in the case of insertions and deletions. # Here are examples of the desired logic. # # Target locus = 1000 # # (1) Simple case: matching bases. # # OFFSET LOCUS # 0 999 # 1 1000 # 2 1001 # # DESIRED RESULT: offset_start=1, offset_end=2. # # # (2) A 1 base insertion at offset 2. # # OFFSET LOCUS # 0 999 # 1 1000 # 2 None # 3 1001 # # DESIRED RESULT: offset_start = 1, offset_end=3. # # # (3) A 2 base deletion at loci 1000 and 1001. # # OFFSET LOCUS # 0 999 # None 1000 # None 1001 # 1 1002 # # DESIRED RESULT: offset_start = 1, offset_end=1. # offset_start = None offset_end = len(pileup_read.alignment.query_sequence) # TODO: doing this with get_blocks() may be faster. for (offset, position) in pileup_read.alignment.aligned_pairs: if offset is not None and position is not None: if position == locus.position: offset_start = offset elif position > locus.position: offset_end = offset break if offset_start is None: offset_start = offset_end assert pileup_read.is_del == (offset_end - offset_start == 0), \ "Deletion=%s but | [%d,%d) |=%d for locus %d in: \n%s" % ( pileup_read.is_del, offset_start, offset_end, offset_end - offset_start, locus.position, pileup_read.alignment.aligned_pairs) assert offset_end >= offset_start result = PileupElement( locus, offset_start, offset_end, pileup_read.alignment) return result
[ "def", "from_pysam_alignment", "(", "locus", ",", "pileup_read", ")", ":", "assert", "not", "pileup_read", ".", "is_refskip", ",", "(", "\"Can't create a PileupElement in a refskip (typically an intronic \"", "\"gap in an RNA alignment)\"", ")", "# Pysam has an `aligned_pairs` method that gives a list of", "# (offset, locus) pairs indicating the correspondence between bases in", "# the alignment and reference loci. Here we use that to compute", "# offset_start and offset_end.", "#", "# This is slightly tricky in the case of insertions and deletions.", "# Here are examples of the desired logic.", "#", "# Target locus = 1000", "#", "# (1) Simple case: matching bases.", "#", "# OFFSET LOCUS", "# 0 999", "# 1 1000", "# 2 1001", "#", "# DESIRED RESULT: offset_start=1, offset_end=2.", "#", "#", "# (2) A 1 base insertion at offset 2.", "#", "# OFFSET LOCUS", "# 0 999", "# 1 1000", "# 2 None", "# 3 1001", "#", "# DESIRED RESULT: offset_start = 1, offset_end=3.", "#", "#", "# (3) A 2 base deletion at loci 1000 and 1001.", "#", "# OFFSET LOCUS", "# 0 999", "# None 1000", "# None 1001", "# 1 1002", "#", "# DESIRED RESULT: offset_start = 1, offset_end=1.", "#", "offset_start", "=", "None", "offset_end", "=", "len", "(", "pileup_read", ".", "alignment", ".", "query_sequence", ")", "# TODO: doing this with get_blocks() may be faster.", "for", "(", "offset", ",", "position", ")", "in", "pileup_read", ".", "alignment", ".", "aligned_pairs", ":", "if", "offset", "is", "not", "None", "and", "position", "is", "not", "None", ":", "if", "position", "==", "locus", ".", "position", ":", "offset_start", "=", "offset", "elif", "position", ">", "locus", ".", "position", ":", "offset_end", "=", "offset", "break", "if", "offset_start", "is", "None", ":", "offset_start", "=", "offset_end", "assert", "pileup_read", ".", "is_del", "==", "(", "offset_end", "-", "offset_start", "==", "0", ")", ",", "\"Deletion=%s but | [%d,%d) |=%d for locus %d in: \\n%s\"", "%", "(", "pileup_read", ".", "is_del", ",", "offset_start", ",", "offset_end", ",", "offset_end", "-", "offset_start", ",", "locus", ".", "position", ",", "pileup_read", ".", "alignment", ".", "aligned_pairs", ")", "assert", "offset_end", ">=", "offset_start", "result", "=", "PileupElement", "(", "locus", ",", "offset_start", ",", "offset_end", ",", "pileup_read", ".", "alignment", ")", "return", "result" ]
Factory function to create a new PileupElement from a pysam `PileupRead`. Parameters ---------- locus : varcode.Locus Reference locus for which to construct a PileupElement. Must include exactly one base. pileup_read : pysam.calignmentfile.PileupRead pysam PileupRead instance. Its alignment must overlap the locus. Returns ---------- PileupElement
[ "Factory", "function", "to", "create", "a", "new", "PileupElement", "from", "a", "pysam", "PileupRead", "." ]
715d3ede5893757b2fcba4117515621bca7b1e5d
https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup_element.py#L117-L206
train
polyaxon/hestia
hestia/http.py
safe_request
def safe_request( url, method=None, params=None, data=None, json=None, headers=None, allow_redirects=False, timeout=30, verify_ssl=True, ): """A slightly safer version of `request`.""" session = requests.Session() kwargs = {} if json: kwargs['json'] = json if not headers: headers = {} headers.setdefault('Content-Type', 'application/json') if data: kwargs['data'] = data if params: kwargs['params'] = params if headers: kwargs['headers'] = headers if method is None: method = 'POST' if (data or json) else 'GET' response = session.request( method=method, url=url, allow_redirects=allow_redirects, timeout=timeout, verify=verify_ssl, **kwargs ) return response
python
def safe_request( url, method=None, params=None, data=None, json=None, headers=None, allow_redirects=False, timeout=30, verify_ssl=True, ): """A slightly safer version of `request`.""" session = requests.Session() kwargs = {} if json: kwargs['json'] = json if not headers: headers = {} headers.setdefault('Content-Type', 'application/json') if data: kwargs['data'] = data if params: kwargs['params'] = params if headers: kwargs['headers'] = headers if method is None: method = 'POST' if (data or json) else 'GET' response = session.request( method=method, url=url, allow_redirects=allow_redirects, timeout=timeout, verify=verify_ssl, **kwargs ) return response
[ "def", "safe_request", "(", "url", ",", "method", "=", "None", ",", "params", "=", "None", ",", "data", "=", "None", ",", "json", "=", "None", ",", "headers", "=", "None", ",", "allow_redirects", "=", "False", ",", "timeout", "=", "30", ",", "verify_ssl", "=", "True", ",", ")", ":", "session", "=", "requests", ".", "Session", "(", ")", "kwargs", "=", "{", "}", "if", "json", ":", "kwargs", "[", "'json'", "]", "=", "json", "if", "not", "headers", ":", "headers", "=", "{", "}", "headers", ".", "setdefault", "(", "'Content-Type'", ",", "'application/json'", ")", "if", "data", ":", "kwargs", "[", "'data'", "]", "=", "data", "if", "params", ":", "kwargs", "[", "'params'", "]", "=", "params", "if", "headers", ":", "kwargs", "[", "'headers'", "]", "=", "headers", "if", "method", "is", "None", ":", "method", "=", "'POST'", "if", "(", "data", "or", "json", ")", "else", "'GET'", "response", "=", "session", ".", "request", "(", "method", "=", "method", ",", "url", "=", "url", ",", "allow_redirects", "=", "allow_redirects", ",", "timeout", "=", "timeout", ",", "verify", "=", "verify_ssl", ",", "*", "*", "kwargs", ")", "return", "response" ]
A slightly safer version of `request`.
[ "A", "slightly", "safer", "version", "of", "request", "." ]
382ed139cff8bf35c987cfc30a31b72c0d6b808e
https://github.com/polyaxon/hestia/blob/382ed139cff8bf35c987cfc30a31b72c0d6b808e/hestia/http.py#L12-L56
train
klmitch/turnstile
turnstile/remote.py
remote
def remote(func): """ Decorator to mark a function as invoking a remote procedure call. When invoked in server mode, the function will be called; when invoked in client mode, an RPC will be initiated. """ @functools.wraps(func) def wrapper(self, *args, **kwargs): if self.mode == 'server': # In server mode, call the function return func(self, *args, **kwargs) # Make sure we're connected if not self.conn: self.connect() # Call the remote function self.conn.send('CALL', func.__name__, args, kwargs) # Receive the response cmd, payload = self.conn.recv() if cmd == 'ERR': self.close() raise Exception("Catastrophic error from server: %s" % payload[0]) elif cmd == 'EXC': exc_type = utils.find_entrypoint(None, payload[0]) raise exc_type(payload[1]) elif cmd != 'RES': self.close() raise Exception("Invalid command response from server: %s" % cmd) return payload[0] # Mark it a callable wrapper._remote = True # Return the wrapped function return wrapper
python
def remote(func): """ Decorator to mark a function as invoking a remote procedure call. When invoked in server mode, the function will be called; when invoked in client mode, an RPC will be initiated. """ @functools.wraps(func) def wrapper(self, *args, **kwargs): if self.mode == 'server': # In server mode, call the function return func(self, *args, **kwargs) # Make sure we're connected if not self.conn: self.connect() # Call the remote function self.conn.send('CALL', func.__name__, args, kwargs) # Receive the response cmd, payload = self.conn.recv() if cmd == 'ERR': self.close() raise Exception("Catastrophic error from server: %s" % payload[0]) elif cmd == 'EXC': exc_type = utils.find_entrypoint(None, payload[0]) raise exc_type(payload[1]) elif cmd != 'RES': self.close() raise Exception("Invalid command response from server: %s" % cmd) return payload[0] # Mark it a callable wrapper._remote = True # Return the wrapped function return wrapper
[ "def", "remote", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "mode", "==", "'server'", ":", "# In server mode, call the function", "return", "func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "# Make sure we're connected", "if", "not", "self", ".", "conn", ":", "self", ".", "connect", "(", ")", "# Call the remote function", "self", ".", "conn", ".", "send", "(", "'CALL'", ",", "func", ".", "__name__", ",", "args", ",", "kwargs", ")", "# Receive the response", "cmd", ",", "payload", "=", "self", ".", "conn", ".", "recv", "(", ")", "if", "cmd", "==", "'ERR'", ":", "self", ".", "close", "(", ")", "raise", "Exception", "(", "\"Catastrophic error from server: %s\"", "%", "payload", "[", "0", "]", ")", "elif", "cmd", "==", "'EXC'", ":", "exc_type", "=", "utils", ".", "find_entrypoint", "(", "None", ",", "payload", "[", "0", "]", ")", "raise", "exc_type", "(", "payload", "[", "1", "]", ")", "elif", "cmd", "!=", "'RES'", ":", "self", ".", "close", "(", ")", "raise", "Exception", "(", "\"Invalid command response from server: %s\"", "%", "cmd", ")", "return", "payload", "[", "0", "]", "# Mark it a callable", "wrapper", ".", "_remote", "=", "True", "# Return the wrapped function", "return", "wrapper" ]
Decorator to mark a function as invoking a remote procedure call. When invoked in server mode, the function will be called; when invoked in client mode, an RPC will be initiated.
[ "Decorator", "to", "mark", "a", "function", "as", "invoking", "a", "remote", "procedure", "call", ".", "When", "invoked", "in", "server", "mode", "the", "function", "will", "be", "called", ";", "when", "invoked", "in", "client", "mode", "an", "RPC", "will", "be", "initiated", "." ]
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/remote.py#L171-L210
train
klmitch/turnstile
turnstile/remote.py
Connection.send
def send(self, cmd, *payload): """ Send a command message to the other end. :param cmd: The command to send to the other end. :param payload: The command payload. Note that all elements of the payload must be serializable to JSON. """ # If it's closed, raise an error up front if not self._sock: raise ConnectionClosed("Connection closed") # Construct the outgoing message msg = json.dumps(dict(cmd=cmd, payload=payload)) + '\n' # Send it try: self._sock.sendall(msg) except socket.error: # We'll need to re-raise e_type, e_value, e_tb = sys.exc_info() # Make sure the socket is closed self.close() # Re-raise raise e_type, e_value, e_tb
python
def send(self, cmd, *payload): """ Send a command message to the other end. :param cmd: The command to send to the other end. :param payload: The command payload. Note that all elements of the payload must be serializable to JSON. """ # If it's closed, raise an error up front if not self._sock: raise ConnectionClosed("Connection closed") # Construct the outgoing message msg = json.dumps(dict(cmd=cmd, payload=payload)) + '\n' # Send it try: self._sock.sendall(msg) except socket.error: # We'll need to re-raise e_type, e_value, e_tb = sys.exc_info() # Make sure the socket is closed self.close() # Re-raise raise e_type, e_value, e_tb
[ "def", "send", "(", "self", ",", "cmd", ",", "*", "payload", ")", ":", "# If it's closed, raise an error up front", "if", "not", "self", ".", "_sock", ":", "raise", "ConnectionClosed", "(", "\"Connection closed\"", ")", "# Construct the outgoing message", "msg", "=", "json", ".", "dumps", "(", "dict", "(", "cmd", "=", "cmd", ",", "payload", "=", "payload", ")", ")", "+", "'\\n'", "# Send it", "try", ":", "self", ".", "_sock", ".", "sendall", "(", "msg", ")", "except", "socket", ".", "error", ":", "# We'll need to re-raise", "e_type", ",", "e_value", ",", "e_tb", "=", "sys", ".", "exc_info", "(", ")", "# Make sure the socket is closed", "self", ".", "close", "(", ")", "# Re-raise", "raise", "e_type", ",", "e_value", ",", "e_tb" ]
Send a command message to the other end. :param cmd: The command to send to the other end. :param payload: The command payload. Note that all elements of the payload must be serializable to JSON.
[ "Send", "a", "command", "message", "to", "the", "other", "end", "." ]
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/remote.py#L67-L94
train
klmitch/turnstile
turnstile/remote.py
Connection._recvbuf_pop
def _recvbuf_pop(self): """ Internal helper to pop a message off the receive buffer. If the message is an Exception, that exception will be raised; otherwise, a tuple of command and payload will be returned. """ # Pop a message off the recv buffer and return (or raise) it msg = self._recvbuf.pop(0) if isinstance(msg, Exception): raise msg return msg['cmd'], msg['payload']
python
def _recvbuf_pop(self): """ Internal helper to pop a message off the receive buffer. If the message is an Exception, that exception will be raised; otherwise, a tuple of command and payload will be returned. """ # Pop a message off the recv buffer and return (or raise) it msg = self._recvbuf.pop(0) if isinstance(msg, Exception): raise msg return msg['cmd'], msg['payload']
[ "def", "_recvbuf_pop", "(", "self", ")", ":", "# Pop a message off the recv buffer and return (or raise) it", "msg", "=", "self", ".", "_recvbuf", ".", "pop", "(", "0", ")", "if", "isinstance", "(", "msg", ",", "Exception", ")", ":", "raise", "msg", "return", "msg", "[", "'cmd'", "]", ",", "msg", "[", "'payload'", "]" ]
Internal helper to pop a message off the receive buffer. If the message is an Exception, that exception will be raised; otherwise, a tuple of command and payload will be returned.
[ "Internal", "helper", "to", "pop", "a", "message", "off", "the", "receive", "buffer", ".", "If", "the", "message", "is", "an", "Exception", "that", "exception", "will", "be", "raised", ";", "otherwise", "a", "tuple", "of", "command", "and", "payload", "will", "be", "returned", "." ]
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/remote.py#L96-L107
train
klmitch/turnstile
turnstile/remote.py
SimpleRPC.ping
def ping(self): """ Ping the server. Returns the time interval, in seconds, required for the server to respond to the PING message. """ # Make sure we're connected if not self.conn: self.connect() # Send the ping and wait for the response self.conn.send('PING', time.time()) cmd, payload = self.conn.recv() recv_ts = time.time() # Make sure the response was a PONG if cmd != 'PONG': raise Exception("Invalid response from server") # Return the RTT return recv_ts - payload[0]
python
def ping(self): """ Ping the server. Returns the time interval, in seconds, required for the server to respond to the PING message. """ # Make sure we're connected if not self.conn: self.connect() # Send the ping and wait for the response self.conn.send('PING', time.time()) cmd, payload = self.conn.recv() recv_ts = time.time() # Make sure the response was a PONG if cmd != 'PONG': raise Exception("Invalid response from server") # Return the RTT return recv_ts - payload[0]
[ "def", "ping", "(", "self", ")", ":", "# Make sure we're connected", "if", "not", "self", ".", "conn", ":", "self", ".", "connect", "(", ")", "# Send the ping and wait for the response", "self", ".", "conn", ".", "send", "(", "'PING'", ",", "time", ".", "time", "(", ")", ")", "cmd", ",", "payload", "=", "self", ".", "conn", ".", "recv", "(", ")", "recv_ts", "=", "time", ".", "time", "(", ")", "# Make sure the response was a PONG", "if", "cmd", "!=", "'PONG'", ":", "raise", "Exception", "(", "\"Invalid response from server\"", ")", "# Return the RTT", "return", "recv_ts", "-", "payload", "[", "0", "]" ]
Ping the server. Returns the time interval, in seconds, required for the server to respond to the PING message.
[ "Ping", "the", "server", ".", "Returns", "the", "time", "interval", "in", "seconds", "required", "for", "the", "server", "to", "respond", "to", "the", "PING", "message", "." ]
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/remote.py#L288-L308
train
klmitch/turnstile
turnstile/remote.py
SimpleRPC.listen
def listen(self): """ Listen for clients. This method causes the SimpleRPC object to switch to server mode. One thread will be created for each client. """ # Make sure we're in server mode if self.mode and self.mode != 'server': raise ValueError("%s is not in server mode" % self.__class__.__name__) self.mode = 'server' # Obtain a listening socket serv = _create_server(self.host, self.port) # If we have too many errors, we want to bail out err_thresh = 0 while True: # Accept a connection try: sock, addr = serv.accept() except Exception as exc: err_thresh += 1 if err_thresh >= self.max_err_thresh: LOG.exception("Too many errors accepting " "connections: %s" % str(exc)) break continue # Pragma: nocover # Decrement error count on successful connections err_thresh = max(err_thresh - 1, 0) # Log the connection attempt LOG.info("Accepted connection from %s port %s" % (addr[0], addr[1])) # And handle the connection eventlet.spawn_n(self.serve, self.connection_class(sock), addr) # Close the listening socket with utils.ignore_except(): serv.close()
python
def listen(self): """ Listen for clients. This method causes the SimpleRPC object to switch to server mode. One thread will be created for each client. """ # Make sure we're in server mode if self.mode and self.mode != 'server': raise ValueError("%s is not in server mode" % self.__class__.__name__) self.mode = 'server' # Obtain a listening socket serv = _create_server(self.host, self.port) # If we have too many errors, we want to bail out err_thresh = 0 while True: # Accept a connection try: sock, addr = serv.accept() except Exception as exc: err_thresh += 1 if err_thresh >= self.max_err_thresh: LOG.exception("Too many errors accepting " "connections: %s" % str(exc)) break continue # Pragma: nocover # Decrement error count on successful connections err_thresh = max(err_thresh - 1, 0) # Log the connection attempt LOG.info("Accepted connection from %s port %s" % (addr[0], addr[1])) # And handle the connection eventlet.spawn_n(self.serve, self.connection_class(sock), addr) # Close the listening socket with utils.ignore_except(): serv.close()
[ "def", "listen", "(", "self", ")", ":", "# Make sure we're in server mode", "if", "self", ".", "mode", "and", "self", ".", "mode", "!=", "'server'", ":", "raise", "ValueError", "(", "\"%s is not in server mode\"", "%", "self", ".", "__class__", ".", "__name__", ")", "self", ".", "mode", "=", "'server'", "# Obtain a listening socket", "serv", "=", "_create_server", "(", "self", ".", "host", ",", "self", ".", "port", ")", "# If we have too many errors, we want to bail out", "err_thresh", "=", "0", "while", "True", ":", "# Accept a connection", "try", ":", "sock", ",", "addr", "=", "serv", ".", "accept", "(", ")", "except", "Exception", "as", "exc", ":", "err_thresh", "+=", "1", "if", "err_thresh", ">=", "self", ".", "max_err_thresh", ":", "LOG", ".", "exception", "(", "\"Too many errors accepting \"", "\"connections: %s\"", "%", "str", "(", "exc", ")", ")", "break", "continue", "# Pragma: nocover", "# Decrement error count on successful connections", "err_thresh", "=", "max", "(", "err_thresh", "-", "1", ",", "0", ")", "# Log the connection attempt", "LOG", ".", "info", "(", "\"Accepted connection from %s port %s\"", "%", "(", "addr", "[", "0", "]", ",", "addr", "[", "1", "]", ")", ")", "# And handle the connection", "eventlet", ".", "spawn_n", "(", "self", ".", "serve", ",", "self", ".", "connection_class", "(", "sock", ")", ",", "addr", ")", "# Close the listening socket", "with", "utils", ".", "ignore_except", "(", ")", ":", "serv", ".", "close", "(", ")" ]
Listen for clients. This method causes the SimpleRPC object to switch to server mode. One thread will be created for each client.
[ "Listen", "for", "clients", ".", "This", "method", "causes", "the", "SimpleRPC", "object", "to", "switch", "to", "server", "mode", ".", "One", "thread", "will", "be", "created", "for", "each", "client", "." ]
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/remote.py#L360-L402
train
klmitch/turnstile
turnstile/remote.py
SimpleRPC.serve
def serve(self, conn, addr, auth=False): """ Handle a single client. :param conn: The Connection instance. :param addr: The address of the client, for logging purposes. :param auth: A boolean specifying whether the connection should be considered authenticated or not. Provided for debugging. """ try: # Handle data from the client while True: # Get the command try: cmd, payload = conn.recv() except ValueError as exc: # Tell the client about the error conn.send('ERR', "Failed to parse command: %s" % str(exc)) # If they haven't successfully authenticated yet, # disconnect them if not auth: return continue # Pragma: nocover # Log the command and payload, for debugging purposes LOG.debug("Received command %r from %s port %s; payload: %r" % (cmd, addr[0], addr[1], payload)) # Handle authentication if cmd == 'AUTH': if auth: conn.send('ERR', "Already authenticated") elif payload[0] != self.authkey: # Don't give them a second chance conn.send('ERR', "Invalid authentication key") return else: # Authentication successful conn.send('OK') auth = True # Handle unauthenticated connections elif not auth: # No second chances conn.send('ERR', "Not authenticated") return # Handle aliveness test elif cmd == 'PING': conn.send('PONG', *payload) # Handle a function call command elif cmd == 'CALL': try: # Get the call parameters try: funcname, args, kwargs = payload except ValueError as exc: conn.send('ERR', "Invalid payload for 'CALL' " "command: %s" % str(exc)) continue # Look up the function func = self._get_remote_method(funcname) # Call the function result = func(*args, **kwargs) except Exception as exc: exc_name = '%s:%s' % (exc.__class__.__module__, exc.__class__.__name__) conn.send('EXC', exc_name, str(exc)) else: # Return the result conn.send('RES', result) # Handle all other commands by returning an ERR else: conn.send('ERR', "Unrecognized command %r" % cmd) except ConnectionClosed: # Ignore the connection closed error pass except Exception as exc: # Log other exceptions LOG.exception("Error serving client at %s port %s: %s" % (addr[0], addr[1], str(exc))) finally: LOG.info("Closing connection from %s port %s" % (addr[0], addr[1])) # Make sure the socket gets closed conn.close()
python
def serve(self, conn, addr, auth=False): """ Handle a single client. :param conn: The Connection instance. :param addr: The address of the client, for logging purposes. :param auth: A boolean specifying whether the connection should be considered authenticated or not. Provided for debugging. """ try: # Handle data from the client while True: # Get the command try: cmd, payload = conn.recv() except ValueError as exc: # Tell the client about the error conn.send('ERR', "Failed to parse command: %s" % str(exc)) # If they haven't successfully authenticated yet, # disconnect them if not auth: return continue # Pragma: nocover # Log the command and payload, for debugging purposes LOG.debug("Received command %r from %s port %s; payload: %r" % (cmd, addr[0], addr[1], payload)) # Handle authentication if cmd == 'AUTH': if auth: conn.send('ERR', "Already authenticated") elif payload[0] != self.authkey: # Don't give them a second chance conn.send('ERR', "Invalid authentication key") return else: # Authentication successful conn.send('OK') auth = True # Handle unauthenticated connections elif not auth: # No second chances conn.send('ERR', "Not authenticated") return # Handle aliveness test elif cmd == 'PING': conn.send('PONG', *payload) # Handle a function call command elif cmd == 'CALL': try: # Get the call parameters try: funcname, args, kwargs = payload except ValueError as exc: conn.send('ERR', "Invalid payload for 'CALL' " "command: %s" % str(exc)) continue # Look up the function func = self._get_remote_method(funcname) # Call the function result = func(*args, **kwargs) except Exception as exc: exc_name = '%s:%s' % (exc.__class__.__module__, exc.__class__.__name__) conn.send('EXC', exc_name, str(exc)) else: # Return the result conn.send('RES', result) # Handle all other commands by returning an ERR else: conn.send('ERR', "Unrecognized command %r" % cmd) except ConnectionClosed: # Ignore the connection closed error pass except Exception as exc: # Log other exceptions LOG.exception("Error serving client at %s port %s: %s" % (addr[0], addr[1], str(exc))) finally: LOG.info("Closing connection from %s port %s" % (addr[0], addr[1])) # Make sure the socket gets closed conn.close()
[ "def", "serve", "(", "self", ",", "conn", ",", "addr", ",", "auth", "=", "False", ")", ":", "try", ":", "# Handle data from the client", "while", "True", ":", "# Get the command", "try", ":", "cmd", ",", "payload", "=", "conn", ".", "recv", "(", ")", "except", "ValueError", "as", "exc", ":", "# Tell the client about the error", "conn", ".", "send", "(", "'ERR'", ",", "\"Failed to parse command: %s\"", "%", "str", "(", "exc", ")", ")", "# If they haven't successfully authenticated yet,", "# disconnect them", "if", "not", "auth", ":", "return", "continue", "# Pragma: nocover", "# Log the command and payload, for debugging purposes", "LOG", ".", "debug", "(", "\"Received command %r from %s port %s; payload: %r\"", "%", "(", "cmd", ",", "addr", "[", "0", "]", ",", "addr", "[", "1", "]", ",", "payload", ")", ")", "# Handle authentication", "if", "cmd", "==", "'AUTH'", ":", "if", "auth", ":", "conn", ".", "send", "(", "'ERR'", ",", "\"Already authenticated\"", ")", "elif", "payload", "[", "0", "]", "!=", "self", ".", "authkey", ":", "# Don't give them a second chance", "conn", ".", "send", "(", "'ERR'", ",", "\"Invalid authentication key\"", ")", "return", "else", ":", "# Authentication successful", "conn", ".", "send", "(", "'OK'", ")", "auth", "=", "True", "# Handle unauthenticated connections", "elif", "not", "auth", ":", "# No second chances", "conn", ".", "send", "(", "'ERR'", ",", "\"Not authenticated\"", ")", "return", "# Handle aliveness test", "elif", "cmd", "==", "'PING'", ":", "conn", ".", "send", "(", "'PONG'", ",", "*", "payload", ")", "# Handle a function call command", "elif", "cmd", "==", "'CALL'", ":", "try", ":", "# Get the call parameters", "try", ":", "funcname", ",", "args", ",", "kwargs", "=", "payload", "except", "ValueError", "as", "exc", ":", "conn", ".", "send", "(", "'ERR'", ",", "\"Invalid payload for 'CALL' \"", "\"command: %s\"", "%", "str", "(", "exc", ")", ")", "continue", "# Look up the function", "func", "=", "self", ".", "_get_remote_method", "(", "funcname", ")", "# Call the function", "result", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", "as", "exc", ":", "exc_name", "=", "'%s:%s'", "%", "(", "exc", ".", "__class__", ".", "__module__", ",", "exc", ".", "__class__", ".", "__name__", ")", "conn", ".", "send", "(", "'EXC'", ",", "exc_name", ",", "str", "(", "exc", ")", ")", "else", ":", "# Return the result", "conn", ".", "send", "(", "'RES'", ",", "result", ")", "# Handle all other commands by returning an ERR", "else", ":", "conn", ".", "send", "(", "'ERR'", ",", "\"Unrecognized command %r\"", "%", "cmd", ")", "except", "ConnectionClosed", ":", "# Ignore the connection closed error", "pass", "except", "Exception", "as", "exc", ":", "# Log other exceptions", "LOG", ".", "exception", "(", "\"Error serving client at %s port %s: %s\"", "%", "(", "addr", "[", "0", "]", ",", "addr", "[", "1", "]", ",", "str", "(", "exc", ")", ")", ")", "finally", ":", "LOG", ".", "info", "(", "\"Closing connection from %s port %s\"", "%", "(", "addr", "[", "0", "]", ",", "addr", "[", "1", "]", ")", ")", "# Make sure the socket gets closed", "conn", ".", "close", "(", ")" ]
Handle a single client. :param conn: The Connection instance. :param addr: The address of the client, for logging purposes. :param auth: A boolean specifying whether the connection should be considered authenticated or not. Provided for debugging.
[ "Handle", "a", "single", "client", "." ]
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/remote.py#L419-L514
train
klmitch/turnstile
turnstile/remote.py
RemoteControlDaemon.get_limits
def get_limits(self): """ Retrieve the LimitData object the middleware will use for getting the limits. This implementation returns a RemoteLimitData instance that can access the LimitData stored in the RemoteControlDaemon process. """ # Set one up if we don't already have it if not self.remote_limits: self.remote_limits = RemoteLimitData(self.remote) return self.remote_limits
python
def get_limits(self): """ Retrieve the LimitData object the middleware will use for getting the limits. This implementation returns a RemoteLimitData instance that can access the LimitData stored in the RemoteControlDaemon process. """ # Set one up if we don't already have it if not self.remote_limits: self.remote_limits = RemoteLimitData(self.remote) return self.remote_limits
[ "def", "get_limits", "(", "self", ")", ":", "# Set one up if we don't already have it", "if", "not", "self", ".", "remote_limits", ":", "self", ".", "remote_limits", "=", "RemoteLimitData", "(", "self", ".", "remote", ")", "return", "self", ".", "remote_limits" ]
Retrieve the LimitData object the middleware will use for getting the limits. This implementation returns a RemoteLimitData instance that can access the LimitData stored in the RemoteControlDaemon process.
[ "Retrieve", "the", "LimitData", "object", "the", "middleware", "will", "use", "for", "getting", "the", "limits", ".", "This", "implementation", "returns", "a", "RemoteLimitData", "instance", "that", "can", "access", "the", "LimitData", "stored", "in", "the", "RemoteControlDaemon", "process", "." ]
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/remote.py#L643-L654
train
kata198/python-subprocess2
subprocess2/__init__.py
waitUpTo
def waitUpTo(self, timeoutSeconds, pollInterval=DEFAULT_POLL_INTERVAL): ''' Popen.waitUpTo - Wait up to a certain number of seconds for the process to end. @param timeoutSeconds <float> - Number of seconds to wait @param pollInterval <float> (default .05) - Number of seconds in between each poll @return - Returncode of application, or None if did not terminate. ''' i = 0 numWaits = timeoutSeconds / float(pollInterval) ret = self.poll() if ret is None: while i < numWaits: time.sleep(pollInterval) ret = self.poll() if ret is not None: break i += 1 return ret
python
def waitUpTo(self, timeoutSeconds, pollInterval=DEFAULT_POLL_INTERVAL): ''' Popen.waitUpTo - Wait up to a certain number of seconds for the process to end. @param timeoutSeconds <float> - Number of seconds to wait @param pollInterval <float> (default .05) - Number of seconds in between each poll @return - Returncode of application, or None if did not terminate. ''' i = 0 numWaits = timeoutSeconds / float(pollInterval) ret = self.poll() if ret is None: while i < numWaits: time.sleep(pollInterval) ret = self.poll() if ret is not None: break i += 1 return ret
[ "def", "waitUpTo", "(", "self", ",", "timeoutSeconds", ",", "pollInterval", "=", "DEFAULT_POLL_INTERVAL", ")", ":", "i", "=", "0", "numWaits", "=", "timeoutSeconds", "/", "float", "(", "pollInterval", ")", "ret", "=", "self", ".", "poll", "(", ")", "if", "ret", "is", "None", ":", "while", "i", "<", "numWaits", ":", "time", ".", "sleep", "(", "pollInterval", ")", "ret", "=", "self", ".", "poll", "(", ")", "if", "ret", "is", "not", "None", ":", "break", "i", "+=", "1", "return", "ret" ]
Popen.waitUpTo - Wait up to a certain number of seconds for the process to end. @param timeoutSeconds <float> - Number of seconds to wait @param pollInterval <float> (default .05) - Number of seconds in between each poll @return - Returncode of application, or None if did not terminate.
[ "Popen", ".", "waitUpTo", "-", "Wait", "up", "to", "a", "certain", "number", "of", "seconds", "for", "the", "process", "to", "end", "." ]
8544b0b651d8e14de9fdd597baa704182e248b01
https://github.com/kata198/python-subprocess2/blob/8544b0b651d8e14de9fdd597baa704182e248b01/subprocess2/__init__.py#L63-L85
train
kata198/python-subprocess2
subprocess2/__init__.py
waitOrTerminate
def waitOrTerminate(self, timeoutSeconds, pollInterval=DEFAULT_POLL_INTERVAL, terminateToKillSeconds=SUBPROCESS2_DEFAULT_TERMINATE_TO_KILL_SECONDS): ''' waitOrTerminate - Wait up to a certain number of seconds for the process to end. If the process is running after the timeout has been exceeded, a SIGTERM will be sent. Optionally, an additional SIGKILL can be sent after some configurable interval. See #terminateToKillSeconds doc below @param timeoutSeconds <float> - Number of seconds to wait @param pollInterval <float> (default .05)- Number of seconds between each poll @param terminateToKillSeconds <float/None> (default 1.5) - If application does not end before #timeoutSeconds , terminate() will be called. * If this is set to None, an additional #pollInterval sleep will occur after calling .terminate, to allow the application to cleanup. returnCode will be return of app if finished, or None if did not complete. * If this is set to 0, no terminate signal will be sent, but directly to kill. Because the application cannot trap this, returnCode will be None. * If this is set to > 0, that number of seconds maximum will be given between .terminate and .kill. If the application does not terminate before KILL, returnCode will be None. Windows Note -- On windows SIGTERM and SIGKILL are the same thing. @return dict { 'returnCode' : <int or None> , 'actionTaken' : <int mask of SUBPROCESS2_PROCESS_*> } Returns a dict representing results: "returnCode" matches return of application, or None per #terminateToKillSeconds doc above. "actionTaken" is a mask of the SUBPROCESS2_PROCESS_* variables. If app completed normally, it will be SUBPROCESS2_PROCESS_COMPLETED, otherwise some mask of SUBPROCESS2_PROCESS_TERMINATED and/or SUBPROCESS2_PROCESS_KILLED ''' returnCode = self.waitUpTo(timeoutSeconds, pollInterval) actionTaken = SUBPROCESS2_PROCESS_COMPLETED if returnCode is None: if terminateToKillSeconds is None: self.terminate() actionTaken |= SUBPROCESS2_PROCESS_TERMINATED time.sleep(pollInterval) # Give a chance to cleanup returnCode = self.poll() elif terminateToKillSeconds == 0: self.kill() actionTaken |= SUBPROCESS2_PROCESS_KILLED time.sleep(.01) # Give a chance to happen self.poll() # Don't defunct returnCode = None else: self.terminate() actionTaken |= SUBPROCESS2_PROCESS_TERMINATED returnCode = self.waitUpTo(terminateToKillSeconds, pollInterval) if returnCode is None: actionTaken |= SUBPROCESS2_PROCESS_KILLED self.kill() time.sleep(.01) self.poll() # Don't defunct return { 'returnCode' : returnCode, 'actionTaken' : actionTaken }
python
def waitOrTerminate(self, timeoutSeconds, pollInterval=DEFAULT_POLL_INTERVAL, terminateToKillSeconds=SUBPROCESS2_DEFAULT_TERMINATE_TO_KILL_SECONDS): ''' waitOrTerminate - Wait up to a certain number of seconds for the process to end. If the process is running after the timeout has been exceeded, a SIGTERM will be sent. Optionally, an additional SIGKILL can be sent after some configurable interval. See #terminateToKillSeconds doc below @param timeoutSeconds <float> - Number of seconds to wait @param pollInterval <float> (default .05)- Number of seconds between each poll @param terminateToKillSeconds <float/None> (default 1.5) - If application does not end before #timeoutSeconds , terminate() will be called. * If this is set to None, an additional #pollInterval sleep will occur after calling .terminate, to allow the application to cleanup. returnCode will be return of app if finished, or None if did not complete. * If this is set to 0, no terminate signal will be sent, but directly to kill. Because the application cannot trap this, returnCode will be None. * If this is set to > 0, that number of seconds maximum will be given between .terminate and .kill. If the application does not terminate before KILL, returnCode will be None. Windows Note -- On windows SIGTERM and SIGKILL are the same thing. @return dict { 'returnCode' : <int or None> , 'actionTaken' : <int mask of SUBPROCESS2_PROCESS_*> } Returns a dict representing results: "returnCode" matches return of application, or None per #terminateToKillSeconds doc above. "actionTaken" is a mask of the SUBPROCESS2_PROCESS_* variables. If app completed normally, it will be SUBPROCESS2_PROCESS_COMPLETED, otherwise some mask of SUBPROCESS2_PROCESS_TERMINATED and/or SUBPROCESS2_PROCESS_KILLED ''' returnCode = self.waitUpTo(timeoutSeconds, pollInterval) actionTaken = SUBPROCESS2_PROCESS_COMPLETED if returnCode is None: if terminateToKillSeconds is None: self.terminate() actionTaken |= SUBPROCESS2_PROCESS_TERMINATED time.sleep(pollInterval) # Give a chance to cleanup returnCode = self.poll() elif terminateToKillSeconds == 0: self.kill() actionTaken |= SUBPROCESS2_PROCESS_KILLED time.sleep(.01) # Give a chance to happen self.poll() # Don't defunct returnCode = None else: self.terminate() actionTaken |= SUBPROCESS2_PROCESS_TERMINATED returnCode = self.waitUpTo(terminateToKillSeconds, pollInterval) if returnCode is None: actionTaken |= SUBPROCESS2_PROCESS_KILLED self.kill() time.sleep(.01) self.poll() # Don't defunct return { 'returnCode' : returnCode, 'actionTaken' : actionTaken }
[ "def", "waitOrTerminate", "(", "self", ",", "timeoutSeconds", ",", "pollInterval", "=", "DEFAULT_POLL_INTERVAL", ",", "terminateToKillSeconds", "=", "SUBPROCESS2_DEFAULT_TERMINATE_TO_KILL_SECONDS", ")", ":", "returnCode", "=", "self", ".", "waitUpTo", "(", "timeoutSeconds", ",", "pollInterval", ")", "actionTaken", "=", "SUBPROCESS2_PROCESS_COMPLETED", "if", "returnCode", "is", "None", ":", "if", "terminateToKillSeconds", "is", "None", ":", "self", ".", "terminate", "(", ")", "actionTaken", "|=", "SUBPROCESS2_PROCESS_TERMINATED", "time", ".", "sleep", "(", "pollInterval", ")", "# Give a chance to cleanup", "returnCode", "=", "self", ".", "poll", "(", ")", "elif", "terminateToKillSeconds", "==", "0", ":", "self", ".", "kill", "(", ")", "actionTaken", "|=", "SUBPROCESS2_PROCESS_KILLED", "time", ".", "sleep", "(", ".01", ")", "# Give a chance to happen", "self", ".", "poll", "(", ")", "# Don't defunct", "returnCode", "=", "None", "else", ":", "self", ".", "terminate", "(", ")", "actionTaken", "|=", "SUBPROCESS2_PROCESS_TERMINATED", "returnCode", "=", "self", ".", "waitUpTo", "(", "terminateToKillSeconds", ",", "pollInterval", ")", "if", "returnCode", "is", "None", ":", "actionTaken", "|=", "SUBPROCESS2_PROCESS_KILLED", "self", ".", "kill", "(", ")", "time", ".", "sleep", "(", ".01", ")", "self", ".", "poll", "(", ")", "# Don't defunct", "return", "{", "'returnCode'", ":", "returnCode", ",", "'actionTaken'", ":", "actionTaken", "}" ]
waitOrTerminate - Wait up to a certain number of seconds for the process to end. If the process is running after the timeout has been exceeded, a SIGTERM will be sent. Optionally, an additional SIGKILL can be sent after some configurable interval. See #terminateToKillSeconds doc below @param timeoutSeconds <float> - Number of seconds to wait @param pollInterval <float> (default .05)- Number of seconds between each poll @param terminateToKillSeconds <float/None> (default 1.5) - If application does not end before #timeoutSeconds , terminate() will be called. * If this is set to None, an additional #pollInterval sleep will occur after calling .terminate, to allow the application to cleanup. returnCode will be return of app if finished, or None if did not complete. * If this is set to 0, no terminate signal will be sent, but directly to kill. Because the application cannot trap this, returnCode will be None. * If this is set to > 0, that number of seconds maximum will be given between .terminate and .kill. If the application does not terminate before KILL, returnCode will be None. Windows Note -- On windows SIGTERM and SIGKILL are the same thing. @return dict { 'returnCode' : <int or None> , 'actionTaken' : <int mask of SUBPROCESS2_PROCESS_*> } Returns a dict representing results: "returnCode" matches return of application, or None per #terminateToKillSeconds doc above. "actionTaken" is a mask of the SUBPROCESS2_PROCESS_* variables. If app completed normally, it will be SUBPROCESS2_PROCESS_COMPLETED, otherwise some mask of SUBPROCESS2_PROCESS_TERMINATED and/or SUBPROCESS2_PROCESS_KILLED
[ "waitOrTerminate", "-", "Wait", "up", "to", "a", "certain", "number", "of", "seconds", "for", "the", "process", "to", "end", "." ]
8544b0b651d8e14de9fdd597baa704182e248b01
https://github.com/kata198/python-subprocess2/blob/8544b0b651d8e14de9fdd597baa704182e248b01/subprocess2/__init__.py#L89-L147
train
kata198/python-subprocess2
subprocess2/__init__.py
runInBackground
def runInBackground(self, pollInterval=.1, encoding=False): ''' runInBackground - Create a background thread which will manage this process, automatically read from streams, and perform any cleanups The object returned is a "BackgroundTaskInfo" object, and represents the state of the process. It is updated automatically as the program runs, and if stdout or stderr are streams, they are automatically read from and populated into this object. @see BackgroundTaskInfo for more info or http://pythonhosted.org/python-subprocess2/subprocess2.BackgroundTask.html @param pollInterval - Amount of idle time between polling @param encoding - Default False. If provided, data will be decoded using the value of this field as the codec name (e.x. "utf-8"). Otherwise, data will be stored as bytes. ''' from .BackgroundTask import BackgroundTaskThread taskInfo = BackgroundTaskInfo(encoding) thread = BackgroundTaskThread(self, taskInfo, pollInterval, encoding) thread.start() #thread.run() # Uncomment to use pdb debug (will not run in background) return taskInfo
python
def runInBackground(self, pollInterval=.1, encoding=False): ''' runInBackground - Create a background thread which will manage this process, automatically read from streams, and perform any cleanups The object returned is a "BackgroundTaskInfo" object, and represents the state of the process. It is updated automatically as the program runs, and if stdout or stderr are streams, they are automatically read from and populated into this object. @see BackgroundTaskInfo for more info or http://pythonhosted.org/python-subprocess2/subprocess2.BackgroundTask.html @param pollInterval - Amount of idle time between polling @param encoding - Default False. If provided, data will be decoded using the value of this field as the codec name (e.x. "utf-8"). Otherwise, data will be stored as bytes. ''' from .BackgroundTask import BackgroundTaskThread taskInfo = BackgroundTaskInfo(encoding) thread = BackgroundTaskThread(self, taskInfo, pollInterval, encoding) thread.start() #thread.run() # Uncomment to use pdb debug (will not run in background) return taskInfo
[ "def", "runInBackground", "(", "self", ",", "pollInterval", "=", ".1", ",", "encoding", "=", "False", ")", ":", "from", ".", "BackgroundTask", "import", "BackgroundTaskThread", "taskInfo", "=", "BackgroundTaskInfo", "(", "encoding", ")", "thread", "=", "BackgroundTaskThread", "(", "self", ",", "taskInfo", ",", "pollInterval", ",", "encoding", ")", "thread", ".", "start", "(", ")", "#thread.run() # Uncomment to use pdb debug (will not run in background)", "return", "taskInfo" ]
runInBackground - Create a background thread which will manage this process, automatically read from streams, and perform any cleanups The object returned is a "BackgroundTaskInfo" object, and represents the state of the process. It is updated automatically as the program runs, and if stdout or stderr are streams, they are automatically read from and populated into this object. @see BackgroundTaskInfo for more info or http://pythonhosted.org/python-subprocess2/subprocess2.BackgroundTask.html @param pollInterval - Amount of idle time between polling @param encoding - Default False. If provided, data will be decoded using the value of this field as the codec name (e.x. "utf-8"). Otherwise, data will be stored as bytes.
[ "runInBackground", "-", "Create", "a", "background", "thread", "which", "will", "manage", "this", "process", "automatically", "read", "from", "streams", "and", "perform", "any", "cleanups" ]
8544b0b651d8e14de9fdd597baa704182e248b01
https://github.com/kata198/python-subprocess2/blob/8544b0b651d8e14de9fdd597baa704182e248b01/subprocess2/__init__.py#L152-L172
train
jstitch/MambuPy
MambuPy/rest/mambugroup.py
MambuGroup.setClients
def setClients(self, *args, **kwargs): """Adds the clients for this group to a 'clients' field. The 'groupMembers' field of the group holds the encodedKeys of the member clients of the group. Since Mambu REST API accepts both ids or encodedKeys to retrieve entities, we use that here. You may wish to get the full details of each client by passing a fullDetails=True argument here. Returns the number of requests done to Mambu. """ requests = 0 if 'fullDetails' in kwargs: fullDetails = kwargs['fullDetails'] kwargs.pop('fullDetails') else: fullDetails = True clients = [] for m in self['groupMembers']: try: client = self.mambuclientclass(entid=m['clientKey'], fullDetails=fullDetails, *args, **kwargs) except AttributeError as ae: from .mambuclient import MambuClient self.mambuclientclass = MambuClient client = self.mambuclientclass(entid=m['clientKey'], fullDetails=fullDetails, *args, **kwargs) requests += 1 clients.append(client) self['clients'] = clients return requests
python
def setClients(self, *args, **kwargs): """Adds the clients for this group to a 'clients' field. The 'groupMembers' field of the group holds the encodedKeys of the member clients of the group. Since Mambu REST API accepts both ids or encodedKeys to retrieve entities, we use that here. You may wish to get the full details of each client by passing a fullDetails=True argument here. Returns the number of requests done to Mambu. """ requests = 0 if 'fullDetails' in kwargs: fullDetails = kwargs['fullDetails'] kwargs.pop('fullDetails') else: fullDetails = True clients = [] for m in self['groupMembers']: try: client = self.mambuclientclass(entid=m['clientKey'], fullDetails=fullDetails, *args, **kwargs) except AttributeError as ae: from .mambuclient import MambuClient self.mambuclientclass = MambuClient client = self.mambuclientclass(entid=m['clientKey'], fullDetails=fullDetails, *args, **kwargs) requests += 1 clients.append(client) self['clients'] = clients return requests
[ "def", "setClients", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "requests", "=", "0", "if", "'fullDetails'", "in", "kwargs", ":", "fullDetails", "=", "kwargs", "[", "'fullDetails'", "]", "kwargs", ".", "pop", "(", "'fullDetails'", ")", "else", ":", "fullDetails", "=", "True", "clients", "=", "[", "]", "for", "m", "in", "self", "[", "'groupMembers'", "]", ":", "try", ":", "client", "=", "self", ".", "mambuclientclass", "(", "entid", "=", "m", "[", "'clientKey'", "]", ",", "fullDetails", "=", "fullDetails", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", "AttributeError", "as", "ae", ":", "from", ".", "mambuclient", "import", "MambuClient", "self", ".", "mambuclientclass", "=", "MambuClient", "client", "=", "self", ".", "mambuclientclass", "(", "entid", "=", "m", "[", "'clientKey'", "]", ",", "fullDetails", "=", "fullDetails", ",", "*", "args", ",", "*", "*", "kwargs", ")", "requests", "+=", "1", "clients", ".", "append", "(", "client", ")", "self", "[", "'clients'", "]", "=", "clients", "return", "requests" ]
Adds the clients for this group to a 'clients' field. The 'groupMembers' field of the group holds the encodedKeys of the member clients of the group. Since Mambu REST API accepts both ids or encodedKeys to retrieve entities, we use that here. You may wish to get the full details of each client by passing a fullDetails=True argument here. Returns the number of requests done to Mambu.
[ "Adds", "the", "clients", "for", "this", "group", "to", "a", "clients", "field", "." ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambugroup.py#L77-L112
train
jstitch/MambuPy
MambuPy/rest/mambugroup.py
MambuGroup.setActivities
def setActivities(self, *args, **kwargs): """Adds the activities for this group to a 'activities' field. Activities are MambuActivity objects. Activities get sorted by activity timestamp. Returns the number of requests done to Mambu. """ def activityDate(activity): """Util function used for sorting activities according to timestamp""" try: return activity['activity']['timestamp'] except KeyError as kerr: return None try: activities = self.mambuactivitiesclass(groupId=self['encodedKey'], *args, **kwargs) except AttributeError as ae: from .mambuactivity import MambuActivities self.mambuactivitiesclass = MambuActivities activities = self.mambuactivitiesclass(groupId=self['encodedKey'], *args, **kwargs) activities.attrs = sorted(activities.attrs, key=activityDate) self['activities'] = activities return 1
python
def setActivities(self, *args, **kwargs): """Adds the activities for this group to a 'activities' field. Activities are MambuActivity objects. Activities get sorted by activity timestamp. Returns the number of requests done to Mambu. """ def activityDate(activity): """Util function used for sorting activities according to timestamp""" try: return activity['activity']['timestamp'] except KeyError as kerr: return None try: activities = self.mambuactivitiesclass(groupId=self['encodedKey'], *args, **kwargs) except AttributeError as ae: from .mambuactivity import MambuActivities self.mambuactivitiesclass = MambuActivities activities = self.mambuactivitiesclass(groupId=self['encodedKey'], *args, **kwargs) activities.attrs = sorted(activities.attrs, key=activityDate) self['activities'] = activities return 1
[ "def", "setActivities", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "activityDate", "(", "activity", ")", ":", "\"\"\"Util function used for sorting activities according to timestamp\"\"\"", "try", ":", "return", "activity", "[", "'activity'", "]", "[", "'timestamp'", "]", "except", "KeyError", "as", "kerr", ":", "return", "None", "try", ":", "activities", "=", "self", ".", "mambuactivitiesclass", "(", "groupId", "=", "self", "[", "'encodedKey'", "]", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", "AttributeError", "as", "ae", ":", "from", ".", "mambuactivity", "import", "MambuActivities", "self", ".", "mambuactivitiesclass", "=", "MambuActivities", "activities", "=", "self", ".", "mambuactivitiesclass", "(", "groupId", "=", "self", "[", "'encodedKey'", "]", ",", "*", "args", ",", "*", "*", "kwargs", ")", "activities", ".", "attrs", "=", "sorted", "(", "activities", ".", "attrs", ",", "key", "=", "activityDate", ")", "self", "[", "'activities'", "]", "=", "activities", "return", "1" ]
Adds the activities for this group to a 'activities' field. Activities are MambuActivity objects. Activities get sorted by activity timestamp. Returns the number of requests done to Mambu.
[ "Adds", "the", "activities", "for", "this", "group", "to", "a", "activities", "field", "." ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambugroup.py#L142-L167
train
azogue/i2csense
i2csense/bh1750.py
BH1750.set_sensitivity
def set_sensitivity(self, sensitivity=DEFAULT_SENSITIVITY): """Set the sensitivity value. Valid values are 31 (lowest) to 254 (highest), default is 69. """ if sensitivity < 31: self._mtreg = 31 elif sensitivity > 254: self._mtreg = 254 else: self._mtreg = sensitivity self._power_on() self._set_mode(0x40 | (self._mtreg >> 5)) self._set_mode(0x60 | (self._mtreg & 0x1f)) self._power_down()
python
def set_sensitivity(self, sensitivity=DEFAULT_SENSITIVITY): """Set the sensitivity value. Valid values are 31 (lowest) to 254 (highest), default is 69. """ if sensitivity < 31: self._mtreg = 31 elif sensitivity > 254: self._mtreg = 254 else: self._mtreg = sensitivity self._power_on() self._set_mode(0x40 | (self._mtreg >> 5)) self._set_mode(0x60 | (self._mtreg & 0x1f)) self._power_down()
[ "def", "set_sensitivity", "(", "self", ",", "sensitivity", "=", "DEFAULT_SENSITIVITY", ")", ":", "if", "sensitivity", "<", "31", ":", "self", ".", "_mtreg", "=", "31", "elif", "sensitivity", ">", "254", ":", "self", ".", "_mtreg", "=", "254", "else", ":", "self", ".", "_mtreg", "=", "sensitivity", "self", ".", "_power_on", "(", ")", "self", ".", "_set_mode", "(", "0x40", "|", "(", "self", ".", "_mtreg", ">>", "5", ")", ")", "self", ".", "_set_mode", "(", "0x60", "|", "(", "self", ".", "_mtreg", "&", "0x1f", ")", ")", "self", ".", "_power_down", "(", ")" ]
Set the sensitivity value. Valid values are 31 (lowest) to 254 (highest), default is 69.
[ "Set", "the", "sensitivity", "value", "." ]
ecc6806dcee9de827a5414a9e836d271fedca9b9
https://github.com/azogue/i2csense/blob/ecc6806dcee9de827a5414a9e836d271fedca9b9/i2csense/bh1750.py#L92-L106
train
azogue/i2csense
i2csense/bh1750.py
BH1750._get_result
def _get_result(self) -> float: """Return current measurement result in lx.""" try: data = self._bus.read_word_data(self._i2c_add, self._mode) self._ok = True except OSError as exc: self.log_error("Bad reading in bus: %s", exc) self._ok = False return -1 count = data >> 8 | (data & 0xff) << 8 mode2coeff = 2 if self._high_res else 1 ratio = 1 / (1.2 * (self._mtreg / 69.0) * mode2coeff) return ratio * count
python
def _get_result(self) -> float: """Return current measurement result in lx.""" try: data = self._bus.read_word_data(self._i2c_add, self._mode) self._ok = True except OSError as exc: self.log_error("Bad reading in bus: %s", exc) self._ok = False return -1 count = data >> 8 | (data & 0xff) << 8 mode2coeff = 2 if self._high_res else 1 ratio = 1 / (1.2 * (self._mtreg / 69.0) * mode2coeff) return ratio * count
[ "def", "_get_result", "(", "self", ")", "->", "float", ":", "try", ":", "data", "=", "self", ".", "_bus", ".", "read_word_data", "(", "self", ".", "_i2c_add", ",", "self", ".", "_mode", ")", "self", ".", "_ok", "=", "True", "except", "OSError", "as", "exc", ":", "self", ".", "log_error", "(", "\"Bad reading in bus: %s\"", ",", "exc", ")", "self", ".", "_ok", "=", "False", "return", "-", "1", "count", "=", "data", ">>", "8", "|", "(", "data", "&", "0xff", ")", "<<", "8", "mode2coeff", "=", "2", "if", "self", ".", "_high_res", "else", "1", "ratio", "=", "1", "/", "(", "1.2", "*", "(", "self", ".", "_mtreg", "/", "69.0", ")", "*", "mode2coeff", ")", "return", "ratio", "*", "count" ]
Return current measurement result in lx.
[ "Return", "current", "measurement", "result", "in", "lx", "." ]
ecc6806dcee9de827a5414a9e836d271fedca9b9
https://github.com/azogue/i2csense/blob/ecc6806dcee9de827a5414a9e836d271fedca9b9/i2csense/bh1750.py#L108-L121
train
azogue/i2csense
i2csense/bh1750.py
BH1750._wait_for_result
def _wait_for_result(self): """Wait for the sensor to be ready for measurement.""" basetime = 0.018 if self._low_res else 0.128 sleep(basetime * (self._mtreg / 69.0) + self._delay)
python
def _wait_for_result(self): """Wait for the sensor to be ready for measurement.""" basetime = 0.018 if self._low_res else 0.128 sleep(basetime * (self._mtreg / 69.0) + self._delay)
[ "def", "_wait_for_result", "(", "self", ")", ":", "basetime", "=", "0.018", "if", "self", ".", "_low_res", "else", "0.128", "sleep", "(", "basetime", "*", "(", "self", ".", "_mtreg", "/", "69.0", ")", "+", "self", ".", "_delay", ")" ]
Wait for the sensor to be ready for measurement.
[ "Wait", "for", "the", "sensor", "to", "be", "ready", "for", "measurement", "." ]
ecc6806dcee9de827a5414a9e836d271fedca9b9
https://github.com/azogue/i2csense/blob/ecc6806dcee9de827a5414a9e836d271fedca9b9/i2csense/bh1750.py#L123-L126
train
azogue/i2csense
i2csense/bh1750.py
BH1750.update
def update(self): """Update the measured light level in lux.""" if not self._continuous_sampling \ or self._light_level < 0 \ or self._operation_mode != self._mode: self._reset() self._set_mode(self._operation_mode) self._wait_for_result() self._light_level = self._get_result() if not self._continuous_sampling: self._power_down()
python
def update(self): """Update the measured light level in lux.""" if not self._continuous_sampling \ or self._light_level < 0 \ or self._operation_mode != self._mode: self._reset() self._set_mode(self._operation_mode) self._wait_for_result() self._light_level = self._get_result() if not self._continuous_sampling: self._power_down()
[ "def", "update", "(", "self", ")", ":", "if", "not", "self", ".", "_continuous_sampling", "or", "self", ".", "_light_level", "<", "0", "or", "self", ".", "_operation_mode", "!=", "self", ".", "_mode", ":", "self", ".", "_reset", "(", ")", "self", ".", "_set_mode", "(", "self", ".", "_operation_mode", ")", "self", ".", "_wait_for_result", "(", ")", "self", ".", "_light_level", "=", "self", ".", "_get_result", "(", ")", "if", "not", "self", ".", "_continuous_sampling", ":", "self", ".", "_power_down", "(", ")" ]
Update the measured light level in lux.
[ "Update", "the", "measured", "light", "level", "in", "lux", "." ]
ecc6806dcee9de827a5414a9e836d271fedca9b9
https://github.com/azogue/i2csense/blob/ecc6806dcee9de827a5414a9e836d271fedca9b9/i2csense/bh1750.py#L128-L138
train
jpscaletti/authcode
authcode/utils.py
get_token
def get_token(user, secret, timestamp=None): """Make a timestamped one-time-use token that can be used to identifying the user. By hashing the `last_sign_in` attribute and a snippet of the current password hash salt, it produces a token that will be invalidated as soon as the user log in again or the is changed. A hash of the user ID is used, so the HMAC part of the token is always unique for each user. It also hash a secret key, so without access to the source code, fake tokens cannot be generated even if the database is compromised. """ timestamp = int(timestamp or time()) secret = to_bytes(secret) key = '|'.join([ hashlib.sha1(secret).hexdigest(), str(user.id), get_hash_extract(user.password), str(getattr(user, 'last_sign_in', 0)), str(timestamp), ]) key = key.encode('utf8', 'ignore') mac = hmac.new(key, msg=None, digestmod=hashlib.sha512) mac = mac.hexdigest()[:50] token = '{0}${1}${2}'.format(user.id, to36(timestamp), mac) return token
python
def get_token(user, secret, timestamp=None): """Make a timestamped one-time-use token that can be used to identifying the user. By hashing the `last_sign_in` attribute and a snippet of the current password hash salt, it produces a token that will be invalidated as soon as the user log in again or the is changed. A hash of the user ID is used, so the HMAC part of the token is always unique for each user. It also hash a secret key, so without access to the source code, fake tokens cannot be generated even if the database is compromised. """ timestamp = int(timestamp or time()) secret = to_bytes(secret) key = '|'.join([ hashlib.sha1(secret).hexdigest(), str(user.id), get_hash_extract(user.password), str(getattr(user, 'last_sign_in', 0)), str(timestamp), ]) key = key.encode('utf8', 'ignore') mac = hmac.new(key, msg=None, digestmod=hashlib.sha512) mac = mac.hexdigest()[:50] token = '{0}${1}${2}'.format(user.id, to36(timestamp), mac) return token
[ "def", "get_token", "(", "user", ",", "secret", ",", "timestamp", "=", "None", ")", ":", "timestamp", "=", "int", "(", "timestamp", "or", "time", "(", ")", ")", "secret", "=", "to_bytes", "(", "secret", ")", "key", "=", "'|'", ".", "join", "(", "[", "hashlib", ".", "sha1", "(", "secret", ")", ".", "hexdigest", "(", ")", ",", "str", "(", "user", ".", "id", ")", ",", "get_hash_extract", "(", "user", ".", "password", ")", ",", "str", "(", "getattr", "(", "user", ",", "'last_sign_in'", ",", "0", ")", ")", ",", "str", "(", "timestamp", ")", ",", "]", ")", "key", "=", "key", ".", "encode", "(", "'utf8'", ",", "'ignore'", ")", "mac", "=", "hmac", ".", "new", "(", "key", ",", "msg", "=", "None", ",", "digestmod", "=", "hashlib", ".", "sha512", ")", "mac", "=", "mac", ".", "hexdigest", "(", ")", "[", ":", "50", "]", "token", "=", "'{0}${1}${2}'", ".", "format", "(", "user", ".", "id", ",", "to36", "(", "timestamp", ")", ",", "mac", ")", "return", "token" ]
Make a timestamped one-time-use token that can be used to identifying the user. By hashing the `last_sign_in` attribute and a snippet of the current password hash salt, it produces a token that will be invalidated as soon as the user log in again or the is changed. A hash of the user ID is used, so the HMAC part of the token is always unique for each user. It also hash a secret key, so without access to the source code, fake tokens cannot be generated even if the database is compromised.
[ "Make", "a", "timestamped", "one", "-", "time", "-", "use", "token", "that", "can", "be", "used", "to", "identifying", "the", "user", "." ]
91529b6d0caec07d1452758d937e1e0745826139
https://github.com/jpscaletti/authcode/blob/91529b6d0caec07d1452758d937e1e0745826139/authcode/utils.py#L63-L90
train
jpscaletti/authcode
authcode/utils.py
LazyUser.__get_user
def __get_user(self): """Return the real user object. """ storage = object.__getattribute__(self, '_LazyUser__storage') user = getattr(self.__auth, 'get_user')() setattr(storage, self.__user_name, user) return user
python
def __get_user(self): """Return the real user object. """ storage = object.__getattribute__(self, '_LazyUser__storage') user = getattr(self.__auth, 'get_user')() setattr(storage, self.__user_name, user) return user
[ "def", "__get_user", "(", "self", ")", ":", "storage", "=", "object", ".", "__getattribute__", "(", "self", ",", "'_LazyUser__storage'", ")", "user", "=", "getattr", "(", "self", ".", "__auth", ",", "'get_user'", ")", "(", ")", "setattr", "(", "storage", ",", "self", ".", "__user_name", ",", "user", ")", "return", "user" ]
Return the real user object.
[ "Return", "the", "real", "user", "object", "." ]
91529b6d0caec07d1452758d937e1e0745826139
https://github.com/jpscaletti/authcode/blob/91529b6d0caec07d1452758d937e1e0745826139/authcode/utils.py#L116-L122
train
cloudmesh-cmd3/cmd3
cmd3/plugins/browser.py
browser._expand_filename
def _expand_filename(self, line): """expands the filename if there is a . as leading path""" # expand . newline = line path = os.getcwd() if newline.startswith("."): newline = newline.replace(".", path, 1) # expand ~ newline = os.path.expanduser(newline) return newline
python
def _expand_filename(self, line): """expands the filename if there is a . as leading path""" # expand . newline = line path = os.getcwd() if newline.startswith("."): newline = newline.replace(".", path, 1) # expand ~ newline = os.path.expanduser(newline) return newline
[ "def", "_expand_filename", "(", "self", ",", "line", ")", ":", "# expand .", "newline", "=", "line", "path", "=", "os", ".", "getcwd", "(", ")", "if", "newline", ".", "startswith", "(", "\".\"", ")", ":", "newline", "=", "newline", ".", "replace", "(", "\".\"", ",", "path", ",", "1", ")", "# expand ~", "newline", "=", "os", ".", "path", ".", "expanduser", "(", "newline", ")", "return", "newline" ]
expands the filename if there is a . as leading path
[ "expands", "the", "filename", "if", "there", "is", "a", ".", "as", "leading", "path" ]
92e33c96032fd3921f159198a0e57917c4dc34ed
https://github.com/cloudmesh-cmd3/cmd3/blob/92e33c96032fd3921f159198a0e57917c4dc34ed/cmd3/plugins/browser.py#L14-L23
train
jstitch/MambuPy
MambuPy/rest/mambustruct.py
setCustomField
def setCustomField(mambuentity, customfield="", *args, **kwargs): """Modifies the customField field for the given object with something related to the value of the given field. If the dataType == "USER_LINK" then instead of using the value of the CF, it will be a MambuUser object. Same if dataType == "CLIENT_LINK", but with a MambuClient. Default case: just uses the same value the CF already had. Returns the number of requests done to Mambu. """ from . import mambuuser from . import mambuclient try: customFieldValue = mambuentity[customfield] # find the dataType customfield by name or id datatype = [ l['customField']['dataType'] for l in mambuentity[mambuentity.customFieldName] if (l['name'] == customfield or l['id'] == customfield) ][0] except IndexError as ierr: # if no customfield found with the given name, assume it is a # grouped custom field, name must have an index suffix that must # be removed try: # find the dataType customfield by name or id datatype = [ l['customField']['dataType'] for l in mambuentity[mambuentity.customFieldName] if (l['name'] == customfield.split('_')[0] or l['id'] == customfield.split('_')[0]) ][0] except IndexError: err = MambuError("Object %s has no custom field '%s'" % (mambuentity['id'], customfield)) raise err except AttributeError: err = MambuError("Object does not have a custom field to set") raise err if datatype == "USER_LINK": mambuentity[customfield] = mambuuser.MambuUser(entid=customFieldValue, *args, **kwargs) elif datatype == "CLIENT_LINK": mambuentity[customfield] = mambuclient.MambuClient(entid=customFieldValue, *args, **kwargs) else: mambuentity[customfield] = customFieldValue return 0 return 1
python
def setCustomField(mambuentity, customfield="", *args, **kwargs): """Modifies the customField field for the given object with something related to the value of the given field. If the dataType == "USER_LINK" then instead of using the value of the CF, it will be a MambuUser object. Same if dataType == "CLIENT_LINK", but with a MambuClient. Default case: just uses the same value the CF already had. Returns the number of requests done to Mambu. """ from . import mambuuser from . import mambuclient try: customFieldValue = mambuentity[customfield] # find the dataType customfield by name or id datatype = [ l['customField']['dataType'] for l in mambuentity[mambuentity.customFieldName] if (l['name'] == customfield or l['id'] == customfield) ][0] except IndexError as ierr: # if no customfield found with the given name, assume it is a # grouped custom field, name must have an index suffix that must # be removed try: # find the dataType customfield by name or id datatype = [ l['customField']['dataType'] for l in mambuentity[mambuentity.customFieldName] if (l['name'] == customfield.split('_')[0] or l['id'] == customfield.split('_')[0]) ][0] except IndexError: err = MambuError("Object %s has no custom field '%s'" % (mambuentity['id'], customfield)) raise err except AttributeError: err = MambuError("Object does not have a custom field to set") raise err if datatype == "USER_LINK": mambuentity[customfield] = mambuuser.MambuUser(entid=customFieldValue, *args, **kwargs) elif datatype == "CLIENT_LINK": mambuentity[customfield] = mambuclient.MambuClient(entid=customFieldValue, *args, **kwargs) else: mambuentity[customfield] = customFieldValue return 0 return 1
[ "def", "setCustomField", "(", "mambuentity", ",", "customfield", "=", "\"\"", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", ".", "import", "mambuuser", "from", ".", "import", "mambuclient", "try", ":", "customFieldValue", "=", "mambuentity", "[", "customfield", "]", "# find the dataType customfield by name or id", "datatype", "=", "[", "l", "[", "'customField'", "]", "[", "'dataType'", "]", "for", "l", "in", "mambuentity", "[", "mambuentity", ".", "customFieldName", "]", "if", "(", "l", "[", "'name'", "]", "==", "customfield", "or", "l", "[", "'id'", "]", "==", "customfield", ")", "]", "[", "0", "]", "except", "IndexError", "as", "ierr", ":", "# if no customfield found with the given name, assume it is a", "# grouped custom field, name must have an index suffix that must", "# be removed", "try", ":", "# find the dataType customfield by name or id", "datatype", "=", "[", "l", "[", "'customField'", "]", "[", "'dataType'", "]", "for", "l", "in", "mambuentity", "[", "mambuentity", ".", "customFieldName", "]", "if", "(", "l", "[", "'name'", "]", "==", "customfield", ".", "split", "(", "'_'", ")", "[", "0", "]", "or", "l", "[", "'id'", "]", "==", "customfield", ".", "split", "(", "'_'", ")", "[", "0", "]", ")", "]", "[", "0", "]", "except", "IndexError", ":", "err", "=", "MambuError", "(", "\"Object %s has no custom field '%s'\"", "%", "(", "mambuentity", "[", "'id'", "]", ",", "customfield", ")", ")", "raise", "err", "except", "AttributeError", ":", "err", "=", "MambuError", "(", "\"Object does not have a custom field to set\"", ")", "raise", "err", "if", "datatype", "==", "\"USER_LINK\"", ":", "mambuentity", "[", "customfield", "]", "=", "mambuuser", ".", "MambuUser", "(", "entid", "=", "customFieldValue", ",", "*", "args", ",", "*", "*", "kwargs", ")", "elif", "datatype", "==", "\"CLIENT_LINK\"", ":", "mambuentity", "[", "customfield", "]", "=", "mambuclient", ".", "MambuClient", "(", "entid", "=", "customFieldValue", ",", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "mambuentity", "[", "customfield", "]", "=", "customFieldValue", "return", "0", "return", "1" ]
Modifies the customField field for the given object with something related to the value of the given field. If the dataType == "USER_LINK" then instead of using the value of the CF, it will be a MambuUser object. Same if dataType == "CLIENT_LINK", but with a MambuClient. Default case: just uses the same value the CF already had. Returns the number of requests done to Mambu.
[ "Modifies", "the", "customField", "field", "for", "the", "given", "object", "with", "something", "related", "to", "the", "value", "of", "the", "given", "field", "." ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambustruct.py#L837-L878
train
jstitch/MambuPy
MambuPy/rest/mambustruct.py
MambuStruct.serializeFields
def serializeFields(data): """Turns every attribute of the Mambu object in to a string representation. If the object is an iterable one, it goes down to each of its elements and turns its attributes too, recursively. The base case is when it's a MambuStruct class (this one) so it just 'serializes' the attr atribute. Refer to MambuStruct.serializeStruct pydoc. This is perhaps the worst way to do it, still looking for a better way. """ if isinstance(data, MambuStruct): return data.serializeStruct() try: it = iter(data) except TypeError as terr: return unicode(data) if type(it) == type(iter([])): l = [] for e in it: l.append(MambuStruct.serializeFields(e)) return l elif type(it) == type(iter({})): d = {} for k in it: d[k] = MambuStruct.serializeFields(data[k]) return d # elif ... tuples? sets? return unicode(data)
python
def serializeFields(data): """Turns every attribute of the Mambu object in to a string representation. If the object is an iterable one, it goes down to each of its elements and turns its attributes too, recursively. The base case is when it's a MambuStruct class (this one) so it just 'serializes' the attr atribute. Refer to MambuStruct.serializeStruct pydoc. This is perhaps the worst way to do it, still looking for a better way. """ if isinstance(data, MambuStruct): return data.serializeStruct() try: it = iter(data) except TypeError as terr: return unicode(data) if type(it) == type(iter([])): l = [] for e in it: l.append(MambuStruct.serializeFields(e)) return l elif type(it) == type(iter({})): d = {} for k in it: d[k] = MambuStruct.serializeFields(data[k]) return d # elif ... tuples? sets? return unicode(data)
[ "def", "serializeFields", "(", "data", ")", ":", "if", "isinstance", "(", "data", ",", "MambuStruct", ")", ":", "return", "data", ".", "serializeStruct", "(", ")", "try", ":", "it", "=", "iter", "(", "data", ")", "except", "TypeError", "as", "terr", ":", "return", "unicode", "(", "data", ")", "if", "type", "(", "it", ")", "==", "type", "(", "iter", "(", "[", "]", ")", ")", ":", "l", "=", "[", "]", "for", "e", "in", "it", ":", "l", ".", "append", "(", "MambuStruct", ".", "serializeFields", "(", "e", ")", ")", "return", "l", "elif", "type", "(", "it", ")", "==", "type", "(", "iter", "(", "{", "}", ")", ")", ":", "d", "=", "{", "}", "for", "k", "in", "it", ":", "d", "[", "k", "]", "=", "MambuStruct", ".", "serializeFields", "(", "data", "[", "k", "]", ")", "return", "d", "# elif ... tuples? sets?", "return", "unicode", "(", "data", ")" ]
Turns every attribute of the Mambu object in to a string representation. If the object is an iterable one, it goes down to each of its elements and turns its attributes too, recursively. The base case is when it's a MambuStruct class (this one) so it just 'serializes' the attr atribute. Refer to MambuStruct.serializeStruct pydoc. This is perhaps the worst way to do it, still looking for a better way.
[ "Turns", "every", "attribute", "of", "the", "Mambu", "object", "in", "to", "a", "string", "representation", "." ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambustruct.py#L121-L150
train
jstitch/MambuPy
MambuPy/rest/mambustruct.py
MambuStruct.init
def init(self, attrs={}, *args, **kwargs): """Default initialization from a dictionary responded by Mambu in to the elements of the Mambu object. It assings the response to attrs attribute and converts each of its elements from a string to an adequate python object: number, datetime, etc. Basically it stores the response on the attrs attribute, then runs some customizable preprocess method, then runs convertDict2Attrs method to convert the string elements to an adequate python object, then a customizable postprocess method. It also executes each method on the 'methods' attribute given on instantiation time, and sets new customizable 'properties' to the object. Why not on __init__? two reasons: * __init__ optionally connects to Mambu, if you don't connect to Mambu, the Mambu object will be configured but it won't have any Mambu info on it. Only when connected, the Mambu object will be initialized, here. Useful to POST several times the same Mambu object. You make a POST request over and over again by calling it's connect() method every time you wish. This init method will configure the response in to the attrs attribute each time. You may also wish to update the info on a previously initialized Mambu object and refresh it with what Mambu now has. Instead of building a new object, you just connect() again and it will be refreshed. * Iterable Mambu objects (lists) do not initialize here, the iterable Mambu object __init__ goes through each of its elements and then initializes with this code one by one. Please look at some Mambu iterable object code and pydoc for more details. """ self.attrs = attrs self.preprocess() self.convertDict2Attrs(*args, **kwargs) self.postprocess() try: for meth in kwargs['methods']: try: getattr(self,meth)() except Exception: pass except Exception: pass try: for propname,propval in kwargs['properties'].items(): setattr(self,propname,propval) except Exception: pass
python
def init(self, attrs={}, *args, **kwargs): """Default initialization from a dictionary responded by Mambu in to the elements of the Mambu object. It assings the response to attrs attribute and converts each of its elements from a string to an adequate python object: number, datetime, etc. Basically it stores the response on the attrs attribute, then runs some customizable preprocess method, then runs convertDict2Attrs method to convert the string elements to an adequate python object, then a customizable postprocess method. It also executes each method on the 'methods' attribute given on instantiation time, and sets new customizable 'properties' to the object. Why not on __init__? two reasons: * __init__ optionally connects to Mambu, if you don't connect to Mambu, the Mambu object will be configured but it won't have any Mambu info on it. Only when connected, the Mambu object will be initialized, here. Useful to POST several times the same Mambu object. You make a POST request over and over again by calling it's connect() method every time you wish. This init method will configure the response in to the attrs attribute each time. You may also wish to update the info on a previously initialized Mambu object and refresh it with what Mambu now has. Instead of building a new object, you just connect() again and it will be refreshed. * Iterable Mambu objects (lists) do not initialize here, the iterable Mambu object __init__ goes through each of its elements and then initializes with this code one by one. Please look at some Mambu iterable object code and pydoc for more details. """ self.attrs = attrs self.preprocess() self.convertDict2Attrs(*args, **kwargs) self.postprocess() try: for meth in kwargs['methods']: try: getattr(self,meth)() except Exception: pass except Exception: pass try: for propname,propval in kwargs['properties'].items(): setattr(self,propname,propval) except Exception: pass
[ "def", "init", "(", "self", ",", "attrs", "=", "{", "}", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "attrs", "=", "attrs", "self", ".", "preprocess", "(", ")", "self", ".", "convertDict2Attrs", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "postprocess", "(", ")", "try", ":", "for", "meth", "in", "kwargs", "[", "'methods'", "]", ":", "try", ":", "getattr", "(", "self", ",", "meth", ")", "(", ")", "except", "Exception", ":", "pass", "except", "Exception", ":", "pass", "try", ":", "for", "propname", ",", "propval", "in", "kwargs", "[", "'properties'", "]", ".", "items", "(", ")", ":", "setattr", "(", "self", ",", "propname", ",", "propval", ")", "except", "Exception", ":", "pass" ]
Default initialization from a dictionary responded by Mambu in to the elements of the Mambu object. It assings the response to attrs attribute and converts each of its elements from a string to an adequate python object: number, datetime, etc. Basically it stores the response on the attrs attribute, then runs some customizable preprocess method, then runs convertDict2Attrs method to convert the string elements to an adequate python object, then a customizable postprocess method. It also executes each method on the 'methods' attribute given on instantiation time, and sets new customizable 'properties' to the object. Why not on __init__? two reasons: * __init__ optionally connects to Mambu, if you don't connect to Mambu, the Mambu object will be configured but it won't have any Mambu info on it. Only when connected, the Mambu object will be initialized, here. Useful to POST several times the same Mambu object. You make a POST request over and over again by calling it's connect() method every time you wish. This init method will configure the response in to the attrs attribute each time. You may also wish to update the info on a previously initialized Mambu object and refresh it with what Mambu now has. Instead of building a new object, you just connect() again and it will be refreshed. * Iterable Mambu objects (lists) do not initialize here, the iterable Mambu object __init__ goes through each of its elements and then initializes with this code one by one. Please look at some Mambu iterable object code and pydoc for more details.
[ "Default", "initialization", "from", "a", "dictionary", "responded", "by", "Mambu" ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambustruct.py#L299-L355
train
jstitch/MambuPy
MambuPy/rest/mambustruct.py
MambuStruct.connect
def connect(self, *args, **kwargs): """Connect to Mambu, make the request to the REST API. If there's no urlfunc to use, nothing is done here. When done, initializes the attrs attribute of the Mambu object by calling the init method. Please refer to that code and pydoc for further information. Uses urllib module to connect. Since all Mambu REST API responses are json, uses json module to translate the response to a valid python object (dictionary or list). When Mambu returns a response with returnCode and returnStatus fields, it means something went wrong with the request, and a MambuError is thrown detailing the error given by Mambu itself. If you need to make a POST request, send a data argument to the new Mambu object. Provides to prevent errors due to using special chars on the request URL. See mambuutil.iriToUri() method pydoc for further info. Provides to prevent errors due to using special chars on the parameters of a POST request. See mambuutil.encoded_dict() method pydoc for further info. For every request done, the request counter Singleton is increased. Includes retry logic, to provide for a max number of connection failures with Mambu. If maximum retries are reached, MambuCommError is thrown. Includes pagination code. Mambu supports a max of 500 elements per response. Such an ugly detail is wrapped here so further pagination logic is not needed above here. You need a million elements? you got them by making several 500 elements requests later joined together in a sigle list. Just send a limit=0 (default) and that's it. .. todo:: improve raised exception messages. Sometimes MambuCommErrors are thrown due to reasons not always clear when catched down the road, but that perhaps may be noticed in here and aren't fully reported to the user. Specially serious on retries-MambuCommError situations (the except Exception that increases the retries counter is not saving the exception message, just retrying). .. todo:: what about using decorators for the retry and for the window logic? (https://www.oreilly.com/ideas/5-reasons-you-need-to-learn-to-write-python-decorators # Reusing impossible-to-reuse code) """ from copy import deepcopy if args: self.__args = deepcopy(args) if kwargs: for k,v in kwargs.items(): self.__kwargs[k] = deepcopy(v) jsresp = {} if not self.__urlfunc: return # Pagination window, Mambu restricts at most 500 elements in response offset = self.__offset window = True jsresp = {} while window: if not self.__limit or self.__limit > OUT_OF_BOUNDS_PAGINATION_LIMIT_VALUE: limit = OUT_OF_BOUNDS_PAGINATION_LIMIT_VALUE else: limit = self.__limit # Retry mechanism, for awful connections retries = 0 while retries < MambuStruct.RETRIES: try: # Basic authentication user = self.__kwargs.get('user', apiuser) pwd = self.__kwargs.get('pwd', apipwd) if self.__data: headers = {'content-type': 'application/json'} data = json.dumps(encoded_dict(self.__data)) url = iriToUri(self.__urlfunc(self.entid, limit=limit, offset=offset, *self.__args, **self.__kwargs)) # PATCH if self.__method=="PATCH": resp = requests.patch(url, data=data, headers=headers, auth=(user, pwd)) # POST else: resp = requests.post(url, data=data, headers=headers, auth=(user, pwd)) # GET else: url = iriToUri(self.__urlfunc(self.entid, limit=limit, offset=offset, *self.__args, **self.__kwargs)) resp = requests.get(url, auth=(user, pwd)) # Always count a new request when done! self.rc.add(datetime.now()) try: jsonresp = json.loads(resp.content) # Returns list: extend list for offset if type(jsonresp) == list: try: jsresp.extend(jsonresp) except AttributeError: # First window, forget that jsresp was a dict, turn it in to a list jsresp=jsonresp if len(jsonresp) < limit: window = False # Returns dict: in theory Mambu REST API doesn't takes limit/offset in to account else: jsresp = jsonresp window = False except ValueError as ex: # json.loads invalid data argument raise ex except Exception as ex: # any other json error raise MambuError("JSON Error: %s" % repr(ex)) # if we reach here, we're done and safe break except MambuError as merr: raise merr except requests.exceptions.RequestException: retries += 1 except Exception as ex: raise ex else: raise MambuCommError("ERROR I can't communicate with Mambu") # next window, moving offset... offset = offset + limit if self.__limit: self.__limit -= limit if self.__limit <= 0: window = False self.__limit = self.__inilimit try: if u'returnCode' in jsresp and u'returnStatus' in jsresp and jsresp[u'returnCode'] != 0: raise MambuError(jsresp[u'returnStatus']) except AttributeError: pass if self.__method != "PATCH": self.init(attrs=jsresp, *self.__args, **self.__kwargs)
python
def connect(self, *args, **kwargs): """Connect to Mambu, make the request to the REST API. If there's no urlfunc to use, nothing is done here. When done, initializes the attrs attribute of the Mambu object by calling the init method. Please refer to that code and pydoc for further information. Uses urllib module to connect. Since all Mambu REST API responses are json, uses json module to translate the response to a valid python object (dictionary or list). When Mambu returns a response with returnCode and returnStatus fields, it means something went wrong with the request, and a MambuError is thrown detailing the error given by Mambu itself. If you need to make a POST request, send a data argument to the new Mambu object. Provides to prevent errors due to using special chars on the request URL. See mambuutil.iriToUri() method pydoc for further info. Provides to prevent errors due to using special chars on the parameters of a POST request. See mambuutil.encoded_dict() method pydoc for further info. For every request done, the request counter Singleton is increased. Includes retry logic, to provide for a max number of connection failures with Mambu. If maximum retries are reached, MambuCommError is thrown. Includes pagination code. Mambu supports a max of 500 elements per response. Such an ugly detail is wrapped here so further pagination logic is not needed above here. You need a million elements? you got them by making several 500 elements requests later joined together in a sigle list. Just send a limit=0 (default) and that's it. .. todo:: improve raised exception messages. Sometimes MambuCommErrors are thrown due to reasons not always clear when catched down the road, but that perhaps may be noticed in here and aren't fully reported to the user. Specially serious on retries-MambuCommError situations (the except Exception that increases the retries counter is not saving the exception message, just retrying). .. todo:: what about using decorators for the retry and for the window logic? (https://www.oreilly.com/ideas/5-reasons-you-need-to-learn-to-write-python-decorators # Reusing impossible-to-reuse code) """ from copy import deepcopy if args: self.__args = deepcopy(args) if kwargs: for k,v in kwargs.items(): self.__kwargs[k] = deepcopy(v) jsresp = {} if not self.__urlfunc: return # Pagination window, Mambu restricts at most 500 elements in response offset = self.__offset window = True jsresp = {} while window: if not self.__limit or self.__limit > OUT_OF_BOUNDS_PAGINATION_LIMIT_VALUE: limit = OUT_OF_BOUNDS_PAGINATION_LIMIT_VALUE else: limit = self.__limit # Retry mechanism, for awful connections retries = 0 while retries < MambuStruct.RETRIES: try: # Basic authentication user = self.__kwargs.get('user', apiuser) pwd = self.__kwargs.get('pwd', apipwd) if self.__data: headers = {'content-type': 'application/json'} data = json.dumps(encoded_dict(self.__data)) url = iriToUri(self.__urlfunc(self.entid, limit=limit, offset=offset, *self.__args, **self.__kwargs)) # PATCH if self.__method=="PATCH": resp = requests.patch(url, data=data, headers=headers, auth=(user, pwd)) # POST else: resp = requests.post(url, data=data, headers=headers, auth=(user, pwd)) # GET else: url = iriToUri(self.__urlfunc(self.entid, limit=limit, offset=offset, *self.__args, **self.__kwargs)) resp = requests.get(url, auth=(user, pwd)) # Always count a new request when done! self.rc.add(datetime.now()) try: jsonresp = json.loads(resp.content) # Returns list: extend list for offset if type(jsonresp) == list: try: jsresp.extend(jsonresp) except AttributeError: # First window, forget that jsresp was a dict, turn it in to a list jsresp=jsonresp if len(jsonresp) < limit: window = False # Returns dict: in theory Mambu REST API doesn't takes limit/offset in to account else: jsresp = jsonresp window = False except ValueError as ex: # json.loads invalid data argument raise ex except Exception as ex: # any other json error raise MambuError("JSON Error: %s" % repr(ex)) # if we reach here, we're done and safe break except MambuError as merr: raise merr except requests.exceptions.RequestException: retries += 1 except Exception as ex: raise ex else: raise MambuCommError("ERROR I can't communicate with Mambu") # next window, moving offset... offset = offset + limit if self.__limit: self.__limit -= limit if self.__limit <= 0: window = False self.__limit = self.__inilimit try: if u'returnCode' in jsresp and u'returnStatus' in jsresp and jsresp[u'returnCode'] != 0: raise MambuError(jsresp[u'returnStatus']) except AttributeError: pass if self.__method != "PATCH": self.init(attrs=jsresp, *self.__args, **self.__kwargs)
[ "def", "connect", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "copy", "import", "deepcopy", "if", "args", ":", "self", ".", "__args", "=", "deepcopy", "(", "args", ")", "if", "kwargs", ":", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "self", ".", "__kwargs", "[", "k", "]", "=", "deepcopy", "(", "v", ")", "jsresp", "=", "{", "}", "if", "not", "self", ".", "__urlfunc", ":", "return", "# Pagination window, Mambu restricts at most 500 elements in response", "offset", "=", "self", ".", "__offset", "window", "=", "True", "jsresp", "=", "{", "}", "while", "window", ":", "if", "not", "self", ".", "__limit", "or", "self", ".", "__limit", ">", "OUT_OF_BOUNDS_PAGINATION_LIMIT_VALUE", ":", "limit", "=", "OUT_OF_BOUNDS_PAGINATION_LIMIT_VALUE", "else", ":", "limit", "=", "self", ".", "__limit", "# Retry mechanism, for awful connections", "retries", "=", "0", "while", "retries", "<", "MambuStruct", ".", "RETRIES", ":", "try", ":", "# Basic authentication", "user", "=", "self", ".", "__kwargs", ".", "get", "(", "'user'", ",", "apiuser", ")", "pwd", "=", "self", ".", "__kwargs", ".", "get", "(", "'pwd'", ",", "apipwd", ")", "if", "self", ".", "__data", ":", "headers", "=", "{", "'content-type'", ":", "'application/json'", "}", "data", "=", "json", ".", "dumps", "(", "encoded_dict", "(", "self", ".", "__data", ")", ")", "url", "=", "iriToUri", "(", "self", ".", "__urlfunc", "(", "self", ".", "entid", ",", "limit", "=", "limit", ",", "offset", "=", "offset", ",", "*", "self", ".", "__args", ",", "*", "*", "self", ".", "__kwargs", ")", ")", "# PATCH", "if", "self", ".", "__method", "==", "\"PATCH\"", ":", "resp", "=", "requests", ".", "patch", "(", "url", ",", "data", "=", "data", ",", "headers", "=", "headers", ",", "auth", "=", "(", "user", ",", "pwd", ")", ")", "# POST", "else", ":", "resp", "=", "requests", ".", "post", "(", "url", ",", "data", "=", "data", ",", "headers", "=", "headers", ",", "auth", "=", "(", "user", ",", "pwd", ")", ")", "# GET", "else", ":", "url", "=", "iriToUri", "(", "self", ".", "__urlfunc", "(", "self", ".", "entid", ",", "limit", "=", "limit", ",", "offset", "=", "offset", ",", "*", "self", ".", "__args", ",", "*", "*", "self", ".", "__kwargs", ")", ")", "resp", "=", "requests", ".", "get", "(", "url", ",", "auth", "=", "(", "user", ",", "pwd", ")", ")", "# Always count a new request when done!", "self", ".", "rc", ".", "add", "(", "datetime", ".", "now", "(", ")", ")", "try", ":", "jsonresp", "=", "json", ".", "loads", "(", "resp", ".", "content", ")", "# Returns list: extend list for offset", "if", "type", "(", "jsonresp", ")", "==", "list", ":", "try", ":", "jsresp", ".", "extend", "(", "jsonresp", ")", "except", "AttributeError", ":", "# First window, forget that jsresp was a dict, turn it in to a list", "jsresp", "=", "jsonresp", "if", "len", "(", "jsonresp", ")", "<", "limit", ":", "window", "=", "False", "# Returns dict: in theory Mambu REST API doesn't takes limit/offset in to account", "else", ":", "jsresp", "=", "jsonresp", "window", "=", "False", "except", "ValueError", "as", "ex", ":", "# json.loads invalid data argument", "raise", "ex", "except", "Exception", "as", "ex", ":", "# any other json error", "raise", "MambuError", "(", "\"JSON Error: %s\"", "%", "repr", "(", "ex", ")", ")", "# if we reach here, we're done and safe", "break", "except", "MambuError", "as", "merr", ":", "raise", "merr", "except", "requests", ".", "exceptions", ".", "RequestException", ":", "retries", "+=", "1", "except", "Exception", "as", "ex", ":", "raise", "ex", "else", ":", "raise", "MambuCommError", "(", "\"ERROR I can't communicate with Mambu\"", ")", "# next window, moving offset...", "offset", "=", "offset", "+", "limit", "if", "self", ".", "__limit", ":", "self", ".", "__limit", "-=", "limit", "if", "self", ".", "__limit", "<=", "0", ":", "window", "=", "False", "self", ".", "__limit", "=", "self", ".", "__inilimit", "try", ":", "if", "u'returnCode'", "in", "jsresp", "and", "u'returnStatus'", "in", "jsresp", "and", "jsresp", "[", "u'returnCode'", "]", "!=", "0", ":", "raise", "MambuError", "(", "jsresp", "[", "u'returnStatus'", "]", ")", "except", "AttributeError", ":", "pass", "if", "self", ".", "__method", "!=", "\"PATCH\"", ":", "self", ".", "init", "(", "attrs", "=", "jsresp", ",", "*", "self", ".", "__args", ",", "*", "*", "self", ".", "__kwargs", ")" ]
Connect to Mambu, make the request to the REST API. If there's no urlfunc to use, nothing is done here. When done, initializes the attrs attribute of the Mambu object by calling the init method. Please refer to that code and pydoc for further information. Uses urllib module to connect. Since all Mambu REST API responses are json, uses json module to translate the response to a valid python object (dictionary or list). When Mambu returns a response with returnCode and returnStatus fields, it means something went wrong with the request, and a MambuError is thrown detailing the error given by Mambu itself. If you need to make a POST request, send a data argument to the new Mambu object. Provides to prevent errors due to using special chars on the request URL. See mambuutil.iriToUri() method pydoc for further info. Provides to prevent errors due to using special chars on the parameters of a POST request. See mambuutil.encoded_dict() method pydoc for further info. For every request done, the request counter Singleton is increased. Includes retry logic, to provide for a max number of connection failures with Mambu. If maximum retries are reached, MambuCommError is thrown. Includes pagination code. Mambu supports a max of 500 elements per response. Such an ugly detail is wrapped here so further pagination logic is not needed above here. You need a million elements? you got them by making several 500 elements requests later joined together in a sigle list. Just send a limit=0 (default) and that's it. .. todo:: improve raised exception messages. Sometimes MambuCommErrors are thrown due to reasons not always clear when catched down the road, but that perhaps may be noticed in here and aren't fully reported to the user. Specially serious on retries-MambuCommError situations (the except Exception that increases the retries counter is not saving the exception message, just retrying). .. todo:: what about using decorators for the retry and for the window logic? (https://www.oreilly.com/ideas/5-reasons-you-need-to-learn-to-write-python-decorators # Reusing impossible-to-reuse code)
[ "Connect", "to", "Mambu", "make", "the", "request", "to", "the", "REST", "API", "." ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambustruct.py#L516-L664
train
jstitch/MambuPy
MambuPy/rest/mambustruct.py
MambuStruct.convertDict2Attrs
def convertDict2Attrs(self, *args, **kwargs): """Each element on the atttrs attribute gest converted to a proper python object, depending on type. Some default constantFields are left as is (strings), because they are better treated as strings. """ constantFields = ['id', 'groupName', 'name', 'homePhone', 'mobilePhone1', 'phoneNumber', 'postcode', 'emailAddress'] def convierte(data): """Recursively convert the fields on the data given to a python object.""" # Iterators, lists and dictionaries # Here comes the recursive calls! try: it = iter(data) if type(it) == type(iter({})): d = {} for k in it: if k in constantFields: d[k] = data[k] else: d[k] = convierte(data[k]) data = d if type(it) == type(iter([])): l = [] for e in it: l.append(convierte(e)) data = l except TypeError as terr: pass except Exception as ex: raise ex # Python built-in types: ints, floats, or even datetimes. If it # cannot convert it to a built-in type, leave it as string, or # as-is. There may be nested Mambu objects here! # This are the recursion base cases! try: d = int(data) if str(d) != data: # if string has trailing 0's, leave it as string, to not lose them return data return d except (TypeError, ValueError) as tverr: try: return float(data) except (TypeError, ValueError) as tverr: try: return self.util_dateFormat(data) except (TypeError, ValueError) as tverr: return data return data self.attrs = convierte(self.attrs)
python
def convertDict2Attrs(self, *args, **kwargs): """Each element on the atttrs attribute gest converted to a proper python object, depending on type. Some default constantFields are left as is (strings), because they are better treated as strings. """ constantFields = ['id', 'groupName', 'name', 'homePhone', 'mobilePhone1', 'phoneNumber', 'postcode', 'emailAddress'] def convierte(data): """Recursively convert the fields on the data given to a python object.""" # Iterators, lists and dictionaries # Here comes the recursive calls! try: it = iter(data) if type(it) == type(iter({})): d = {} for k in it: if k in constantFields: d[k] = data[k] else: d[k] = convierte(data[k]) data = d if type(it) == type(iter([])): l = [] for e in it: l.append(convierte(e)) data = l except TypeError as terr: pass except Exception as ex: raise ex # Python built-in types: ints, floats, or even datetimes. If it # cannot convert it to a built-in type, leave it as string, or # as-is. There may be nested Mambu objects here! # This are the recursion base cases! try: d = int(data) if str(d) != data: # if string has trailing 0's, leave it as string, to not lose them return data return d except (TypeError, ValueError) as tverr: try: return float(data) except (TypeError, ValueError) as tverr: try: return self.util_dateFormat(data) except (TypeError, ValueError) as tverr: return data return data self.attrs = convierte(self.attrs)
[ "def", "convertDict2Attrs", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "constantFields", "=", "[", "'id'", ",", "'groupName'", ",", "'name'", ",", "'homePhone'", ",", "'mobilePhone1'", ",", "'phoneNumber'", ",", "'postcode'", ",", "'emailAddress'", "]", "def", "convierte", "(", "data", ")", ":", "\"\"\"Recursively convert the fields on the data given to a python object.\"\"\"", "# Iterators, lists and dictionaries", "# Here comes the recursive calls!", "try", ":", "it", "=", "iter", "(", "data", ")", "if", "type", "(", "it", ")", "==", "type", "(", "iter", "(", "{", "}", ")", ")", ":", "d", "=", "{", "}", "for", "k", "in", "it", ":", "if", "k", "in", "constantFields", ":", "d", "[", "k", "]", "=", "data", "[", "k", "]", "else", ":", "d", "[", "k", "]", "=", "convierte", "(", "data", "[", "k", "]", ")", "data", "=", "d", "if", "type", "(", "it", ")", "==", "type", "(", "iter", "(", "[", "]", ")", ")", ":", "l", "=", "[", "]", "for", "e", "in", "it", ":", "l", ".", "append", "(", "convierte", "(", "e", ")", ")", "data", "=", "l", "except", "TypeError", "as", "terr", ":", "pass", "except", "Exception", "as", "ex", ":", "raise", "ex", "# Python built-in types: ints, floats, or even datetimes. If it", "# cannot convert it to a built-in type, leave it as string, or", "# as-is. There may be nested Mambu objects here!", "# This are the recursion base cases!", "try", ":", "d", "=", "int", "(", "data", ")", "if", "str", "(", "d", ")", "!=", "data", ":", "# if string has trailing 0's, leave it as string, to not lose them", "return", "data", "return", "d", "except", "(", "TypeError", ",", "ValueError", ")", "as", "tverr", ":", "try", ":", "return", "float", "(", "data", ")", "except", "(", "TypeError", ",", "ValueError", ")", "as", "tverr", ":", "try", ":", "return", "self", ".", "util_dateFormat", "(", "data", ")", "except", "(", "TypeError", ",", "ValueError", ")", "as", "tverr", ":", "return", "data", "return", "data", "self", ".", "attrs", "=", "convierte", "(", "self", ".", "attrs", ")" ]
Each element on the atttrs attribute gest converted to a proper python object, depending on type. Some default constantFields are left as is (strings), because they are better treated as strings.
[ "Each", "element", "on", "the", "atttrs", "attribute", "gest", "converted", "to", "a", "proper", "python", "object", "depending", "on", "type", "." ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambustruct.py#L739-L791
train
jstitch/MambuPy
MambuPy/rest/mambustruct.py
MambuStruct.util_dateFormat
def util_dateFormat(self, field, formato=None): """Converts a datetime field to a datetime using some specified format. What this really means is that, if specified format includes only for instance just year and month, day and further info gets ignored and the objects get a datetime with year and month, and day 1, hour 0, minute 0, etc. A useful format may be %Y%m%d, then the datetime objects effectively translates into date objects alone, with no relevant time information. PLEASE BE AWARE, that this may lose useful information for your datetimes from Mambu. Read this for why this may be a BAD idea: https://julien.danjou.info/blog/2015/python-and-timezones """ if not formato: try: formato = self.__formatoFecha except AttributeError: formato = "%Y-%m-%dT%H:%M:%S+0000" return datetime.strptime(datetime.strptime(field, "%Y-%m-%dT%H:%M:%S+0000").strftime(formato), formato)
python
def util_dateFormat(self, field, formato=None): """Converts a datetime field to a datetime using some specified format. What this really means is that, if specified format includes only for instance just year and month, day and further info gets ignored and the objects get a datetime with year and month, and day 1, hour 0, minute 0, etc. A useful format may be %Y%m%d, then the datetime objects effectively translates into date objects alone, with no relevant time information. PLEASE BE AWARE, that this may lose useful information for your datetimes from Mambu. Read this for why this may be a BAD idea: https://julien.danjou.info/blog/2015/python-and-timezones """ if not formato: try: formato = self.__formatoFecha except AttributeError: formato = "%Y-%m-%dT%H:%M:%S+0000" return datetime.strptime(datetime.strptime(field, "%Y-%m-%dT%H:%M:%S+0000").strftime(formato), formato)
[ "def", "util_dateFormat", "(", "self", ",", "field", ",", "formato", "=", "None", ")", ":", "if", "not", "formato", ":", "try", ":", "formato", "=", "self", ".", "__formatoFecha", "except", "AttributeError", ":", "formato", "=", "\"%Y-%m-%dT%H:%M:%S+0000\"", "return", "datetime", ".", "strptime", "(", "datetime", ".", "strptime", "(", "field", ",", "\"%Y-%m-%dT%H:%M:%S+0000\"", ")", ".", "strftime", "(", "formato", ")", ",", "formato", ")" ]
Converts a datetime field to a datetime using some specified format. What this really means is that, if specified format includes only for instance just year and month, day and further info gets ignored and the objects get a datetime with year and month, and day 1, hour 0, minute 0, etc. A useful format may be %Y%m%d, then the datetime objects effectively translates into date objects alone, with no relevant time information. PLEASE BE AWARE, that this may lose useful information for your datetimes from Mambu. Read this for why this may be a BAD idea: https://julien.danjou.info/blog/2015/python-and-timezones
[ "Converts", "a", "datetime", "field", "to", "a", "datetime", "using", "some", "specified", "format", "." ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambustruct.py#L793-L814
train
jstitch/MambuPy
MambuPy/rest/mambustruct.py
MambuStruct.create
def create(self, data, *args, **kwargs): """Creates an entity in Mambu This method must be implemented in child classes Args: data (dictionary): dictionary with data to send, this dictionary is specific for each Mambu entity """ # if module of the function is diferent from the module of the object # that means create is not implemented in child class if self.create.__func__.__module__ != self.__module__: raise Exception("Child method not implemented") self._MambuStruct__method = "POST" self._MambuStruct__data = data self.connect(*args, **kwargs) self._MambuStruct__method = "GET" self._MambuStruct__data = None
python
def create(self, data, *args, **kwargs): """Creates an entity in Mambu This method must be implemented in child classes Args: data (dictionary): dictionary with data to send, this dictionary is specific for each Mambu entity """ # if module of the function is diferent from the module of the object # that means create is not implemented in child class if self.create.__func__.__module__ != self.__module__: raise Exception("Child method not implemented") self._MambuStruct__method = "POST" self._MambuStruct__data = data self.connect(*args, **kwargs) self._MambuStruct__method = "GET" self._MambuStruct__data = None
[ "def", "create", "(", "self", ",", "data", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# if module of the function is diferent from the module of the object", "# that means create is not implemented in child class", "if", "self", ".", "create", ".", "__func__", ".", "__module__", "!=", "self", ".", "__module__", ":", "raise", "Exception", "(", "\"Child method not implemented\"", ")", "self", ".", "_MambuStruct__method", "=", "\"POST\"", "self", ".", "_MambuStruct__data", "=", "data", "self", ".", "connect", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "_MambuStruct__method", "=", "\"GET\"", "self", ".", "_MambuStruct__data", "=", "None" ]
Creates an entity in Mambu This method must be implemented in child classes Args: data (dictionary): dictionary with data to send, this dictionary is specific for each Mambu entity
[ "Creates", "an", "entity", "in", "Mambu" ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambustruct.py#L816-L834
train
ExoticObjects/django-sql-server-bcp
django_sql_server_bcp/__init__.py
BCPFormat.make
def make(self, cmd_args, db_args): ''' Runs bcp FORMAT command to create a format file that will assist in creating the bulk data file ''' with NamedTemporaryFile(delete=True) as f: format_file = f.name + '.bcp-format' format_args = cmd_args + ['format', NULL_FILE, '-c', '-f', format_file, '-t,'] + db_args _run_cmd(format_args) self.load(format_file) return format_file
python
def make(self, cmd_args, db_args): ''' Runs bcp FORMAT command to create a format file that will assist in creating the bulk data file ''' with NamedTemporaryFile(delete=True) as f: format_file = f.name + '.bcp-format' format_args = cmd_args + ['format', NULL_FILE, '-c', '-f', format_file, '-t,'] + db_args _run_cmd(format_args) self.load(format_file) return format_file
[ "def", "make", "(", "self", ",", "cmd_args", ",", "db_args", ")", ":", "with", "NamedTemporaryFile", "(", "delete", "=", "True", ")", "as", "f", ":", "format_file", "=", "f", ".", "name", "+", "'.bcp-format'", "format_args", "=", "cmd_args", "+", "[", "'format'", ",", "NULL_FILE", ",", "'-c'", ",", "'-f'", ",", "format_file", ",", "'-t,'", "]", "+", "db_args", "_run_cmd", "(", "format_args", ")", "self", ".", "load", "(", "format_file", ")", "return", "format_file" ]
Runs bcp FORMAT command to create a format file that will assist in creating the bulk data file
[ "Runs", "bcp", "FORMAT", "command", "to", "create", "a", "format", "file", "that", "will", "assist", "in", "creating", "the", "bulk", "data", "file" ]
3bfc593a18091cf837a9c31cbbe7025ecc5e3226
https://github.com/ExoticObjects/django-sql-server-bcp/blob/3bfc593a18091cf837a9c31cbbe7025ecc5e3226/django_sql_server_bcp/__init__.py#L110-L119
train
ExoticObjects/django-sql-server-bcp
django_sql_server_bcp/__init__.py
BCPFormat.load
def load(self, filename=None): ''' Reads a non-XML bcp FORMAT file and parses it into fields list used for creating bulk data file ''' fields = [] with open(filename, 'r') as f: format_data = f.read().strip() lines = format_data.split('\n') self._sql_version = lines.pop(0) self._num_fields = int(lines.pop(0)) for line in lines: # Get rid of mulitple spaces line = re.sub(' +', ' ', line.strip()) row_format = BCPFormatRow(line.split(' ')) fields.append(row_format) self.fields = fields self.filename = filename
python
def load(self, filename=None): ''' Reads a non-XML bcp FORMAT file and parses it into fields list used for creating bulk data file ''' fields = [] with open(filename, 'r') as f: format_data = f.read().strip() lines = format_data.split('\n') self._sql_version = lines.pop(0) self._num_fields = int(lines.pop(0)) for line in lines: # Get rid of mulitple spaces line = re.sub(' +', ' ', line.strip()) row_format = BCPFormatRow(line.split(' ')) fields.append(row_format) self.fields = fields self.filename = filename
[ "def", "load", "(", "self", ",", "filename", "=", "None", ")", ":", "fields", "=", "[", "]", "with", "open", "(", "filename", ",", "'r'", ")", "as", "f", ":", "format_data", "=", "f", ".", "read", "(", ")", ".", "strip", "(", ")", "lines", "=", "format_data", ".", "split", "(", "'\\n'", ")", "self", ".", "_sql_version", "=", "lines", ".", "pop", "(", "0", ")", "self", ".", "_num_fields", "=", "int", "(", "lines", ".", "pop", "(", "0", ")", ")", "for", "line", "in", "lines", ":", "# Get rid of mulitple spaces", "line", "=", "re", ".", "sub", "(", "' +'", ",", "' '", ",", "line", ".", "strip", "(", ")", ")", "row_format", "=", "BCPFormatRow", "(", "line", ".", "split", "(", "' '", ")", ")", "fields", ".", "append", "(", "row_format", ")", "self", ".", "fields", "=", "fields", "self", ".", "filename", "=", "filename" ]
Reads a non-XML bcp FORMAT file and parses it into fields list used for creating bulk data file
[ "Reads", "a", "non", "-", "XML", "bcp", "FORMAT", "file", "and", "parses", "it", "into", "fields", "list", "used", "for", "creating", "bulk", "data", "file" ]
3bfc593a18091cf837a9c31cbbe7025ecc5e3226
https://github.com/ExoticObjects/django-sql-server-bcp/blob/3bfc593a18091cf837a9c31cbbe7025ecc5e3226/django_sql_server_bcp/__init__.py#L121-L140
train
transifex/transifex-python-library
txlib/api/resources.py
Resource.retrieve_content
def retrieve_content(self): """Retrieve the content of a resource.""" path = self._construct_path_to_source_content() res = self._http.get(path) self._populated_fields['content'] = res['content'] return res['content']
python
def retrieve_content(self): """Retrieve the content of a resource.""" path = self._construct_path_to_source_content() res = self._http.get(path) self._populated_fields['content'] = res['content'] return res['content']
[ "def", "retrieve_content", "(", "self", ")", ":", "path", "=", "self", ".", "_construct_path_to_source_content", "(", ")", "res", "=", "self", ".", "_http", ".", "get", "(", "path", ")", "self", ".", "_populated_fields", "[", "'content'", "]", "=", "res", "[", "'content'", "]", "return", "res", "[", "'content'", "]" ]
Retrieve the content of a resource.
[ "Retrieve", "the", "content", "of", "a", "resource", "." ]
9fea86b718973de35ccca6d54bd1f445c9632406
https://github.com/transifex/transifex-python-library/blob/9fea86b718973de35ccca6d54bd1f445c9632406/txlib/api/resources.py#L27-L32
train
transifex/transifex-python-library
txlib/api/resources.py
Resource._update
def _update(self, **kwargs): """Use separate URL for updating the source file.""" if 'content' in kwargs: content = kwargs.pop('content') path = self._construct_path_to_source_content() self._http.put(path, json.dumps({'content': content})) super(Resource, self)._update(**kwargs)
python
def _update(self, **kwargs): """Use separate URL for updating the source file.""" if 'content' in kwargs: content = kwargs.pop('content') path = self._construct_path_to_source_content() self._http.put(path, json.dumps({'content': content})) super(Resource, self)._update(**kwargs)
[ "def", "_update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "'content'", "in", "kwargs", ":", "content", "=", "kwargs", ".", "pop", "(", "'content'", ")", "path", "=", "self", ".", "_construct_path_to_source_content", "(", ")", "self", ".", "_http", ".", "put", "(", "path", ",", "json", ".", "dumps", "(", "{", "'content'", ":", "content", "}", ")", ")", "super", "(", "Resource", ",", "self", ")", ".", "_update", "(", "*", "*", "kwargs", ")" ]
Use separate URL for updating the source file.
[ "Use", "separate", "URL", "for", "updating", "the", "source", "file", "." ]
9fea86b718973de35ccca6d54bd1f445c9632406
https://github.com/transifex/transifex-python-library/blob/9fea86b718973de35ccca6d54bd1f445c9632406/txlib/api/resources.py#L34-L40
train
cloudmesh-cmd3/cmd3
fabfile/clean.py
all
def all(): """clean the dis and uninstall cloudmesh""" dir() cmd3() banner("CLEAN PREVIOUS CLOUDMESH INSTALLS") r = int(local("pip freeze |fgrep cloudmesh | wc -l", capture=True)) while r > 0: local('echo "y\n" | pip uninstall cloudmesh') r = int(local("pip freeze |fgrep cloudmesh | wc -l", capture=True))
python
def all(): """clean the dis and uninstall cloudmesh""" dir() cmd3() banner("CLEAN PREVIOUS CLOUDMESH INSTALLS") r = int(local("pip freeze |fgrep cloudmesh | wc -l", capture=True)) while r > 0: local('echo "y\n" | pip uninstall cloudmesh') r = int(local("pip freeze |fgrep cloudmesh | wc -l", capture=True))
[ "def", "all", "(", ")", ":", "dir", "(", ")", "cmd3", "(", ")", "banner", "(", "\"CLEAN PREVIOUS CLOUDMESH INSTALLS\"", ")", "r", "=", "int", "(", "local", "(", "\"pip freeze |fgrep cloudmesh | wc -l\"", ",", "capture", "=", "True", ")", ")", "while", "r", ">", "0", ":", "local", "(", "'echo \"y\\n\" | pip uninstall cloudmesh'", ")", "r", "=", "int", "(", "local", "(", "\"pip freeze |fgrep cloudmesh | wc -l\"", ",", "capture", "=", "True", ")", ")" ]
clean the dis and uninstall cloudmesh
[ "clean", "the", "dis", "and", "uninstall", "cloudmesh" ]
92e33c96032fd3921f159198a0e57917c4dc34ed
https://github.com/cloudmesh-cmd3/cmd3/blob/92e33c96032fd3921f159198a0e57917c4dc34ed/fabfile/clean.py#L24-L32
train
frostming/marko
marko/inline.py
InlineElement.find
def find(cls, text): """This method should return an iterable containing matches of this element.""" if isinstance(cls.pattern, string_types): cls.pattern = re.compile(cls.pattern) return cls.pattern.finditer(text)
python
def find(cls, text): """This method should return an iterable containing matches of this element.""" if isinstance(cls.pattern, string_types): cls.pattern = re.compile(cls.pattern) return cls.pattern.finditer(text)
[ "def", "find", "(", "cls", ",", "text", ")", ":", "if", "isinstance", "(", "cls", ".", "pattern", ",", "string_types", ")", ":", "cls", ".", "pattern", "=", "re", ".", "compile", "(", "cls", ".", "pattern", ")", "return", "cls", ".", "pattern", ".", "finditer", "(", "text", ")" ]
This method should return an iterable containing matches of this element.
[ "This", "method", "should", "return", "an", "iterable", "containing", "matches", "of", "this", "element", "." ]
1cd030b665fa37bad1f8b3a25a89ce1a7c491dde
https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/inline.py#L39-L43
train
youversion/crony
crony/crony.py
main
def main(): """Entry point for running crony. 1. If a --cronitor/-c is specified, a "run" ping is sent to cronitor. 2. The argument string passed to crony is ran. 3. Next steps depend on the exit code of the command ran. * If the exit status is 0 and a --cronitor/-c is specified, a "complete" ping is sent to cronitor. * If the exit status is greater than 0, a message is sent to Sentry with the output captured from the script's exit. * If the exit status is great than 0 and --cronitor/-c is specified, a "fail" ping is sent to cronitor. """ parser = argparse.ArgumentParser( description='Monitor your crons with cronitor.io & sentry.io', epilog='https://github.com/youversion/crony', prog='crony' ) parser.add_argument('-c', '--cronitor', action='store', help='Cronitor link identifier. This can be found in your Cronitor unique' ' ping URL right after https://cronitor.link/') parser.add_argument('-e', '--venv', action='store', help='Path to virtualenv to source before running script. May be passed' ' as an argument or loaded from an environment variable or config file.') parser.add_argument('-d', '--cd', action='store', help='If the script needs ran in a specific directory, than can be passed' ' or cd can be ran prior to running crony.') parser.add_argument('-l', '--log', action='store', help='Log file to direct stdout of script run to. Can be passed or ' 'defined in config file with "log_file"') parser.add_argument('-o', '--config', action='store', help='Path to a crony config file to use.') parser.add_argument('-p', '--path', action='store', help='Paths to append to the PATH environment variable before running. ' ' Can be passed as an argument or loaded from config file.') parser.add_argument('-s', '--dsn', action='store', help='Sentry DSN. May be passed or loaded from an environment variable ' 'or a config file.') parser.add_argument('-t', '--timeout', action='store', default=10, help='Timeout to use when' ' sending requests to Cronitor', type=int) parser.add_argument('-v', '--verbose', action='store_true', help='Increase level of verbosity' ' output by crony') parser.add_argument('--version', action='store_true', help='Output crony version # and exit') parser.add_argument('cmd', nargs=argparse.REMAINDER, help='Command to run and monitor') cc = CommandCenter(parser.parse_args()) sys.exit(cc.log(*cc.func()))
python
def main(): """Entry point for running crony. 1. If a --cronitor/-c is specified, a "run" ping is sent to cronitor. 2. The argument string passed to crony is ran. 3. Next steps depend on the exit code of the command ran. * If the exit status is 0 and a --cronitor/-c is specified, a "complete" ping is sent to cronitor. * If the exit status is greater than 0, a message is sent to Sentry with the output captured from the script's exit. * If the exit status is great than 0 and --cronitor/-c is specified, a "fail" ping is sent to cronitor. """ parser = argparse.ArgumentParser( description='Monitor your crons with cronitor.io & sentry.io', epilog='https://github.com/youversion/crony', prog='crony' ) parser.add_argument('-c', '--cronitor', action='store', help='Cronitor link identifier. This can be found in your Cronitor unique' ' ping URL right after https://cronitor.link/') parser.add_argument('-e', '--venv', action='store', help='Path to virtualenv to source before running script. May be passed' ' as an argument or loaded from an environment variable or config file.') parser.add_argument('-d', '--cd', action='store', help='If the script needs ran in a specific directory, than can be passed' ' or cd can be ran prior to running crony.') parser.add_argument('-l', '--log', action='store', help='Log file to direct stdout of script run to. Can be passed or ' 'defined in config file with "log_file"') parser.add_argument('-o', '--config', action='store', help='Path to a crony config file to use.') parser.add_argument('-p', '--path', action='store', help='Paths to append to the PATH environment variable before running. ' ' Can be passed as an argument or loaded from config file.') parser.add_argument('-s', '--dsn', action='store', help='Sentry DSN. May be passed or loaded from an environment variable ' 'or a config file.') parser.add_argument('-t', '--timeout', action='store', default=10, help='Timeout to use when' ' sending requests to Cronitor', type=int) parser.add_argument('-v', '--verbose', action='store_true', help='Increase level of verbosity' ' output by crony') parser.add_argument('--version', action='store_true', help='Output crony version # and exit') parser.add_argument('cmd', nargs=argparse.REMAINDER, help='Command to run and monitor') cc = CommandCenter(parser.parse_args()) sys.exit(cc.log(*cc.func()))
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Monitor your crons with cronitor.io & sentry.io'", ",", "epilog", "=", "'https://github.com/youversion/crony'", ",", "prog", "=", "'crony'", ")", "parser", ".", "add_argument", "(", "'-c'", ",", "'--cronitor'", ",", "action", "=", "'store'", ",", "help", "=", "'Cronitor link identifier. This can be found in your Cronitor unique'", "' ping URL right after https://cronitor.link/'", ")", "parser", ".", "add_argument", "(", "'-e'", ",", "'--venv'", ",", "action", "=", "'store'", ",", "help", "=", "'Path to virtualenv to source before running script. May be passed'", "' as an argument or loaded from an environment variable or config file.'", ")", "parser", ".", "add_argument", "(", "'-d'", ",", "'--cd'", ",", "action", "=", "'store'", ",", "help", "=", "'If the script needs ran in a specific directory, than can be passed'", "' or cd can be ran prior to running crony.'", ")", "parser", ".", "add_argument", "(", "'-l'", ",", "'--log'", ",", "action", "=", "'store'", ",", "help", "=", "'Log file to direct stdout of script run to. Can be passed or '", "'defined in config file with \"log_file\"'", ")", "parser", ".", "add_argument", "(", "'-o'", ",", "'--config'", ",", "action", "=", "'store'", ",", "help", "=", "'Path to a crony config file to use.'", ")", "parser", ".", "add_argument", "(", "'-p'", ",", "'--path'", ",", "action", "=", "'store'", ",", "help", "=", "'Paths to append to the PATH environment variable before running. '", "' Can be passed as an argument or loaded from config file.'", ")", "parser", ".", "add_argument", "(", "'-s'", ",", "'--dsn'", ",", "action", "=", "'store'", ",", "help", "=", "'Sentry DSN. May be passed or loaded from an environment variable '", "'or a config file.'", ")", "parser", ".", "add_argument", "(", "'-t'", ",", "'--timeout'", ",", "action", "=", "'store'", ",", "default", "=", "10", ",", "help", "=", "'Timeout to use when'", "' sending requests to Cronitor'", ",", "type", "=", "int", ")", "parser", ".", "add_argument", "(", "'-v'", ",", "'--verbose'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Increase level of verbosity'", "' output by crony'", ")", "parser", ".", "add_argument", "(", "'--version'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Output crony version # and exit'", ")", "parser", ".", "add_argument", "(", "'cmd'", ",", "nargs", "=", "argparse", ".", "REMAINDER", ",", "help", "=", "'Command to run and monitor'", ")", "cc", "=", "CommandCenter", "(", "parser", ".", "parse_args", "(", ")", ")", "sys", ".", "exit", "(", "cc", ".", "log", "(", "*", "cc", ".", "func", "(", ")", ")", ")" ]
Entry point for running crony. 1. If a --cronitor/-c is specified, a "run" ping is sent to cronitor. 2. The argument string passed to crony is ran. 3. Next steps depend on the exit code of the command ran. * If the exit status is 0 and a --cronitor/-c is specified, a "complete" ping is sent to cronitor. * If the exit status is greater than 0, a message is sent to Sentry with the output captured from the script's exit. * If the exit status is great than 0 and --cronitor/-c is specified, a "fail" ping is sent to cronitor.
[ "Entry", "point", "for", "running", "crony", "." ]
c93d14b809a2e878f1b9d6d53d5a04947896583b
https://github.com/youversion/crony/blob/c93d14b809a2e878f1b9d6d53d5a04947896583b/crony/crony.py#L232-L290
train
youversion/crony
crony/crony.py
CommandCenter.cronitor
def cronitor(self): """Wrap run with requests to cronitor.""" url = f'https://cronitor.link/{self.opts.cronitor}/{{}}' try: run_url = url.format('run') self.logger.debug(f'Pinging {run_url}') requests.get(run_url, timeout=self.opts.timeout) except requests.exceptions.RequestException as e: self.logger.exception(e) # Cronitor may be having an outage, but we still want to run our stuff output, exit_status = self.run() endpoint = 'complete' if exit_status == 0 else 'fail' try: ping_url = url.format(endpoint) self.logger.debug('Pinging {}'.format(ping_url)) requests.get(ping_url, timeout=self.opts.timeout) except requests.exceptions.RequestException as e: self.logger.exception(e) return output, exit_status
python
def cronitor(self): """Wrap run with requests to cronitor.""" url = f'https://cronitor.link/{self.opts.cronitor}/{{}}' try: run_url = url.format('run') self.logger.debug(f'Pinging {run_url}') requests.get(run_url, timeout=self.opts.timeout) except requests.exceptions.RequestException as e: self.logger.exception(e) # Cronitor may be having an outage, but we still want to run our stuff output, exit_status = self.run() endpoint = 'complete' if exit_status == 0 else 'fail' try: ping_url = url.format(endpoint) self.logger.debug('Pinging {}'.format(ping_url)) requests.get(ping_url, timeout=self.opts.timeout) except requests.exceptions.RequestException as e: self.logger.exception(e) return output, exit_status
[ "def", "cronitor", "(", "self", ")", ":", "url", "=", "f'https://cronitor.link/{self.opts.cronitor}/{{}}'", "try", ":", "run_url", "=", "url", ".", "format", "(", "'run'", ")", "self", ".", "logger", ".", "debug", "(", "f'Pinging {run_url}'", ")", "requests", ".", "get", "(", "run_url", ",", "timeout", "=", "self", ".", "opts", ".", "timeout", ")", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "e", ":", "self", ".", "logger", ".", "exception", "(", "e", ")", "# Cronitor may be having an outage, but we still want to run our stuff", "output", ",", "exit_status", "=", "self", ".", "run", "(", ")", "endpoint", "=", "'complete'", "if", "exit_status", "==", "0", "else", "'fail'", "try", ":", "ping_url", "=", "url", ".", "format", "(", "endpoint", ")", "self", ".", "logger", ".", "debug", "(", "'Pinging {}'", ".", "format", "(", "ping_url", ")", ")", "requests", ".", "get", "(", "ping_url", ",", "timeout", "=", "self", ".", "opts", ".", "timeout", ")", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "e", ":", "self", ".", "logger", ".", "exception", "(", "e", ")", "return", "output", ",", "exit_status" ]
Wrap run with requests to cronitor.
[ "Wrap", "run", "with", "requests", "to", "cronitor", "." ]
c93d14b809a2e878f1b9d6d53d5a04947896583b
https://github.com/youversion/crony/blob/c93d14b809a2e878f1b9d6d53d5a04947896583b/crony/crony.py#L76-L100
train
youversion/crony
crony/crony.py
CommandCenter.load_config
def load_config(self, custom_config): """Attempt to load config from file. If the command specified a --config parameter, then load that config file. Otherwise, the user's home directory takes precedence over a system wide config. Config file in the user's dir should be named ".cronyrc". System wide config should be located at "/etc/crony.conf" """ self.config = configparser.ConfigParser() if custom_config: self.config.read(custom_config) return f'Loading config from file {custom_config}.' home = os.path.expanduser('~{}'.format(getpass.getuser())) home_conf_file = os.path.join(home, '.cronyrc') system_conf_file = '/etc/crony.conf' conf_precedence = (home_conf_file, system_conf_file) for conf_file in conf_precedence: if os.path.exists(conf_file): self.config.read(conf_file) return f'Loading config from file {conf_file}.' self.config['crony'] = {} return 'No config file found.'
python
def load_config(self, custom_config): """Attempt to load config from file. If the command specified a --config parameter, then load that config file. Otherwise, the user's home directory takes precedence over a system wide config. Config file in the user's dir should be named ".cronyrc". System wide config should be located at "/etc/crony.conf" """ self.config = configparser.ConfigParser() if custom_config: self.config.read(custom_config) return f'Loading config from file {custom_config}.' home = os.path.expanduser('~{}'.format(getpass.getuser())) home_conf_file = os.path.join(home, '.cronyrc') system_conf_file = '/etc/crony.conf' conf_precedence = (home_conf_file, system_conf_file) for conf_file in conf_precedence: if os.path.exists(conf_file): self.config.read(conf_file) return f'Loading config from file {conf_file}.' self.config['crony'] = {} return 'No config file found.'
[ "def", "load_config", "(", "self", ",", "custom_config", ")", ":", "self", ".", "config", "=", "configparser", ".", "ConfigParser", "(", ")", "if", "custom_config", ":", "self", ".", "config", ".", "read", "(", "custom_config", ")", "return", "f'Loading config from file {custom_config}.'", "home", "=", "os", ".", "path", ".", "expanduser", "(", "'~{}'", ".", "format", "(", "getpass", ".", "getuser", "(", ")", ")", ")", "home_conf_file", "=", "os", ".", "path", ".", "join", "(", "home", ",", "'.cronyrc'", ")", "system_conf_file", "=", "'/etc/crony.conf'", "conf_precedence", "=", "(", "home_conf_file", ",", "system_conf_file", ")", "for", "conf_file", "in", "conf_precedence", ":", "if", "os", ".", "path", ".", "exists", "(", "conf_file", ")", ":", "self", ".", "config", ".", "read", "(", "conf_file", ")", "return", "f'Loading config from file {conf_file}.'", "self", ".", "config", "[", "'crony'", "]", "=", "{", "}", "return", "'No config file found.'" ]
Attempt to load config from file. If the command specified a --config parameter, then load that config file. Otherwise, the user's home directory takes precedence over a system wide config. Config file in the user's dir should be named ".cronyrc". System wide config should be located at "/etc/crony.conf"
[ "Attempt", "to", "load", "config", "from", "file", "." ]
c93d14b809a2e878f1b9d6d53d5a04947896583b
https://github.com/youversion/crony/blob/c93d14b809a2e878f1b9d6d53d5a04947896583b/crony/crony.py#L102-L127
train
youversion/crony
crony/crony.py
CommandCenter.log
def log(self, output, exit_status): """Log given CompletedProcess and return exit status code.""" if exit_status != 0: self.logger.error(f'Error running command! Exit status: {exit_status}, {output}') return exit_status
python
def log(self, output, exit_status): """Log given CompletedProcess and return exit status code.""" if exit_status != 0: self.logger.error(f'Error running command! Exit status: {exit_status}, {output}') return exit_status
[ "def", "log", "(", "self", ",", "output", ",", "exit_status", ")", ":", "if", "exit_status", "!=", "0", ":", "self", ".", "logger", ".", "error", "(", "f'Error running command! Exit status: {exit_status}, {output}'", ")", "return", "exit_status" ]
Log given CompletedProcess and return exit status code.
[ "Log", "given", "CompletedProcess", "and", "return", "exit", "status", "code", "." ]
c93d14b809a2e878f1b9d6d53d5a04947896583b
https://github.com/youversion/crony/blob/c93d14b809a2e878f1b9d6d53d5a04947896583b/crony/crony.py#L129-L134
train
youversion/crony
crony/crony.py
CommandCenter.run
def run(self): """Run command and report errors to Sentry.""" self.logger.debug(f'Running command: {self.cmd}') def execute(cmd): output = "" popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, shell=True) for stdout_line in iter(popen.stdout.readline, ""): stdout_line = stdout_line.strip('\n') output += stdout_line yield stdout_line popen.stdout.close() return_code = popen.wait() if return_code: raise subprocess.CalledProcessError(return_code, cmd, output) try: for out in execute(self.cmd): self.logger.info(out) return "", 0 except subprocess.CalledProcessError as e: return e.output, e.returncode
python
def run(self): """Run command and report errors to Sentry.""" self.logger.debug(f'Running command: {self.cmd}') def execute(cmd): output = "" popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, shell=True) for stdout_line in iter(popen.stdout.readline, ""): stdout_line = stdout_line.strip('\n') output += stdout_line yield stdout_line popen.stdout.close() return_code = popen.wait() if return_code: raise subprocess.CalledProcessError(return_code, cmd, output) try: for out in execute(self.cmd): self.logger.info(out) return "", 0 except subprocess.CalledProcessError as e: return e.output, e.returncode
[ "def", "run", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "f'Running command: {self.cmd}'", ")", "def", "execute", "(", "cmd", ")", ":", "output", "=", "\"\"", "popen", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "universal_newlines", "=", "True", ",", "shell", "=", "True", ")", "for", "stdout_line", "in", "iter", "(", "popen", ".", "stdout", ".", "readline", ",", "\"\"", ")", ":", "stdout_line", "=", "stdout_line", ".", "strip", "(", "'\\n'", ")", "output", "+=", "stdout_line", "yield", "stdout_line", "popen", ".", "stdout", ".", "close", "(", ")", "return_code", "=", "popen", ".", "wait", "(", ")", "if", "return_code", ":", "raise", "subprocess", ".", "CalledProcessError", "(", "return_code", ",", "cmd", ",", "output", ")", "try", ":", "for", "out", "in", "execute", "(", "self", ".", "cmd", ")", ":", "self", ".", "logger", ".", "info", "(", "out", ")", "return", "\"\"", ",", "0", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "return", "e", ".", "output", ",", "e", ".", "returncode" ]
Run command and report errors to Sentry.
[ "Run", "command", "and", "report", "errors", "to", "Sentry", "." ]
c93d14b809a2e878f1b9d6d53d5a04947896583b
https://github.com/youversion/crony/blob/c93d14b809a2e878f1b9d6d53d5a04947896583b/crony/crony.py#L136-L158
train
youversion/crony
crony/crony.py
CommandCenter.setup_dir
def setup_dir(self): """Change directory for script if necessary.""" cd = self.opts.cd or self.config['crony'].get('directory') if cd: self.logger.debug(f'Adding cd to {cd}') self.cmd = f'cd {cd} && {self.cmd}'
python
def setup_dir(self): """Change directory for script if necessary.""" cd = self.opts.cd or self.config['crony'].get('directory') if cd: self.logger.debug(f'Adding cd to {cd}') self.cmd = f'cd {cd} && {self.cmd}'
[ "def", "setup_dir", "(", "self", ")", ":", "cd", "=", "self", ".", "opts", ".", "cd", "or", "self", ".", "config", "[", "'crony'", "]", ".", "get", "(", "'directory'", ")", "if", "cd", ":", "self", ".", "logger", ".", "debug", "(", "f'Adding cd to {cd}'", ")", "self", ".", "cmd", "=", "f'cd {cd} && {self.cmd}'" ]
Change directory for script if necessary.
[ "Change", "directory", "for", "script", "if", "necessary", "." ]
c93d14b809a2e878f1b9d6d53d5a04947896583b
https://github.com/youversion/crony/blob/c93d14b809a2e878f1b9d6d53d5a04947896583b/crony/crony.py#L160-L165
train
youversion/crony
crony/crony.py
CommandCenter.setup_logging
def setup_logging(self): """Setup python logging handler.""" date_format = '%Y-%m-%dT%H:%M:%S' log_format = '%(asctime)s %(levelname)s: %(message)s' if self.opts.verbose: lvl = logging.DEBUG else: lvl = logging.INFO # Requests is a bit chatty logging.getLogger('requests').setLevel('WARNING') self.logger.setLevel(lvl) stdout = logging.StreamHandler(sys.stdout) stdout.setLevel(lvl) formatter = logging.Formatter(log_format, date_format) stdout.setFormatter(formatter) self.logger.addHandler(stdout) # Decided not to use stderr # stderr = logging.StreamHandler(sys.stderr) # stderr.setLevel(logging.ERROR) # Error and above go to both stdout & stderr # formatter = logging.Formatter(log_format, date_format) # stderr.setFormatter(formatter) # self.logger.addHandler(stderr) log = self.opts.log or self.config['crony'].get('log_file') if log: logfile = logging.FileHandler(log) logfile.setLevel(lvl) formatter = logging.Formatter(log_format, date_format) logfile.setFormatter(formatter) self.logger.addHandler(logfile) if self.sentry_client: sentry = SentryHandler(self.sentry_client) sentry.setLevel(logging.ERROR) self.logger.addHandler(sentry) self.logger.debug('Logging setup complete.')
python
def setup_logging(self): """Setup python logging handler.""" date_format = '%Y-%m-%dT%H:%M:%S' log_format = '%(asctime)s %(levelname)s: %(message)s' if self.opts.verbose: lvl = logging.DEBUG else: lvl = logging.INFO # Requests is a bit chatty logging.getLogger('requests').setLevel('WARNING') self.logger.setLevel(lvl) stdout = logging.StreamHandler(sys.stdout) stdout.setLevel(lvl) formatter = logging.Formatter(log_format, date_format) stdout.setFormatter(formatter) self.logger.addHandler(stdout) # Decided not to use stderr # stderr = logging.StreamHandler(sys.stderr) # stderr.setLevel(logging.ERROR) # Error and above go to both stdout & stderr # formatter = logging.Formatter(log_format, date_format) # stderr.setFormatter(formatter) # self.logger.addHandler(stderr) log = self.opts.log or self.config['crony'].get('log_file') if log: logfile = logging.FileHandler(log) logfile.setLevel(lvl) formatter = logging.Formatter(log_format, date_format) logfile.setFormatter(formatter) self.logger.addHandler(logfile) if self.sentry_client: sentry = SentryHandler(self.sentry_client) sentry.setLevel(logging.ERROR) self.logger.addHandler(sentry) self.logger.debug('Logging setup complete.')
[ "def", "setup_logging", "(", "self", ")", ":", "date_format", "=", "'%Y-%m-%dT%H:%M:%S'", "log_format", "=", "'%(asctime)s %(levelname)s: %(message)s'", "if", "self", ".", "opts", ".", "verbose", ":", "lvl", "=", "logging", ".", "DEBUG", "else", ":", "lvl", "=", "logging", ".", "INFO", "# Requests is a bit chatty", "logging", ".", "getLogger", "(", "'requests'", ")", ".", "setLevel", "(", "'WARNING'", ")", "self", ".", "logger", ".", "setLevel", "(", "lvl", ")", "stdout", "=", "logging", ".", "StreamHandler", "(", "sys", ".", "stdout", ")", "stdout", ".", "setLevel", "(", "lvl", ")", "formatter", "=", "logging", ".", "Formatter", "(", "log_format", ",", "date_format", ")", "stdout", ".", "setFormatter", "(", "formatter", ")", "self", ".", "logger", ".", "addHandler", "(", "stdout", ")", "# Decided not to use stderr", "# stderr = logging.StreamHandler(sys.stderr)", "# stderr.setLevel(logging.ERROR) # Error and above go to both stdout & stderr", "# formatter = logging.Formatter(log_format, date_format)", "# stderr.setFormatter(formatter)", "# self.logger.addHandler(stderr)", "log", "=", "self", ".", "opts", ".", "log", "or", "self", ".", "config", "[", "'crony'", "]", ".", "get", "(", "'log_file'", ")", "if", "log", ":", "logfile", "=", "logging", ".", "FileHandler", "(", "log", ")", "logfile", ".", "setLevel", "(", "lvl", ")", "formatter", "=", "logging", ".", "Formatter", "(", "log_format", ",", "date_format", ")", "logfile", ".", "setFormatter", "(", "formatter", ")", "self", ".", "logger", ".", "addHandler", "(", "logfile", ")", "if", "self", ".", "sentry_client", ":", "sentry", "=", "SentryHandler", "(", "self", ".", "sentry_client", ")", "sentry", ".", "setLevel", "(", "logging", ".", "ERROR", ")", "self", ".", "logger", ".", "addHandler", "(", "sentry", ")", "self", ".", "logger", ".", "debug", "(", "'Logging setup complete.'", ")" ]
Setup python logging handler.
[ "Setup", "python", "logging", "handler", "." ]
c93d14b809a2e878f1b9d6d53d5a04947896583b
https://github.com/youversion/crony/blob/c93d14b809a2e878f1b9d6d53d5a04947896583b/crony/crony.py#L167-L207
train
youversion/crony
crony/crony.py
CommandCenter.setup_path
def setup_path(self): """Setup PATH env var if necessary.""" path = self.opts.path or self.config['crony'].get('path') if path: self.logger.debug(f'Adding {path} to PATH environment variable') self.cmd = f'export PATH={path}:$PATH && {self.cmd}'
python
def setup_path(self): """Setup PATH env var if necessary.""" path = self.opts.path or self.config['crony'].get('path') if path: self.logger.debug(f'Adding {path} to PATH environment variable') self.cmd = f'export PATH={path}:$PATH && {self.cmd}'
[ "def", "setup_path", "(", "self", ")", ":", "path", "=", "self", ".", "opts", ".", "path", "or", "self", ".", "config", "[", "'crony'", "]", ".", "get", "(", "'path'", ")", "if", "path", ":", "self", ".", "logger", ".", "debug", "(", "f'Adding {path} to PATH environment variable'", ")", "self", ".", "cmd", "=", "f'export PATH={path}:$PATH && {self.cmd}'" ]
Setup PATH env var if necessary.
[ "Setup", "PATH", "env", "var", "if", "necessary", "." ]
c93d14b809a2e878f1b9d6d53d5a04947896583b
https://github.com/youversion/crony/blob/c93d14b809a2e878f1b9d6d53d5a04947896583b/crony/crony.py#L209-L214
train
youversion/crony
crony/crony.py
CommandCenter.setup_venv
def setup_venv(self): """Setup virtualenv if necessary.""" venv = self.opts.venv if not venv: venv = os.environ.get('CRONY_VENV') if not venv and self.config['crony']: venv = self.config['crony'].get('venv') if venv: if not venv.endswith('activate'): add_path = os.path.join('bin', 'activate') self.logger.debug(f'Venv directory given, adding {add_path}') venv = os.path.join(venv, add_path) self.logger.debug(f'Adding sourcing virtualenv {venv}') self.cmd = f'. {venv} && {self.cmd}'
python
def setup_venv(self): """Setup virtualenv if necessary.""" venv = self.opts.venv if not venv: venv = os.environ.get('CRONY_VENV') if not venv and self.config['crony']: venv = self.config['crony'].get('venv') if venv: if not venv.endswith('activate'): add_path = os.path.join('bin', 'activate') self.logger.debug(f'Venv directory given, adding {add_path}') venv = os.path.join(venv, add_path) self.logger.debug(f'Adding sourcing virtualenv {venv}') self.cmd = f'. {venv} && {self.cmd}'
[ "def", "setup_venv", "(", "self", ")", ":", "venv", "=", "self", ".", "opts", ".", "venv", "if", "not", "venv", ":", "venv", "=", "os", ".", "environ", ".", "get", "(", "'CRONY_VENV'", ")", "if", "not", "venv", "and", "self", ".", "config", "[", "'crony'", "]", ":", "venv", "=", "self", ".", "config", "[", "'crony'", "]", ".", "get", "(", "'venv'", ")", "if", "venv", ":", "if", "not", "venv", ".", "endswith", "(", "'activate'", ")", ":", "add_path", "=", "os", ".", "path", ".", "join", "(", "'bin'", ",", "'activate'", ")", "self", ".", "logger", ".", "debug", "(", "f'Venv directory given, adding {add_path}'", ")", "venv", "=", "os", ".", "path", ".", "join", "(", "venv", ",", "add_path", ")", "self", ".", "logger", ".", "debug", "(", "f'Adding sourcing virtualenv {venv}'", ")", "self", ".", "cmd", "=", "f'. {venv} && {self.cmd}'" ]
Setup virtualenv if necessary.
[ "Setup", "virtualenv", "if", "necessary", "." ]
c93d14b809a2e878f1b9d6d53d5a04947896583b
https://github.com/youversion/crony/blob/c93d14b809a2e878f1b9d6d53d5a04947896583b/crony/crony.py#L216-L229
train
rsgalloway/grit
grit/repo/local.py
get_repos
def get_repos(path): """ Returns list of found branches. :return: List of grit.Local objects """ p = str(path) ret = [] if not os.path.exists(p): return ret for d in os.listdir(p): pd = os.path.join(p, d) if os.path.exists(pd) and is_repo(pd): ret.append(Local(pd)) return ret
python
def get_repos(path): """ Returns list of found branches. :return: List of grit.Local objects """ p = str(path) ret = [] if not os.path.exists(p): return ret for d in os.listdir(p): pd = os.path.join(p, d) if os.path.exists(pd) and is_repo(pd): ret.append(Local(pd)) return ret
[ "def", "get_repos", "(", "path", ")", ":", "p", "=", "str", "(", "path", ")", "ret", "=", "[", "]", "if", "not", "os", ".", "path", ".", "exists", "(", "p", ")", ":", "return", "ret", "for", "d", "in", "os", ".", "listdir", "(", "p", ")", ":", "pd", "=", "os", ".", "path", ".", "join", "(", "p", ",", "d", ")", "if", "os", ".", "path", ".", "exists", "(", "pd", ")", "and", "is_repo", "(", "pd", ")", ":", "ret", ".", "append", "(", "Local", "(", "pd", ")", ")", "return", "ret" ]
Returns list of found branches. :return: List of grit.Local objects
[ "Returns", "list", "of", "found", "branches", "." ]
e6434ad8a1f4ac5d0903ebad630c81f8a5164d78
https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/repo/local.py#L32-L46
train
rsgalloway/grit
grit/repo/local.py
get_repo_parent
def get_repo_parent(path): """ Returns parent repo or input path if none found. :return: grit.Local or path """ # path is a repository if is_repo(path): return Local(path) # path is inside a repository elif not os.path.isdir(path): _rel = '' while path and path != '/': if is_repo(path): return Local(path) else: _rel = os.path.join(os.path.basename(path), _rel) path = os.path.dirname(path) return path
python
def get_repo_parent(path): """ Returns parent repo or input path if none found. :return: grit.Local or path """ # path is a repository if is_repo(path): return Local(path) # path is inside a repository elif not os.path.isdir(path): _rel = '' while path and path != '/': if is_repo(path): return Local(path) else: _rel = os.path.join(os.path.basename(path), _rel) path = os.path.dirname(path) return path
[ "def", "get_repo_parent", "(", "path", ")", ":", "# path is a repository", "if", "is_repo", "(", "path", ")", ":", "return", "Local", "(", "path", ")", "# path is inside a repository", "elif", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "_rel", "=", "''", "while", "path", "and", "path", "!=", "'/'", ":", "if", "is_repo", "(", "path", ")", ":", "return", "Local", "(", "path", ")", "else", ":", "_rel", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "basename", "(", "path", ")", ",", "_rel", ")", "path", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "return", "path" ]
Returns parent repo or input path if none found. :return: grit.Local or path
[ "Returns", "parent", "repo", "or", "input", "path", "if", "none", "found", "." ]
e6434ad8a1f4ac5d0903ebad630c81f8a5164d78
https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/repo/local.py#L48-L67
train
rsgalloway/grit
grit/repo/local.py
Local.setVersion
def setVersion(self, version): """ Checkout a version of the repo. :param version: Version number. """ try: sha = self.versions(version).commit.sha self.git.reset("--hard", sha) except Exception, e: raise RepoError(e)
python
def setVersion(self, version): """ Checkout a version of the repo. :param version: Version number. """ try: sha = self.versions(version).commit.sha self.git.reset("--hard", sha) except Exception, e: raise RepoError(e)
[ "def", "setVersion", "(", "self", ",", "version", ")", ":", "try", ":", "sha", "=", "self", ".", "versions", "(", "version", ")", ".", "commit", ".", "sha", "self", ".", "git", ".", "reset", "(", "\"--hard\"", ",", "sha", ")", "except", "Exception", ",", "e", ":", "raise", "RepoError", "(", "e", ")" ]
Checkout a version of the repo. :param version: Version number.
[ "Checkout", "a", "version", "of", "the", "repo", "." ]
e6434ad8a1f4ac5d0903ebad630c81f8a5164d78
https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/repo/local.py#L159-L169
train
rsgalloway/grit
grit/repo/local.py
Local._commits
def _commits(self, head='HEAD'): """Returns a list of the commits reachable from head. :return: List of commit objects. the first of which will be the commit of head, then following theat will be the parents. :raise: RepoError if any no commits are referenced, including if the head parameter isn't the sha of a commit. """ pending_commits = [head] history = [] while pending_commits != []: head = pending_commits.pop(0) try: commit = self[head] except KeyError: raise KeyError(head) if type(commit) != Commit: raise TypeError(commit) if commit in history: continue i = 0 for known_commit in history: if known_commit.commit_time > commit.commit_time: break i += 1 history.insert(i, commit) pending_commits += commit.parents return history
python
def _commits(self, head='HEAD'): """Returns a list of the commits reachable from head. :return: List of commit objects. the first of which will be the commit of head, then following theat will be the parents. :raise: RepoError if any no commits are referenced, including if the head parameter isn't the sha of a commit. """ pending_commits = [head] history = [] while pending_commits != []: head = pending_commits.pop(0) try: commit = self[head] except KeyError: raise KeyError(head) if type(commit) != Commit: raise TypeError(commit) if commit in history: continue i = 0 for known_commit in history: if known_commit.commit_time > commit.commit_time: break i += 1 history.insert(i, commit) pending_commits += commit.parents return history
[ "def", "_commits", "(", "self", ",", "head", "=", "'HEAD'", ")", ":", "pending_commits", "=", "[", "head", "]", "history", "=", "[", "]", "while", "pending_commits", "!=", "[", "]", ":", "head", "=", "pending_commits", ".", "pop", "(", "0", ")", "try", ":", "commit", "=", "self", "[", "head", "]", "except", "KeyError", ":", "raise", "KeyError", "(", "head", ")", "if", "type", "(", "commit", ")", "!=", "Commit", ":", "raise", "TypeError", "(", "commit", ")", "if", "commit", "in", "history", ":", "continue", "i", "=", "0", "for", "known_commit", "in", "history", ":", "if", "known_commit", ".", "commit_time", ">", "commit", ".", "commit_time", ":", "break", "i", "+=", "1", "history", ".", "insert", "(", "i", ",", "commit", ")", "pending_commits", "+=", "commit", ".", "parents", "return", "history" ]
Returns a list of the commits reachable from head. :return: List of commit objects. the first of which will be the commit of head, then following theat will be the parents. :raise: RepoError if any no commits are referenced, including if the head parameter isn't the sha of a commit.
[ "Returns", "a", "list", "of", "the", "commits", "reachable", "from", "head", "." ]
e6434ad8a1f4ac5d0903ebad630c81f8a5164d78
https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/repo/local.py#L171-L199
train
rsgalloway/grit
grit/repo/local.py
Local.versions
def versions(self, version=None): """ List of Versions of this repository. :param version: Version index. :param rev: Commit sha or ref. :return: List of Version objects matching params. """ try: versions = [Version(self, c) for c in self._commits()] except Exception, e: log.debug('No versions exist') return [] if version is not None and versions: try: versions = versions[version] except IndexError: raise VersionError('Version %s does not exist' % version) return versions
python
def versions(self, version=None): """ List of Versions of this repository. :param version: Version index. :param rev: Commit sha or ref. :return: List of Version objects matching params. """ try: versions = [Version(self, c) for c in self._commits()] except Exception, e: log.debug('No versions exist') return [] if version is not None and versions: try: versions = versions[version] except IndexError: raise VersionError('Version %s does not exist' % version) return versions
[ "def", "versions", "(", "self", ",", "version", "=", "None", ")", ":", "try", ":", "versions", "=", "[", "Version", "(", "self", ",", "c", ")", "for", "c", "in", "self", ".", "_commits", "(", ")", "]", "except", "Exception", ",", "e", ":", "log", ".", "debug", "(", "'No versions exist'", ")", "return", "[", "]", "if", "version", "is", "not", "None", "and", "versions", ":", "try", ":", "versions", "=", "versions", "[", "version", "]", "except", "IndexError", ":", "raise", "VersionError", "(", "'Version %s does not exist'", "%", "version", ")", "return", "versions" ]
List of Versions of this repository. :param version: Version index. :param rev: Commit sha or ref. :return: List of Version objects matching params.
[ "List", "of", "Versions", "of", "this", "repository", "." ]
e6434ad8a1f4ac5d0903ebad630c81f8a5164d78
https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/repo/local.py#L201-L220
train
rsgalloway/grit
grit/repo/local.py
Local.setDescription
def setDescription(self, desc='No description'): """sets repository description""" try: self._put_named_file('description', desc) except Exception, e: raise RepoError(e)
python
def setDescription(self, desc='No description'): """sets repository description""" try: self._put_named_file('description', desc) except Exception, e: raise RepoError(e)
[ "def", "setDescription", "(", "self", ",", "desc", "=", "'No description'", ")", ":", "try", ":", "self", ".", "_put_named_file", "(", "'description'", ",", "desc", ")", "except", "Exception", ",", "e", ":", "raise", "RepoError", "(", "e", ")" ]
sets repository description
[ "sets", "repository", "description" ]
e6434ad8a1f4ac5d0903ebad630c81f8a5164d78
https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/repo/local.py#L229-L234
train
rsgalloway/grit
grit/repo/local.py
Local.new
def new(self, path, desc=None, bare=True): """ Create a new bare repo.Local instance. :param path: Path to new repo. :param desc: Repo description. :param bare: Create as bare repo. :returns: New repo.Local instance. """ if os.path.exists(path): raise RepoError('Path already exists: %s' % path) try: os.mkdir(path) if bare: Repo.init_bare(path) else: Repo.init(path) repo = Local(path) if desc: repo.setDescription(desc) version = repo.addVersion() version.save('Repo Initialization') return repo except Exception, e: traceback.print_exc() raise RepoError('Error creating repo')
python
def new(self, path, desc=None, bare=True): """ Create a new bare repo.Local instance. :param path: Path to new repo. :param desc: Repo description. :param bare: Create as bare repo. :returns: New repo.Local instance. """ if os.path.exists(path): raise RepoError('Path already exists: %s' % path) try: os.mkdir(path) if bare: Repo.init_bare(path) else: Repo.init(path) repo = Local(path) if desc: repo.setDescription(desc) version = repo.addVersion() version.save('Repo Initialization') return repo except Exception, e: traceback.print_exc() raise RepoError('Error creating repo')
[ "def", "new", "(", "self", ",", "path", ",", "desc", "=", "None", ",", "bare", "=", "True", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "RepoError", "(", "'Path already exists: %s'", "%", "path", ")", "try", ":", "os", ".", "mkdir", "(", "path", ")", "if", "bare", ":", "Repo", ".", "init_bare", "(", "path", ")", "else", ":", "Repo", ".", "init", "(", "path", ")", "repo", "=", "Local", "(", "path", ")", "if", "desc", ":", "repo", ".", "setDescription", "(", "desc", ")", "version", "=", "repo", ".", "addVersion", "(", ")", "version", ".", "save", "(", "'Repo Initialization'", ")", "return", "repo", "except", "Exception", ",", "e", ":", "traceback", ".", "print_exc", "(", ")", "raise", "RepoError", "(", "'Error creating repo'", ")" ]
Create a new bare repo.Local instance. :param path: Path to new repo. :param desc: Repo description. :param bare: Create as bare repo. :returns: New repo.Local instance.
[ "Create", "a", "new", "bare", "repo", ".", "Local", "instance", "." ]
e6434ad8a1f4ac5d0903ebad630c81f8a5164d78
https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/repo/local.py#L246-L272
train
rsgalloway/grit
grit/repo/local.py
Local.branch
def branch(self, name, desc=None): """ Create a branch of this repo at 'name'. :param name: Name of new branch :param desc: Repo description. :return: New Local instance. """ return Local.new(path=os.path.join(self.path, name), desc=desc, bare=True)
python
def branch(self, name, desc=None): """ Create a branch of this repo at 'name'. :param name: Name of new branch :param desc: Repo description. :return: New Local instance. """ return Local.new(path=os.path.join(self.path, name), desc=desc, bare=True)
[ "def", "branch", "(", "self", ",", "name", ",", "desc", "=", "None", ")", ":", "return", "Local", ".", "new", "(", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "name", ")", ",", "desc", "=", "desc", ",", "bare", "=", "True", ")" ]
Create a branch of this repo at 'name'. :param name: Name of new branch :param desc: Repo description. :return: New Local instance.
[ "Create", "a", "branch", "of", "this", "repo", "at", "name", "." ]
e6434ad8a1f4ac5d0903ebad630c81f8a5164d78
https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/repo/local.py#L274-L283
train
rsgalloway/grit
grit/repo/local.py
Local.addItem
def addItem(self, item, message=None): """add a new Item class object""" if message is None: message = 'Adding item %s' % item.path try: v = Version.new(repo=self) v.addItem(item) v.save(message) except VersionError, e: raise RepoError(e)
python
def addItem(self, item, message=None): """add a new Item class object""" if message is None: message = 'Adding item %s' % item.path try: v = Version.new(repo=self) v.addItem(item) v.save(message) except VersionError, e: raise RepoError(e)
[ "def", "addItem", "(", "self", ",", "item", ",", "message", "=", "None", ")", ":", "if", "message", "is", "None", ":", "message", "=", "'Adding item %s'", "%", "item", ".", "path", "try", ":", "v", "=", "Version", ".", "new", "(", "repo", "=", "self", ")", "v", ".", "addItem", "(", "item", ")", "v", ".", "save", "(", "message", ")", "except", "VersionError", ",", "e", ":", "raise", "RepoError", "(", "e", ")" ]
add a new Item class object
[ "add", "a", "new", "Item", "class", "object" ]
e6434ad8a1f4ac5d0903ebad630c81f8a5164d78
https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/repo/local.py#L290-L299
train
rsgalloway/grit
grit/repo/local.py
Local.items
def items(self, path=None, version=None): """ Returns a list of items. :param path: Regex filter on item path. :param version: Repo versions number/index. :return: List of Item class objects. """ if version is None: version = -1 items = {} for item in self.versions(version).items(): items[item.path] = item parent = self.parent # get latest committed items from parents while parent: for item in parent.items(path=path): if item.path not in items.keys(): items[item.path] = item parent = parent.parent # filter items matching path regex if path is not None: path += '$' regex = re.compile(path) return [item for path, item in items.items() if regex.match(path)] else: return items.values()
python
def items(self, path=None, version=None): """ Returns a list of items. :param path: Regex filter on item path. :param version: Repo versions number/index. :return: List of Item class objects. """ if version is None: version = -1 items = {} for item in self.versions(version).items(): items[item.path] = item parent = self.parent # get latest committed items from parents while parent: for item in parent.items(path=path): if item.path not in items.keys(): items[item.path] = item parent = parent.parent # filter items matching path regex if path is not None: path += '$' regex = re.compile(path) return [item for path, item in items.items() if regex.match(path)] else: return items.values()
[ "def", "items", "(", "self", ",", "path", "=", "None", ",", "version", "=", "None", ")", ":", "if", "version", "is", "None", ":", "version", "=", "-", "1", "items", "=", "{", "}", "for", "item", "in", "self", ".", "versions", "(", "version", ")", ".", "items", "(", ")", ":", "items", "[", "item", ".", "path", "]", "=", "item", "parent", "=", "self", ".", "parent", "# get latest committed items from parents", "while", "parent", ":", "for", "item", "in", "parent", ".", "items", "(", "path", "=", "path", ")", ":", "if", "item", ".", "path", "not", "in", "items", ".", "keys", "(", ")", ":", "items", "[", "item", ".", "path", "]", "=", "item", "parent", "=", "parent", ".", "parent", "# filter items matching path regex", "if", "path", "is", "not", "None", ":", "path", "+=", "'$'", "regex", "=", "re", ".", "compile", "(", "path", ")", "return", "[", "item", "for", "path", ",", "item", "in", "items", ".", "items", "(", ")", "if", "regex", ".", "match", "(", "path", ")", "]", "else", ":", "return", "items", ".", "values", "(", ")" ]
Returns a list of items. :param path: Regex filter on item path. :param version: Repo versions number/index. :return: List of Item class objects.
[ "Returns", "a", "list", "of", "items", "." ]
e6434ad8a1f4ac5d0903ebad630c81f8a5164d78
https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/repo/local.py#L305-L334
train
BernardFW/bernard
src/bernard/platforms/telegram/_utils.py
set_reply_markup
async def set_reply_markup(msg: Dict, request: 'Request', stack: 'Stack') \ -> None: """ Add the "reply markup" to a message from the layers :param msg: Message dictionary :param request: Current request being replied :param stack: Stack to analyze """ from bernard.platforms.telegram.layers import InlineKeyboard, \ ReplyKeyboard, \ ReplyKeyboardRemove try: keyboard = stack.get_layer(InlineKeyboard) except KeyError: pass else: msg['reply_markup'] = await keyboard.serialize(request) try: keyboard = stack.get_layer(ReplyKeyboard) except KeyError: pass else: msg['reply_markup'] = await keyboard.serialize(request) try: remove = stack.get_layer(ReplyKeyboardRemove) except KeyError: pass else: msg['reply_markup'] = remove.serialize()
python
async def set_reply_markup(msg: Dict, request: 'Request', stack: 'Stack') \ -> None: """ Add the "reply markup" to a message from the layers :param msg: Message dictionary :param request: Current request being replied :param stack: Stack to analyze """ from bernard.platforms.telegram.layers import InlineKeyboard, \ ReplyKeyboard, \ ReplyKeyboardRemove try: keyboard = stack.get_layer(InlineKeyboard) except KeyError: pass else: msg['reply_markup'] = await keyboard.serialize(request) try: keyboard = stack.get_layer(ReplyKeyboard) except KeyError: pass else: msg['reply_markup'] = await keyboard.serialize(request) try: remove = stack.get_layer(ReplyKeyboardRemove) except KeyError: pass else: msg['reply_markup'] = remove.serialize()
[ "async", "def", "set_reply_markup", "(", "msg", ":", "Dict", ",", "request", ":", "'Request'", ",", "stack", ":", "'Stack'", ")", "->", "None", ":", "from", "bernard", ".", "platforms", ".", "telegram", ".", "layers", "import", "InlineKeyboard", ",", "ReplyKeyboard", ",", "ReplyKeyboardRemove", "try", ":", "keyboard", "=", "stack", ".", "get_layer", "(", "InlineKeyboard", ")", "except", "KeyError", ":", "pass", "else", ":", "msg", "[", "'reply_markup'", "]", "=", "await", "keyboard", ".", "serialize", "(", "request", ")", "try", ":", "keyboard", "=", "stack", ".", "get_layer", "(", "ReplyKeyboard", ")", "except", "KeyError", ":", "pass", "else", ":", "msg", "[", "'reply_markup'", "]", "=", "await", "keyboard", ".", "serialize", "(", "request", ")", "try", ":", "remove", "=", "stack", ".", "get_layer", "(", "ReplyKeyboardRemove", ")", "except", "KeyError", ":", "pass", "else", ":", "msg", "[", "'reply_markup'", "]", "=", "remove", ".", "serialize", "(", ")" ]
Add the "reply markup" to a message from the layers :param msg: Message dictionary :param request: Current request being replied :param stack: Stack to analyze
[ "Add", "the", "reply", "markup", "to", "a", "message", "from", "the", "layers" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/telegram/_utils.py#L11-L42
train
BernardFW/bernard
src/bernard/i18n/utils.py
split_locale
def split_locale(locale: Text) -> Tuple[Text, Optional[Text]]: """ Decompose the locale into a normalized tuple. The first item is the locale (as lowercase letters) while the second item is either the country as lower case either None if no country was supplied. """ items = re.split(r'[_\-]', locale.lower(), 1) try: return items[0], items[1] except IndexError: return items[0], None
python
def split_locale(locale: Text) -> Tuple[Text, Optional[Text]]: """ Decompose the locale into a normalized tuple. The first item is the locale (as lowercase letters) while the second item is either the country as lower case either None if no country was supplied. """ items = re.split(r'[_\-]', locale.lower(), 1) try: return items[0], items[1] except IndexError: return items[0], None
[ "def", "split_locale", "(", "locale", ":", "Text", ")", "->", "Tuple", "[", "Text", ",", "Optional", "[", "Text", "]", "]", ":", "items", "=", "re", ".", "split", "(", "r'[_\\-]'", ",", "locale", ".", "lower", "(", ")", ",", "1", ")", "try", ":", "return", "items", "[", "0", "]", ",", "items", "[", "1", "]", "except", "IndexError", ":", "return", "items", "[", "0", "]", ",", "None" ]
Decompose the locale into a normalized tuple. The first item is the locale (as lowercase letters) while the second item is either the country as lower case either None if no country was supplied.
[ "Decompose", "the", "locale", "into", "a", "normalized", "tuple", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/utils.py#L14-L27
train
BernardFW/bernard
src/bernard/i18n/utils.py
compare_locales
def compare_locales(a, b): """ Compares two locales to find the level of compatibility :param a: First locale :param b: Second locale :return: 2 full match, 1 lang match, 0 no match """ if a is None or b is None: if a == b: return 2 else: return 0 a = split_locale(a) b = split_locale(b) if a == b: return 2 elif a[0] == b[0]: return 1 else: return 0
python
def compare_locales(a, b): """ Compares two locales to find the level of compatibility :param a: First locale :param b: Second locale :return: 2 full match, 1 lang match, 0 no match """ if a is None or b is None: if a == b: return 2 else: return 0 a = split_locale(a) b = split_locale(b) if a == b: return 2 elif a[0] == b[0]: return 1 else: return 0
[ "def", "compare_locales", "(", "a", ",", "b", ")", ":", "if", "a", "is", "None", "or", "b", "is", "None", ":", "if", "a", "==", "b", ":", "return", "2", "else", ":", "return", "0", "a", "=", "split_locale", "(", "a", ")", "b", "=", "split_locale", "(", "b", ")", "if", "a", "==", "b", ":", "return", "2", "elif", "a", "[", "0", "]", "==", "b", "[", "0", "]", ":", "return", "1", "else", ":", "return", "0" ]
Compares two locales to find the level of compatibility :param a: First locale :param b: Second locale :return: 2 full match, 1 lang match, 0 no match
[ "Compares", "two", "locales", "to", "find", "the", "level", "of", "compatibility" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/utils.py#L30-L53
train
BernardFW/bernard
src/bernard/i18n/utils.py
LocalesDict.list_locales
def list_locales(self) -> List[Optional[Text]]: """ Returns the list of available locales. The first locale is the default locale to be used. If no locales are known, then `None` will be the first item. """ locales = list(self.dict.keys()) if not locales: locales.append(None) return locales
python
def list_locales(self) -> List[Optional[Text]]: """ Returns the list of available locales. The first locale is the default locale to be used. If no locales are known, then `None` will be the first item. """ locales = list(self.dict.keys()) if not locales: locales.append(None) return locales
[ "def", "list_locales", "(", "self", ")", "->", "List", "[", "Optional", "[", "Text", "]", "]", ":", "locales", "=", "list", "(", "self", ".", "dict", ".", "keys", "(", ")", ")", "if", "not", "locales", ":", "locales", ".", "append", "(", "None", ")", "return", "locales" ]
Returns the list of available locales. The first locale is the default locale to be used. If no locales are known, then `None` will be the first item.
[ "Returns", "the", "list", "of", "available", "locales", ".", "The", "first", "locale", "is", "the", "default", "locale", "to", "be", "used", ".", "If", "no", "locales", "are", "known", "then", "None", "will", "be", "the", "first", "item", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/utils.py#L61-L73
train
BernardFW/bernard
src/bernard/i18n/utils.py
LocalesDict.choose_locale
def choose_locale(self, locale: Text) -> Text: """ Returns the best matching locale in what is available. :param locale: Locale to match :return: Locale to use """ if locale not in self._choice_cache: locales = self.list_locales() best_choice = locales[0] best_level = 0 for candidate in locales: cmp = compare_locales(locale, candidate) if cmp > best_level: best_choice = candidate best_level = cmp self._choice_cache[locale] = best_choice return self._choice_cache[locale]
python
def choose_locale(self, locale: Text) -> Text: """ Returns the best matching locale in what is available. :param locale: Locale to match :return: Locale to use """ if locale not in self._choice_cache: locales = self.list_locales() best_choice = locales[0] best_level = 0 for candidate in locales: cmp = compare_locales(locale, candidate) if cmp > best_level: best_choice = candidate best_level = cmp self._choice_cache[locale] = best_choice return self._choice_cache[locale]
[ "def", "choose_locale", "(", "self", ",", "locale", ":", "Text", ")", "->", "Text", ":", "if", "locale", "not", "in", "self", ".", "_choice_cache", ":", "locales", "=", "self", ".", "list_locales", "(", ")", "best_choice", "=", "locales", "[", "0", "]", "best_level", "=", "0", "for", "candidate", "in", "locales", ":", "cmp", "=", "compare_locales", "(", "locale", ",", "candidate", ")", "if", "cmp", ">", "best_level", ":", "best_choice", "=", "candidate", "best_level", "=", "cmp", "self", ".", "_choice_cache", "[", "locale", "]", "=", "best_choice", "return", "self", ".", "_choice_cache", "[", "locale", "]" ]
Returns the best matching locale in what is available. :param locale: Locale to match :return: Locale to use
[ "Returns", "the", "best", "matching", "locale", "in", "what", "is", "available", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/utils.py#L75-L98
train
BernardFW/bernard
src/bernard/i18n/utils.py
LocalesFlatDict.update
def update(self, new_data: Dict[Text, Dict[Text, Text]]): """ Receive an update from a loader. :param new_data: New translation data from the loader """ for locale, data in new_data.items(): if locale not in self.dict: self.dict[locale] = {} self.dict[locale].update(data)
python
def update(self, new_data: Dict[Text, Dict[Text, Text]]): """ Receive an update from a loader. :param new_data: New translation data from the loader """ for locale, data in new_data.items(): if locale not in self.dict: self.dict[locale] = {} self.dict[locale].update(data)
[ "def", "update", "(", "self", ",", "new_data", ":", "Dict", "[", "Text", ",", "Dict", "[", "Text", ",", "Text", "]", "]", ")", ":", "for", "locale", ",", "data", "in", "new_data", ".", "items", "(", ")", ":", "if", "locale", "not", "in", "self", ".", "dict", ":", "self", ".", "dict", "[", "locale", "]", "=", "{", "}", "self", ".", "dict", "[", "locale", "]", ".", "update", "(", "data", ")" ]
Receive an update from a loader. :param new_data: New translation data from the loader
[ "Receive", "an", "update", "from", "a", "loader", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/utils.py#L109-L120
train
BernardFW/bernard
src/bernard/platforms/facebook/helpers.py
UrlButton._make_url
async def _make_url(self, url: Text, request: 'Request') -> Text: """ Signs the URL if needed """ if self.sign_webview: return await request.sign_url(url) return url
python
async def _make_url(self, url: Text, request: 'Request') -> Text: """ Signs the URL if needed """ if self.sign_webview: return await request.sign_url(url) return url
[ "async", "def", "_make_url", "(", "self", ",", "url", ":", "Text", ",", "request", ":", "'Request'", ")", "->", "Text", ":", "if", "self", ".", "sign_webview", ":", "return", "await", "request", ".", "sign_url", "(", "url", ")", "return", "url" ]
Signs the URL if needed
[ "Signs", "the", "URL", "if", "needed" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/helpers.py#L125-L133
train
BernardFW/bernard
src/bernard/platforms/facebook/helpers.py
Card.is_sharable
def is_sharable(self): """ Make sure that nothing inside blocks sharing. """ if self.buttons: return (all(b.is_sharable() for b in self.buttons) and self.default_action and self.default_action.is_sharable())
python
def is_sharable(self): """ Make sure that nothing inside blocks sharing. """ if self.buttons: return (all(b.is_sharable() for b in self.buttons) and self.default_action and self.default_action.is_sharable())
[ "def", "is_sharable", "(", "self", ")", ":", "if", "self", ".", "buttons", ":", "return", "(", "all", "(", "b", ".", "is_sharable", "(", ")", "for", "b", "in", "self", ".", "buttons", ")", "and", "self", ".", "default_action", "and", "self", ".", "default_action", ".", "is_sharable", "(", ")", ")" ]
Make sure that nothing inside blocks sharing.
[ "Make", "sure", "that", "nothing", "inside", "blocks", "sharing", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/helpers.py#L306-L313
train
ioos/cc-plugin-ncei
cc_plugin_ncei/ncei_grid.py
NCEIGridBase.check_bounds_variables
def check_bounds_variables(self, dataset): ''' Checks the grid boundary variables. :param netCDF4.Dataset dataset: An open netCDF dataset ''' recommended_ctx = TestCtx(BaseCheck.MEDIUM, 'Recommended variables to describe grid boundaries') bounds_map = { 'lat_bounds': { 'units': 'degrees_north', 'comment': 'latitude values at the north and south bounds of each pixel.' }, 'lon_bounds': { 'units': 'degrees_east', 'comment': 'longitude values at the west and east bounds of each pixel.' }, 'z_bounds': { 'comment': 'z bounds for each z value', }, 'time_bounds': { 'comment': 'time bounds for each time value' } } bounds_variables = [v.bounds for v in dataset.get_variables_by_attributes(bounds=lambda x: x is not None)] for variable in bounds_variables: ncvar = dataset.variables.get(variable, {}) recommended_ctx.assert_true(ncvar != {}, 'a variable {} should exist as indicated by a bounds attribute'.format(variable)) if ncvar == {}: continue units = getattr(ncvar, 'units', '') if variable in bounds_map and 'units' in bounds_map[variable]: recommended_ctx.assert_true( units == bounds_map[variable]['units'], 'variable {} should have units {}'.format(variable, bounds_map[variable]['units']) ) else: recommended_ctx.assert_true( units != '', 'variable {} should have a units attribute that is not empty'.format(variable) ) comment = getattr(ncvar, 'comment', '') recommended_ctx.assert_true( comment != '', 'variable {} should have a comment and not be empty' ) return recommended_ctx.to_result()
python
def check_bounds_variables(self, dataset): ''' Checks the grid boundary variables. :param netCDF4.Dataset dataset: An open netCDF dataset ''' recommended_ctx = TestCtx(BaseCheck.MEDIUM, 'Recommended variables to describe grid boundaries') bounds_map = { 'lat_bounds': { 'units': 'degrees_north', 'comment': 'latitude values at the north and south bounds of each pixel.' }, 'lon_bounds': { 'units': 'degrees_east', 'comment': 'longitude values at the west and east bounds of each pixel.' }, 'z_bounds': { 'comment': 'z bounds for each z value', }, 'time_bounds': { 'comment': 'time bounds for each time value' } } bounds_variables = [v.bounds for v in dataset.get_variables_by_attributes(bounds=lambda x: x is not None)] for variable in bounds_variables: ncvar = dataset.variables.get(variable, {}) recommended_ctx.assert_true(ncvar != {}, 'a variable {} should exist as indicated by a bounds attribute'.format(variable)) if ncvar == {}: continue units = getattr(ncvar, 'units', '') if variable in bounds_map and 'units' in bounds_map[variable]: recommended_ctx.assert_true( units == bounds_map[variable]['units'], 'variable {} should have units {}'.format(variable, bounds_map[variable]['units']) ) else: recommended_ctx.assert_true( units != '', 'variable {} should have a units attribute that is not empty'.format(variable) ) comment = getattr(ncvar, 'comment', '') recommended_ctx.assert_true( comment != '', 'variable {} should have a comment and not be empty' ) return recommended_ctx.to_result()
[ "def", "check_bounds_variables", "(", "self", ",", "dataset", ")", ":", "recommended_ctx", "=", "TestCtx", "(", "BaseCheck", ".", "MEDIUM", ",", "'Recommended variables to describe grid boundaries'", ")", "bounds_map", "=", "{", "'lat_bounds'", ":", "{", "'units'", ":", "'degrees_north'", ",", "'comment'", ":", "'latitude values at the north and south bounds of each pixel.'", "}", ",", "'lon_bounds'", ":", "{", "'units'", ":", "'degrees_east'", ",", "'comment'", ":", "'longitude values at the west and east bounds of each pixel.'", "}", ",", "'z_bounds'", ":", "{", "'comment'", ":", "'z bounds for each z value'", ",", "}", ",", "'time_bounds'", ":", "{", "'comment'", ":", "'time bounds for each time value'", "}", "}", "bounds_variables", "=", "[", "v", ".", "bounds", "for", "v", "in", "dataset", ".", "get_variables_by_attributes", "(", "bounds", "=", "lambda", "x", ":", "x", "is", "not", "None", ")", "]", "for", "variable", "in", "bounds_variables", ":", "ncvar", "=", "dataset", ".", "variables", ".", "get", "(", "variable", ",", "{", "}", ")", "recommended_ctx", ".", "assert_true", "(", "ncvar", "!=", "{", "}", ",", "'a variable {} should exist as indicated by a bounds attribute'", ".", "format", "(", "variable", ")", ")", "if", "ncvar", "==", "{", "}", ":", "continue", "units", "=", "getattr", "(", "ncvar", ",", "'units'", ",", "''", ")", "if", "variable", "in", "bounds_map", "and", "'units'", "in", "bounds_map", "[", "variable", "]", ":", "recommended_ctx", ".", "assert_true", "(", "units", "==", "bounds_map", "[", "variable", "]", "[", "'units'", "]", ",", "'variable {} should have units {}'", ".", "format", "(", "variable", ",", "bounds_map", "[", "variable", "]", "[", "'units'", "]", ")", ")", "else", ":", "recommended_ctx", ".", "assert_true", "(", "units", "!=", "''", ",", "'variable {} should have a units attribute that is not empty'", ".", "format", "(", "variable", ")", ")", "comment", "=", "getattr", "(", "ncvar", ",", "'comment'", ",", "''", ")", "recommended_ctx", ".", "assert_true", "(", "comment", "!=", "''", ",", "'variable {} should have a comment and not be empty'", ")", "return", "recommended_ctx", ".", "to_result", "(", ")" ]
Checks the grid boundary variables. :param netCDF4.Dataset dataset: An open netCDF dataset
[ "Checks", "the", "grid", "boundary", "variables", "." ]
963fefd7fa43afd32657ac4c36aad4ddb4c25acf
https://github.com/ioos/cc-plugin-ncei/blob/963fefd7fa43afd32657ac4c36aad4ddb4c25acf/cc_plugin_ncei/ncei_grid.py#L42-L93
train
walter426/Python_GoogleMapsApi
GoogleMapsApi/geocode.py
Geocoding.geocode
def geocode(self, string, bounds=None, region=None, language=None, sensor=False): '''Geocode an address. Pls refer to the Google Maps Web API for the details of the parameters ''' if isinstance(string, unicode): string = string.encode('utf-8') params = { 'address': self.format_string % string, 'sensor': str(sensor).lower() } if bounds: params['bounds'] = bounds if region: params['region'] = region if language: params['language'] = language if not self.premier: url = self.get_url(params) else: url = self.get_signed_url(params) return self.GetService_url(url)
python
def geocode(self, string, bounds=None, region=None, language=None, sensor=False): '''Geocode an address. Pls refer to the Google Maps Web API for the details of the parameters ''' if isinstance(string, unicode): string = string.encode('utf-8') params = { 'address': self.format_string % string, 'sensor': str(sensor).lower() } if bounds: params['bounds'] = bounds if region: params['region'] = region if language: params['language'] = language if not self.premier: url = self.get_url(params) else: url = self.get_signed_url(params) return self.GetService_url(url)
[ "def", "geocode", "(", "self", ",", "string", ",", "bounds", "=", "None", ",", "region", "=", "None", ",", "language", "=", "None", ",", "sensor", "=", "False", ")", ":", "if", "isinstance", "(", "string", ",", "unicode", ")", ":", "string", "=", "string", ".", "encode", "(", "'utf-8'", ")", "params", "=", "{", "'address'", ":", "self", ".", "format_string", "%", "string", ",", "'sensor'", ":", "str", "(", "sensor", ")", ".", "lower", "(", ")", "}", "if", "bounds", ":", "params", "[", "'bounds'", "]", "=", "bounds", "if", "region", ":", "params", "[", "'region'", "]", "=", "region", "if", "language", ":", "params", "[", "'language'", "]", "=", "language", "if", "not", "self", ".", "premier", ":", "url", "=", "self", ".", "get_url", "(", "params", ")", "else", ":", "url", "=", "self", ".", "get_signed_url", "(", "params", ")", "return", "self", ".", "GetService_url", "(", "url", ")" ]
Geocode an address. Pls refer to the Google Maps Web API for the details of the parameters
[ "Geocode", "an", "address", ".", "Pls", "refer", "to", "the", "Google", "Maps", "Web", "API", "for", "the", "details", "of", "the", "parameters" ]
4832b293a0027446941a5f00ecc66256f92ddbce
https://github.com/walter426/Python_GoogleMapsApi/blob/4832b293a0027446941a5f00ecc66256f92ddbce/GoogleMapsApi/geocode.py#L34-L63
train
walter426/Python_GoogleMapsApi
GoogleMapsApi/geocode.py
Geocoding.reverse
def reverse(self, point, language=None, sensor=False): '''Reverse geocode a point. Pls refer to the Google Maps Web API for the details of the parameters ''' params = { 'latlng': point, 'sensor': str(sensor).lower() } if language: params['language'] = language if not self.premier: url = self.get_url(params) else: url = self.get_signed_url(params) return self.GetService_url(url)
python
def reverse(self, point, language=None, sensor=False): '''Reverse geocode a point. Pls refer to the Google Maps Web API for the details of the parameters ''' params = { 'latlng': point, 'sensor': str(sensor).lower() } if language: params['language'] = language if not self.premier: url = self.get_url(params) else: url = self.get_signed_url(params) return self.GetService_url(url)
[ "def", "reverse", "(", "self", ",", "point", ",", "language", "=", "None", ",", "sensor", "=", "False", ")", ":", "params", "=", "{", "'latlng'", ":", "point", ",", "'sensor'", ":", "str", "(", "sensor", ")", ".", "lower", "(", ")", "}", "if", "language", ":", "params", "[", "'language'", "]", "=", "language", "if", "not", "self", ".", "premier", ":", "url", "=", "self", ".", "get_url", "(", "params", ")", "else", ":", "url", "=", "self", ".", "get_signed_url", "(", "params", ")", "return", "self", ".", "GetService_url", "(", "url", ")" ]
Reverse geocode a point. Pls refer to the Google Maps Web API for the details of the parameters
[ "Reverse", "geocode", "a", "point", ".", "Pls", "refer", "to", "the", "Google", "Maps", "Web", "API", "for", "the", "details", "of", "the", "parameters" ]
4832b293a0027446941a5f00ecc66256f92ddbce
https://github.com/walter426/Python_GoogleMapsApi/blob/4832b293a0027446941a5f00ecc66256f92ddbce/GoogleMapsApi/geocode.py#L66-L83
train
walter426/Python_GoogleMapsApi
GoogleMapsApi/directions.py
Directions.GetDirections
def GetDirections(self, origin, destination, sensor = False, mode = None, waypoints = None, alternatives = None, avoid = None, language = None, units = None, region = None, departure_time = None, arrival_time = None): '''Get Directions Service Pls refer to the Google Maps Web API for the details of the remained parameters ''' params = { 'origin': origin, 'destination': destination, 'sensor': str(sensor).lower() } if mode: params['mode'] = mode if waypoints: params['waypoints'] = waypoints if alternatives: params['alternatives'] = alternatives if avoid: params['avoid'] = avoid if language: params['language'] = language if units: params['units'] = units if region: params['region'] = region if departure_time: params['departure_time'] = departure_time if arrival_time: params['arrival_time'] = arrival_time if not self.premier: url = self.get_url(params) else: url = self.get_signed_url(params) return self.GetService_url(url)
python
def GetDirections(self, origin, destination, sensor = False, mode = None, waypoints = None, alternatives = None, avoid = None, language = None, units = None, region = None, departure_time = None, arrival_time = None): '''Get Directions Service Pls refer to the Google Maps Web API for the details of the remained parameters ''' params = { 'origin': origin, 'destination': destination, 'sensor': str(sensor).lower() } if mode: params['mode'] = mode if waypoints: params['waypoints'] = waypoints if alternatives: params['alternatives'] = alternatives if avoid: params['avoid'] = avoid if language: params['language'] = language if units: params['units'] = units if region: params['region'] = region if departure_time: params['departure_time'] = departure_time if arrival_time: params['arrival_time'] = arrival_time if not self.premier: url = self.get_url(params) else: url = self.get_signed_url(params) return self.GetService_url(url)
[ "def", "GetDirections", "(", "self", ",", "origin", ",", "destination", ",", "sensor", "=", "False", ",", "mode", "=", "None", ",", "waypoints", "=", "None", ",", "alternatives", "=", "None", ",", "avoid", "=", "None", ",", "language", "=", "None", ",", "units", "=", "None", ",", "region", "=", "None", ",", "departure_time", "=", "None", ",", "arrival_time", "=", "None", ")", ":", "params", "=", "{", "'origin'", ":", "origin", ",", "'destination'", ":", "destination", ",", "'sensor'", ":", "str", "(", "sensor", ")", ".", "lower", "(", ")", "}", "if", "mode", ":", "params", "[", "'mode'", "]", "=", "mode", "if", "waypoints", ":", "params", "[", "'waypoints'", "]", "=", "waypoints", "if", "alternatives", ":", "params", "[", "'alternatives'", "]", "=", "alternatives", "if", "avoid", ":", "params", "[", "'avoid'", "]", "=", "avoid", "if", "language", ":", "params", "[", "'language'", "]", "=", "language", "if", "units", ":", "params", "[", "'units'", "]", "=", "units", "if", "region", ":", "params", "[", "'region'", "]", "=", "region", "if", "departure_time", ":", "params", "[", "'departure_time'", "]", "=", "departure_time", "if", "arrival_time", ":", "params", "[", "'arrival_time'", "]", "=", "arrival_time", "if", "not", "self", ".", "premier", ":", "url", "=", "self", ".", "get_url", "(", "params", ")", "else", ":", "url", "=", "self", ".", "get_signed_url", "(", "params", ")", "return", "self", ".", "GetService_url", "(", "url", ")" ]
Get Directions Service Pls refer to the Google Maps Web API for the details of the remained parameters
[ "Get", "Directions", "Service", "Pls", "refer", "to", "the", "Google", "Maps", "Web", "API", "for", "the", "details", "of", "the", "remained", "parameters" ]
4832b293a0027446941a5f00ecc66256f92ddbce
https://github.com/walter426/Python_GoogleMapsApi/blob/4832b293a0027446941a5f00ecc66256f92ddbce/GoogleMapsApi/directions.py#L33-L79
train
sthysel/knobs
src/knobs.py
ListKnob.get
def get(self): """ convert json env variable if set to list """ self._cast = type([]) source_value = os.getenv(self.env_name) # set the environment if it is not set if source_value is None: os.environ[self.env_name] = json.dumps(self.default) return self.default try: val = json.loads(source_value) except JSONDecodeError as e: click.secho(str(e), err=True, color='red') sys.exit(1) except ValueError as e: click.secho(e.message, err=True, color='red') sys.exit(1) if self.validator: val = self.validator(val) return val
python
def get(self): """ convert json env variable if set to list """ self._cast = type([]) source_value = os.getenv(self.env_name) # set the environment if it is not set if source_value is None: os.environ[self.env_name] = json.dumps(self.default) return self.default try: val = json.loads(source_value) except JSONDecodeError as e: click.secho(str(e), err=True, color='red') sys.exit(1) except ValueError as e: click.secho(e.message, err=True, color='red') sys.exit(1) if self.validator: val = self.validator(val) return val
[ "def", "get", "(", "self", ")", ":", "self", ".", "_cast", "=", "type", "(", "[", "]", ")", "source_value", "=", "os", ".", "getenv", "(", "self", ".", "env_name", ")", "# set the environment if it is not set", "if", "source_value", "is", "None", ":", "os", ".", "environ", "[", "self", ".", "env_name", "]", "=", "json", ".", "dumps", "(", "self", ".", "default", ")", "return", "self", ".", "default", "try", ":", "val", "=", "json", ".", "loads", "(", "source_value", ")", "except", "JSONDecodeError", "as", "e", ":", "click", ".", "secho", "(", "str", "(", "e", ")", ",", "err", "=", "True", ",", "color", "=", "'red'", ")", "sys", ".", "exit", "(", "1", ")", "except", "ValueError", "as", "e", ":", "click", ".", "secho", "(", "e", ".", "message", ",", "err", "=", "True", ",", "color", "=", "'red'", ")", "sys", ".", "exit", "(", "1", ")", "if", "self", ".", "validator", ":", "val", "=", "self", ".", "validator", "(", "val", ")", "return", "val" ]
convert json env variable if set to list
[ "convert", "json", "env", "variable", "if", "set", "to", "list" ]
1d01f50f643068076e38118a93fed9375ea3ac81
https://github.com/sthysel/knobs/blob/1d01f50f643068076e38118a93fed9375ea3ac81/src/knobs.py#L225-L250
train
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/parsers.py
parse_ppi_graph
def parse_ppi_graph(path: str, min_edge_weight: float = 0.0) -> Graph: """Build an undirected graph of gene interactions from edgelist file. :param str path: The path to the edgelist file :param float min_edge_weight: Cutoff to keep/remove the edges, default is 0, but could also be 0.63. :return Graph: Protein-protein interaction graph """ logger.info("In parse_ppi_graph()") graph = igraph.read(os.path.expanduser(path), format="ncol", directed=False, names=True) graph.delete_edges(graph.es.select(weight_lt=min_edge_weight)) graph.delete_vertices(graph.vs.select(_degree=0)) logger.info(f"Loaded PPI network.\n" f"Number of proteins: {len(graph.vs)}\n" f"Number of interactions: {len(graph.es)}\n") return graph
python
def parse_ppi_graph(path: str, min_edge_weight: float = 0.0) -> Graph: """Build an undirected graph of gene interactions from edgelist file. :param str path: The path to the edgelist file :param float min_edge_weight: Cutoff to keep/remove the edges, default is 0, but could also be 0.63. :return Graph: Protein-protein interaction graph """ logger.info("In parse_ppi_graph()") graph = igraph.read(os.path.expanduser(path), format="ncol", directed=False, names=True) graph.delete_edges(graph.es.select(weight_lt=min_edge_weight)) graph.delete_vertices(graph.vs.select(_degree=0)) logger.info(f"Loaded PPI network.\n" f"Number of proteins: {len(graph.vs)}\n" f"Number of interactions: {len(graph.es)}\n") return graph
[ "def", "parse_ppi_graph", "(", "path", ":", "str", ",", "min_edge_weight", ":", "float", "=", "0.0", ")", "->", "Graph", ":", "logger", ".", "info", "(", "\"In parse_ppi_graph()\"", ")", "graph", "=", "igraph", ".", "read", "(", "os", ".", "path", ".", "expanduser", "(", "path", ")", ",", "format", "=", "\"ncol\"", ",", "directed", "=", "False", ",", "names", "=", "True", ")", "graph", ".", "delete_edges", "(", "graph", ".", "es", ".", "select", "(", "weight_lt", "=", "min_edge_weight", ")", ")", "graph", ".", "delete_vertices", "(", "graph", ".", "vs", ".", "select", "(", "_degree", "=", "0", ")", ")", "logger", ".", "info", "(", "f\"Loaded PPI network.\\n\"", "f\"Number of proteins: {len(graph.vs)}\\n\"", "f\"Number of interactions: {len(graph.es)}\\n\"", ")", "return", "graph" ]
Build an undirected graph of gene interactions from edgelist file. :param str path: The path to the edgelist file :param float min_edge_weight: Cutoff to keep/remove the edges, default is 0, but could also be 0.63. :return Graph: Protein-protein interaction graph
[ "Build", "an", "undirected", "graph", "of", "gene", "interactions", "from", "edgelist", "file", "." ]
4d7b6713485f2d0a0957e6457edc1b1b5a237460
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/parsers.py#L19-L33
train
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/parsers.py
parse_excel
def parse_excel(file_path: str, entrez_id_header, log_fold_change_header, adjusted_p_value_header, entrez_delimiter, base_mean_header=None) -> List[Gene]: """Read an excel file on differential expression values as Gene objects. :param str file_path: The path to the differential expression file to be parsed. :param config.Params params: An object that includes paths, cutoffs and other information. :return list: A list of Gene objects. """ logger.info("In parse_excel()") df = pd.read_excel(file_path) return handle_dataframe( df, entrez_id_name=entrez_id_header, log2_fold_change_name=log_fold_change_header, adjusted_p_value_name=adjusted_p_value_header, entrez_delimiter=entrez_delimiter, base_mean=base_mean_header, )
python
def parse_excel(file_path: str, entrez_id_header, log_fold_change_header, adjusted_p_value_header, entrez_delimiter, base_mean_header=None) -> List[Gene]: """Read an excel file on differential expression values as Gene objects. :param str file_path: The path to the differential expression file to be parsed. :param config.Params params: An object that includes paths, cutoffs and other information. :return list: A list of Gene objects. """ logger.info("In parse_excel()") df = pd.read_excel(file_path) return handle_dataframe( df, entrez_id_name=entrez_id_header, log2_fold_change_name=log_fold_change_header, adjusted_p_value_name=adjusted_p_value_header, entrez_delimiter=entrez_delimiter, base_mean=base_mean_header, )
[ "def", "parse_excel", "(", "file_path", ":", "str", ",", "entrez_id_header", ",", "log_fold_change_header", ",", "adjusted_p_value_header", ",", "entrez_delimiter", ",", "base_mean_header", "=", "None", ")", "->", "List", "[", "Gene", "]", ":", "logger", ".", "info", "(", "\"In parse_excel()\"", ")", "df", "=", "pd", ".", "read_excel", "(", "file_path", ")", "return", "handle_dataframe", "(", "df", ",", "entrez_id_name", "=", "entrez_id_header", ",", "log2_fold_change_name", "=", "log_fold_change_header", ",", "adjusted_p_value_name", "=", "adjusted_p_value_header", ",", "entrez_delimiter", "=", "entrez_delimiter", ",", "base_mean", "=", "base_mean_header", ",", ")" ]
Read an excel file on differential expression values as Gene objects. :param str file_path: The path to the differential expression file to be parsed. :param config.Params params: An object that includes paths, cutoffs and other information. :return list: A list of Gene objects.
[ "Read", "an", "excel", "file", "on", "differential", "expression", "values", "as", "Gene", "objects", "." ]
4d7b6713485f2d0a0957e6457edc1b1b5a237460
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/parsers.py#L36-L59
train
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/parsers.py
parse_csv
def parse_csv(file_path: str, entrez_id_header, log_fold_change_header, adjusted_p_value_header, entrez_delimiter, base_mean_header=None, sep=",") -> List[Gene]: """Read a csv file on differential expression values as Gene objects. :param str file_path: The path to the differential expression file to be parsed. :param config.Params params: An object that includes paths, cutoffs and other information. :return list: A list of Gene objects. """ logger.info("In parse_csv()") df = pd.read_csv(file_path, sep=sep) return handle_dataframe( df, entrez_id_name=entrez_id_header, log2_fold_change_name=log_fold_change_header, adjusted_p_value_name=adjusted_p_value_header, entrez_delimiter=entrez_delimiter, base_mean=base_mean_header, )
python
def parse_csv(file_path: str, entrez_id_header, log_fold_change_header, adjusted_p_value_header, entrez_delimiter, base_mean_header=None, sep=",") -> List[Gene]: """Read a csv file on differential expression values as Gene objects. :param str file_path: The path to the differential expression file to be parsed. :param config.Params params: An object that includes paths, cutoffs and other information. :return list: A list of Gene objects. """ logger.info("In parse_csv()") df = pd.read_csv(file_path, sep=sep) return handle_dataframe( df, entrez_id_name=entrez_id_header, log2_fold_change_name=log_fold_change_header, adjusted_p_value_name=adjusted_p_value_header, entrez_delimiter=entrez_delimiter, base_mean=base_mean_header, )
[ "def", "parse_csv", "(", "file_path", ":", "str", ",", "entrez_id_header", ",", "log_fold_change_header", ",", "adjusted_p_value_header", ",", "entrez_delimiter", ",", "base_mean_header", "=", "None", ",", "sep", "=", "\",\"", ")", "->", "List", "[", "Gene", "]", ":", "logger", ".", "info", "(", "\"In parse_csv()\"", ")", "df", "=", "pd", ".", "read_csv", "(", "file_path", ",", "sep", "=", "sep", ")", "return", "handle_dataframe", "(", "df", ",", "entrez_id_name", "=", "entrez_id_header", ",", "log2_fold_change_name", "=", "log_fold_change_header", ",", "adjusted_p_value_name", "=", "adjusted_p_value_header", ",", "entrez_delimiter", "=", "entrez_delimiter", ",", "base_mean", "=", "base_mean_header", ",", ")" ]
Read a csv file on differential expression values as Gene objects. :param str file_path: The path to the differential expression file to be parsed. :param config.Params params: An object that includes paths, cutoffs and other information. :return list: A list of Gene objects.
[ "Read", "a", "csv", "file", "on", "differential", "expression", "values", "as", "Gene", "objects", "." ]
4d7b6713485f2d0a0957e6457edc1b1b5a237460
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/parsers.py#L62-L86
train
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/parsers.py
handle_dataframe
def handle_dataframe( df: pd.DataFrame, entrez_id_name, log2_fold_change_name, adjusted_p_value_name, entrez_delimiter, base_mean=None, ) -> List[Gene]: """Convert data frame on differential expression values as Gene objects. :param df: Data frame with columns showing values on differential expression. :param cfp: An object that includes paths, cutoffs and other information. :return list: A list of Gene objects. """ logger.info("In _handle_df()") if base_mean is not None and base_mean in df.columns: df = df[pd.notnull(df[base_mean])] df = df[pd.notnull(df[entrez_id_name])] df = df[pd.notnull(df[log2_fold_change_name])] df = df[pd.notnull(df[adjusted_p_value_name])] # try: # import bio2bel_hgnc # except ImportError: # logger.debug('skipping mapping') # else: # manager = bio2bel_hgnc.Manager() # # TODO @cthoyt return [ Gene( entrez_id=entrez_id, log2_fold_change=data[log2_fold_change_name], padj=data[adjusted_p_value_name] ) for _, data in df.iterrows() for entrez_id in str(data[entrez_id_name]).split(entrez_delimiter) ]
python
def handle_dataframe( df: pd.DataFrame, entrez_id_name, log2_fold_change_name, adjusted_p_value_name, entrez_delimiter, base_mean=None, ) -> List[Gene]: """Convert data frame on differential expression values as Gene objects. :param df: Data frame with columns showing values on differential expression. :param cfp: An object that includes paths, cutoffs and other information. :return list: A list of Gene objects. """ logger.info("In _handle_df()") if base_mean is not None and base_mean in df.columns: df = df[pd.notnull(df[base_mean])] df = df[pd.notnull(df[entrez_id_name])] df = df[pd.notnull(df[log2_fold_change_name])] df = df[pd.notnull(df[adjusted_p_value_name])] # try: # import bio2bel_hgnc # except ImportError: # logger.debug('skipping mapping') # else: # manager = bio2bel_hgnc.Manager() # # TODO @cthoyt return [ Gene( entrez_id=entrez_id, log2_fold_change=data[log2_fold_change_name], padj=data[adjusted_p_value_name] ) for _, data in df.iterrows() for entrez_id in str(data[entrez_id_name]).split(entrez_delimiter) ]
[ "def", "handle_dataframe", "(", "df", ":", "pd", ".", "DataFrame", ",", "entrez_id_name", ",", "log2_fold_change_name", ",", "adjusted_p_value_name", ",", "entrez_delimiter", ",", "base_mean", "=", "None", ",", ")", "->", "List", "[", "Gene", "]", ":", "logger", ".", "info", "(", "\"In _handle_df()\"", ")", "if", "base_mean", "is", "not", "None", "and", "base_mean", "in", "df", ".", "columns", ":", "df", "=", "df", "[", "pd", ".", "notnull", "(", "df", "[", "base_mean", "]", ")", "]", "df", "=", "df", "[", "pd", ".", "notnull", "(", "df", "[", "entrez_id_name", "]", ")", "]", "df", "=", "df", "[", "pd", ".", "notnull", "(", "df", "[", "log2_fold_change_name", "]", ")", "]", "df", "=", "df", "[", "pd", ".", "notnull", "(", "df", "[", "adjusted_p_value_name", "]", ")", "]", "# try:", "# import bio2bel_hgnc", "# except ImportError:", "# logger.debug('skipping mapping')", "# else:", "# manager = bio2bel_hgnc.Manager()", "# # TODO @cthoyt", "return", "[", "Gene", "(", "entrez_id", "=", "entrez_id", ",", "log2_fold_change", "=", "data", "[", "log2_fold_change_name", "]", ",", "padj", "=", "data", "[", "adjusted_p_value_name", "]", ")", "for", "_", ",", "data", "in", "df", ".", "iterrows", "(", ")", "for", "entrez_id", "in", "str", "(", "data", "[", "entrez_id_name", "]", ")", ".", "split", "(", "entrez_delimiter", ")", "]" ]
Convert data frame on differential expression values as Gene objects. :param df: Data frame with columns showing values on differential expression. :param cfp: An object that includes paths, cutoffs and other information. :return list: A list of Gene objects.
[ "Convert", "data", "frame", "on", "differential", "expression", "values", "as", "Gene", "objects", "." ]
4d7b6713485f2d0a0957e6457edc1b1b5a237460
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/parsers.py#L89-L129
train
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/parsers.py
parse_gene_list
def parse_gene_list(path: str, graph: Graph, anno_type: str = "name") -> list: """Parse a list of genes and return them if they are in the network. :param str path: The path of input file. :param Graph graph: The graph with genes as nodes. :param str anno_type: The type of annotation with two options:name-Entrez ID, symbol-HGNC symbol. :return list: A list of genes, all of which are in the network. """ # read the file genes = pd.read_csv(path, header=None)[0].tolist() genes = [str(int(gene)) for gene in genes] # get those genes which are in the network ind = [] if anno_type == "name": ind = graph.vs.select(name_in=genes).indices elif anno_type == "symbol": ind = graph.vs.select(symbol_in=genes).indices else: raise Exception("The type can either be name or symbol, {} is not " "supported".format(anno_type)) genes = graph.vs[ind][anno_type] return genes
python
def parse_gene_list(path: str, graph: Graph, anno_type: str = "name") -> list: """Parse a list of genes and return them if they are in the network. :param str path: The path of input file. :param Graph graph: The graph with genes as nodes. :param str anno_type: The type of annotation with two options:name-Entrez ID, symbol-HGNC symbol. :return list: A list of genes, all of which are in the network. """ # read the file genes = pd.read_csv(path, header=None)[0].tolist() genes = [str(int(gene)) for gene in genes] # get those genes which are in the network ind = [] if anno_type == "name": ind = graph.vs.select(name_in=genes).indices elif anno_type == "symbol": ind = graph.vs.select(symbol_in=genes).indices else: raise Exception("The type can either be name or symbol, {} is not " "supported".format(anno_type)) genes = graph.vs[ind][anno_type] return genes
[ "def", "parse_gene_list", "(", "path", ":", "str", ",", "graph", ":", "Graph", ",", "anno_type", ":", "str", "=", "\"name\"", ")", "->", "list", ":", "# read the file", "genes", "=", "pd", ".", "read_csv", "(", "path", ",", "header", "=", "None", ")", "[", "0", "]", ".", "tolist", "(", ")", "genes", "=", "[", "str", "(", "int", "(", "gene", ")", ")", "for", "gene", "in", "genes", "]", "# get those genes which are in the network", "ind", "=", "[", "]", "if", "anno_type", "==", "\"name\"", ":", "ind", "=", "graph", ".", "vs", ".", "select", "(", "name_in", "=", "genes", ")", ".", "indices", "elif", "anno_type", "==", "\"symbol\"", ":", "ind", "=", "graph", ".", "vs", ".", "select", "(", "symbol_in", "=", "genes", ")", ".", "indices", "else", ":", "raise", "Exception", "(", "\"The type can either be name or symbol, {} is not \"", "\"supported\"", ".", "format", "(", "anno_type", ")", ")", "genes", "=", "graph", ".", "vs", "[", "ind", "]", "[", "anno_type", "]", "return", "genes" ]
Parse a list of genes and return them if they are in the network. :param str path: The path of input file. :param Graph graph: The graph with genes as nodes. :param str anno_type: The type of annotation with two options:name-Entrez ID, symbol-HGNC symbol. :return list: A list of genes, all of which are in the network.
[ "Parse", "a", "list", "of", "genes", "and", "return", "them", "if", "they", "are", "in", "the", "network", "." ]
4d7b6713485f2d0a0957e6457edc1b1b5a237460
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/parsers.py#L132-L155
train
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/parsers.py
parse_disease_ids
def parse_disease_ids(path: str): """Parse the disease identifier file. :param str path: Path to the disease identifier file. :return: List of disease identifiers. """ if os.path.isdir(path) or not os.path.exists(path): logger.info("Couldn't find the disease identifiers file. Returning empty list.") return [] df = pd.read_csv(path, names=["ID"]) return set(df["ID"].tolist())
python
def parse_disease_ids(path: str): """Parse the disease identifier file. :param str path: Path to the disease identifier file. :return: List of disease identifiers. """ if os.path.isdir(path) or not os.path.exists(path): logger.info("Couldn't find the disease identifiers file. Returning empty list.") return [] df = pd.read_csv(path, names=["ID"]) return set(df["ID"].tolist())
[ "def", "parse_disease_ids", "(", "path", ":", "str", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", "or", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "logger", ".", "info", "(", "\"Couldn't find the disease identifiers file. Returning empty list.\"", ")", "return", "[", "]", "df", "=", "pd", ".", "read_csv", "(", "path", ",", "names", "=", "[", "\"ID\"", "]", ")", "return", "set", "(", "df", "[", "\"ID\"", "]", ".", "tolist", "(", ")", ")" ]
Parse the disease identifier file. :param str path: Path to the disease identifier file. :return: List of disease identifiers.
[ "Parse", "the", "disease", "identifier", "file", "." ]
4d7b6713485f2d0a0957e6457edc1b1b5a237460
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/parsers.py#L158-L169
train
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/parsers.py
parse_disease_associations
def parse_disease_associations(path: str, excluded_disease_ids: set): """Parse the disease-drug target associations file. :param str path: Path to the disease-drug target associations file. :param list excluded_disease_ids: Identifiers of the disease for which drug targets are being predicted. :return: Dictionary of drug target-disease mappings. """ if os.path.isdir(path) or not os.path.exists(path): logger.info("Couldn't find the disease associations file. Returning empty list.") return {} disease_associations = defaultdict(list) with open(path) as input_file: for line in input_file: target_id, disease_id = line.strip().split(" ") if disease_id not in excluded_disease_ids: disease_associations[target_id].append(disease_id) return disease_associations
python
def parse_disease_associations(path: str, excluded_disease_ids: set): """Parse the disease-drug target associations file. :param str path: Path to the disease-drug target associations file. :param list excluded_disease_ids: Identifiers of the disease for which drug targets are being predicted. :return: Dictionary of drug target-disease mappings. """ if os.path.isdir(path) or not os.path.exists(path): logger.info("Couldn't find the disease associations file. Returning empty list.") return {} disease_associations = defaultdict(list) with open(path) as input_file: for line in input_file: target_id, disease_id = line.strip().split(" ") if disease_id not in excluded_disease_ids: disease_associations[target_id].append(disease_id) return disease_associations
[ "def", "parse_disease_associations", "(", "path", ":", "str", ",", "excluded_disease_ids", ":", "set", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", "or", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "logger", ".", "info", "(", "\"Couldn't find the disease associations file. Returning empty list.\"", ")", "return", "{", "}", "disease_associations", "=", "defaultdict", "(", "list", ")", "with", "open", "(", "path", ")", "as", "input_file", ":", "for", "line", "in", "input_file", ":", "target_id", ",", "disease_id", "=", "line", ".", "strip", "(", ")", ".", "split", "(", "\" \"", ")", "if", "disease_id", "not", "in", "excluded_disease_ids", ":", "disease_associations", "[", "target_id", "]", ".", "append", "(", "disease_id", ")", "return", "disease_associations" ]
Parse the disease-drug target associations file. :param str path: Path to the disease-drug target associations file. :param list excluded_disease_ids: Identifiers of the disease for which drug targets are being predicted. :return: Dictionary of drug target-disease mappings.
[ "Parse", "the", "disease", "-", "drug", "target", "associations", "file", "." ]
4d7b6713485f2d0a0957e6457edc1b1b5a237460
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/parsers.py#L172-L189
train